43b423be4da43d9721750223f31646381fe38b6e
[dotfiles/.git] / typescriptServices.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 "use strict";
17 var __spreadArrays = (this && this.__spreadArrays) || function () {
18     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
19     for (var r = Array(s), k = 0, i = 0; i < il; i++)
20         for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
21             r[k] = a[j];
22     return r;
23 };
24 var __assign = (this && this.__assign) || function () {
25     __assign = Object.assign || function(t) {
26         for (var s, i = 1, n = arguments.length; i < n; i++) {
27             s = arguments[i];
28             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
29                 t[p] = s[p];
30         }
31         return t;
32     };
33     return __assign.apply(this, arguments);
34 };
35 var __generator = (this && this.__generator) || function (thisArg, body) {
36     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
37     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
38     function verb(n) { return function (v) { return step([n, v]); }; }
39     function step(op) {
40         if (f) throw new TypeError("Generator is already executing.");
41         while (_) try {
42             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;
43             if (y = 0, t) op = [op[0] & 2, t.value];
44             switch (op[0]) {
45                 case 0: case 1: t = op; break;
46                 case 4: _.label++; return { value: op[1], done: false };
47                 case 5: _.label++; y = op[1]; op = [0]; continue;
48                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
49                 default:
50                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
51                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
52                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
53                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
54                     if (t[2]) _.ops.pop();
55                     _.trys.pop(); continue;
56             }
57             op = body.call(thisArg, _);
58         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
59         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
60     }
61 };
62 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
63     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
64     return cooked;
65 };
66 var __rest = (this && this.__rest) || function (s, e) {
67     var t = {};
68     for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
69         t[p] = s[p];
70     if (s != null && typeof Object.getOwnPropertySymbols === "function")
71         for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
72             if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
73                 t[p[i]] = s[p[i]];
74         }
75     return t;
76 };
77 var __extends = (this && this.__extends) || (function () {
78     var extendStatics = function (d, b) {
79         extendStatics = Object.setPrototypeOf ||
80             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
81             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
82         return extendStatics(d, b);
83     };
84     return function (d, b) {
85         extendStatics(d, b);
86         function __() { this.constructor = d; }
87         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
88     };
89 })();
90 /* @internal */
91 var ts;
92 (function (ts) {
93     function createMapShim() {
94         /** Create a MapLike with good performance. */
95         function createDictionaryObject() {
96             var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
97             // Using 'delete' on an object causes V8 to put the object in dictionary mode.
98             // This disables creation of hidden classes, which are expensive when an object is
99             // constantly changing shape.
100             map.__ = undefined;
101             delete map.__;
102             return map;
103         }
104         var MapIterator = /** @class */ (function () {
105             function MapIterator(currentEntry, selector) {
106                 this.currentEntry = currentEntry;
107                 this.selector = selector;
108             }
109             MapIterator.prototype.next = function () {
110                 // Navigate to the next entry.
111                 while (this.currentEntry) {
112                     var skipNext = !!this.currentEntry.skipNext;
113                     this.currentEntry = this.currentEntry.nextEntry;
114                     if (!skipNext) {
115                         break;
116                     }
117                 }
118                 if (this.currentEntry) {
119                     return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
120                 }
121                 else {
122                     return { value: undefined, done: true };
123                 }
124             };
125             return MapIterator;
126         }());
127         return /** @class */ (function () {
128             function class_1() {
129                 this.data = createDictionaryObject();
130                 this.size = 0;
131                 // Create a first (stub) map entry that will not contain a key
132                 // and value but serves as starting point for iterators.
133                 this.firstEntry = {};
134                 // When the map is empty, the last entry is the same as the
135                 // first one.
136                 this.lastEntry = this.firstEntry;
137             }
138             class_1.prototype.get = function (key) {
139                 var entry = this.data[key];
140                 return entry && entry.value;
141             };
142             class_1.prototype.set = function (key, value) {
143                 if (!this.has(key)) {
144                     this.size++;
145                     // Create a new entry that will be appended at the
146                     // end of the linked list.
147                     var newEntry = {
148                         key: key,
149                         value: value
150                     };
151                     this.data[key] = newEntry;
152                     // Adjust the references.
153                     var previousLastEntry = this.lastEntry;
154                     previousLastEntry.nextEntry = newEntry;
155                     newEntry.previousEntry = previousLastEntry;
156                     this.lastEntry = newEntry;
157                 }
158                 else {
159                     this.data[key].value = value;
160                 }
161                 return this;
162             };
163             class_1.prototype.has = function (key) {
164                 // eslint-disable-next-line no-in-operator
165                 return key in this.data;
166             };
167             class_1.prototype.delete = function (key) {
168                 if (this.has(key)) {
169                     this.size--;
170                     var entry = this.data[key];
171                     delete this.data[key];
172                     // Adjust the linked list references of the neighbor entries.
173                     var previousEntry = entry.previousEntry;
174                     previousEntry.nextEntry = entry.nextEntry;
175                     if (entry.nextEntry) {
176                         entry.nextEntry.previousEntry = previousEntry;
177                     }
178                     // When the deleted entry was the last one, we need to
179                     // adjust the lastEntry reference.
180                     if (this.lastEntry === entry) {
181                         this.lastEntry = previousEntry;
182                     }
183                     // Adjust the forward reference of the deleted entry
184                     // in case an iterator still references it. This allows us
185                     // to throw away the entry, but when an active iterator
186                     // (which points to the current entry) continues, it will
187                     // navigate to the entry that originally came before the
188                     // current one and skip it.
189                     entry.previousEntry = undefined;
190                     entry.nextEntry = previousEntry;
191                     entry.skipNext = true;
192                     return true;
193                 }
194                 return false;
195             };
196             class_1.prototype.clear = function () {
197                 this.data = createDictionaryObject();
198                 this.size = 0;
199                 // Reset the linked list. Note that we must adjust the forward
200                 // references of the deleted entries to ensure iterators stuck
201                 // in the middle of the list don't continue with deleted entries,
202                 // but can continue with new entries added after the clear()
203                 // operation.
204                 var firstEntry = this.firstEntry;
205                 var currentEntry = firstEntry.nextEntry;
206                 while (currentEntry) {
207                     var nextEntry = currentEntry.nextEntry;
208                     currentEntry.previousEntry = undefined;
209                     currentEntry.nextEntry = firstEntry;
210                     currentEntry.skipNext = true;
211                     currentEntry = nextEntry;
212                 }
213                 firstEntry.nextEntry = undefined;
214                 this.lastEntry = firstEntry;
215             };
216             class_1.prototype.keys = function () {
217                 return new MapIterator(this.firstEntry, function (key) { return key; });
218             };
219             class_1.prototype.values = function () {
220                 return new MapIterator(this.firstEntry, function (_key, value) { return value; });
221             };
222             class_1.prototype.entries = function () {
223                 return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
224             };
225             class_1.prototype.forEach = function (action) {
226                 var iterator = this.entries();
227                 while (true) {
228                     var iterResult = iterator.next();
229                     if (iterResult.done) {
230                         break;
231                     }
232                     var _a = iterResult.value, key = _a[0], value = _a[1];
233                     action(value, key);
234                 }
235             };
236             return class_1;
237         }());
238     }
239     ts.createMapShim = createMapShim;
240 })(ts || (ts = {}));
241 var ts;
242 (function (ts) {
243     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
244     // If changing the text in this section, be sure to test `configurePrerelease` too.
245     ts.versionMajorMinor = "3.9";
246     /** The version of the TypeScript compiler release */
247     ts.version = "3.9.6";
248     /**
249      * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
250      */
251     /* @internal */
252     function tryGetNativeMap() {
253         // eslint-disable-next-line no-in-operator
254         return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
255     }
256     ts.tryGetNativeMap = tryGetNativeMap;
257     /* @internal */
258     ts.Map = tryGetNativeMap() || (function () {
259         // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
260         if (typeof ts.createMapShim === "function") {
261             return ts.createMapShim();
262         }
263         throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
264     })();
265     /* @internal */
266     var Comparison;
267     (function (Comparison) {
268         Comparison[Comparison["LessThan"] = -1] = "LessThan";
269         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
270         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
271     })(Comparison = ts.Comparison || (ts.Comparison = {}));
272 })(ts || (ts = {}));
273 /* @internal */
274 var ts;
275 (function (ts) {
276     ts.emptyArray = [];
277     /** Create a new map. */
278     function createMap() {
279         return new ts.Map();
280     }
281     ts.createMap = createMap;
282     /** Create a new map from an array of entries. */
283     function createMapFromEntries(entries) {
284         var map = createMap();
285         for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
286             var _a = entries_1[_i], key = _a[0], value = _a[1];
287             map.set(key, value);
288         }
289         return map;
290     }
291     ts.createMapFromEntries = createMapFromEntries;
292     /** Create a new map from a template object is provided, the map will copy entries from it. */
293     function createMapFromTemplate(template) {
294         var map = new ts.Map();
295         // Copies keys/values from template. Note that for..in will not throw if
296         // template is undefined, and instead will just exit the loop.
297         for (var key in template) {
298             if (hasOwnProperty.call(template, key)) {
299                 map.set(key, template[key]);
300             }
301         }
302         return map;
303     }
304     ts.createMapFromTemplate = createMapFromTemplate;
305     function length(array) {
306         return array ? array.length : 0;
307     }
308     ts.length = length;
309     /**
310      * Iterates through 'array' by index and performs the callback on each element of array until the callback
311      * returns a truthy value, then returns that value.
312      * If no such value is found, the callback is applied to each element of array and undefined is returned.
313      */
314     function forEach(array, callback) {
315         if (array) {
316             for (var i = 0; i < array.length; i++) {
317                 var result = callback(array[i], i);
318                 if (result) {
319                     return result;
320                 }
321             }
322         }
323         return undefined;
324     }
325     ts.forEach = forEach;
326     /**
327      * Like `forEach`, but iterates in reverse order.
328      */
329     function forEachRight(array, callback) {
330         if (array) {
331             for (var i = array.length - 1; i >= 0; i--) {
332                 var result = callback(array[i], i);
333                 if (result) {
334                     return result;
335                 }
336             }
337         }
338         return undefined;
339     }
340     ts.forEachRight = forEachRight;
341     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
342     function firstDefined(array, callback) {
343         if (array === undefined) {
344             return undefined;
345         }
346         for (var i = 0; i < array.length; i++) {
347             var result = callback(array[i], i);
348             if (result !== undefined) {
349                 return result;
350             }
351         }
352         return undefined;
353     }
354     ts.firstDefined = firstDefined;
355     function firstDefinedIterator(iter, callback) {
356         while (true) {
357             var iterResult = iter.next();
358             if (iterResult.done) {
359                 return undefined;
360             }
361             var result = callback(iterResult.value);
362             if (result !== undefined) {
363                 return result;
364             }
365         }
366     }
367     ts.firstDefinedIterator = firstDefinedIterator;
368     function zipWith(arrayA, arrayB, callback) {
369         var result = [];
370         ts.Debug.assertEqual(arrayA.length, arrayB.length);
371         for (var i = 0; i < arrayA.length; i++) {
372             result.push(callback(arrayA[i], arrayB[i], i));
373         }
374         return result;
375     }
376     ts.zipWith = zipWith;
377     function zipToIterator(arrayA, arrayB) {
378         ts.Debug.assertEqual(arrayA.length, arrayB.length);
379         var i = 0;
380         return {
381             next: function () {
382                 if (i === arrayA.length) {
383                     return { value: undefined, done: true };
384                 }
385                 i++;
386                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
387             }
388         };
389     }
390     ts.zipToIterator = zipToIterator;
391     function zipToMap(keys, values) {
392         ts.Debug.assert(keys.length === values.length);
393         var map = createMap();
394         for (var i = 0; i < keys.length; ++i) {
395             map.set(keys[i], values[i]);
396         }
397         return map;
398     }
399     ts.zipToMap = zipToMap;
400     /**
401      * Iterates through `array` by index and performs the callback on each element of array until the callback
402      * returns a falsey value, then returns false.
403      * If no such value is found, the callback is applied to each element of array and `true` is returned.
404      */
405     function every(array, callback) {
406         if (array) {
407             for (var i = 0; i < array.length; i++) {
408                 if (!callback(array[i], i)) {
409                     return false;
410                 }
411             }
412         }
413         return true;
414     }
415     ts.every = every;
416     function find(array, predicate) {
417         for (var i = 0; i < array.length; i++) {
418             var value = array[i];
419             if (predicate(value, i)) {
420                 return value;
421             }
422         }
423         return undefined;
424     }
425     ts.find = find;
426     function findLast(array, predicate) {
427         for (var i = array.length - 1; i >= 0; i--) {
428             var value = array[i];
429             if (predicate(value, i)) {
430                 return value;
431             }
432         }
433         return undefined;
434     }
435     ts.findLast = findLast;
436     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
437     function findIndex(array, predicate, startIndex) {
438         for (var i = startIndex || 0; i < array.length; i++) {
439             if (predicate(array[i], i)) {
440                 return i;
441             }
442         }
443         return -1;
444     }
445     ts.findIndex = findIndex;
446     function findLastIndex(array, predicate, startIndex) {
447         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
448             if (predicate(array[i], i)) {
449                 return i;
450             }
451         }
452         return -1;
453     }
454     ts.findLastIndex = findLastIndex;
455     /**
456      * Returns the first truthy result of `callback`, or else fails.
457      * This is like `forEach`, but never returns undefined.
458      */
459     function findMap(array, callback) {
460         for (var i = 0; i < array.length; i++) {
461             var result = callback(array[i], i);
462             if (result) {
463                 return result;
464             }
465         }
466         return ts.Debug.fail();
467     }
468     ts.findMap = findMap;
469     function contains(array, value, equalityComparer) {
470         if (equalityComparer === void 0) { equalityComparer = equateValues; }
471         if (array) {
472             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
473                 var v = array_1[_i];
474                 if (equalityComparer(v, value)) {
475                     return true;
476                 }
477             }
478         }
479         return false;
480     }
481     ts.contains = contains;
482     function arraysEqual(a, b, equalityComparer) {
483         if (equalityComparer === void 0) { equalityComparer = equateValues; }
484         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
485     }
486     ts.arraysEqual = arraysEqual;
487     function indexOfAnyCharCode(text, charCodes, start) {
488         for (var i = start || 0; i < text.length; i++) {
489             if (contains(charCodes, text.charCodeAt(i))) {
490                 return i;
491             }
492         }
493         return -1;
494     }
495     ts.indexOfAnyCharCode = indexOfAnyCharCode;
496     function countWhere(array, predicate) {
497         var count = 0;
498         if (array) {
499             for (var i = 0; i < array.length; i++) {
500                 var v = array[i];
501                 if (predicate(v, i)) {
502                     count++;
503                 }
504             }
505         }
506         return count;
507     }
508     ts.countWhere = countWhere;
509     function filter(array, f) {
510         if (array) {
511             var len = array.length;
512             var i = 0;
513             while (i < len && f(array[i]))
514                 i++;
515             if (i < len) {
516                 var result = array.slice(0, i);
517                 i++;
518                 while (i < len) {
519                     var item = array[i];
520                     if (f(item)) {
521                         result.push(item);
522                     }
523                     i++;
524                 }
525                 return result;
526             }
527         }
528         return array;
529     }
530     ts.filter = filter;
531     function filterMutate(array, f) {
532         var outIndex = 0;
533         for (var i = 0; i < array.length; i++) {
534             if (f(array[i], i, array)) {
535                 array[outIndex] = array[i];
536                 outIndex++;
537             }
538         }
539         array.length = outIndex;
540     }
541     ts.filterMutate = filterMutate;
542     function clear(array) {
543         array.length = 0;
544     }
545     ts.clear = clear;
546     function map(array, f) {
547         var result;
548         if (array) {
549             result = [];
550             for (var i = 0; i < array.length; i++) {
551                 result.push(f(array[i], i));
552             }
553         }
554         return result;
555     }
556     ts.map = map;
557     function mapIterator(iter, mapFn) {
558         return {
559             next: function () {
560                 var iterRes = iter.next();
561                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
562             }
563         };
564     }
565     ts.mapIterator = mapIterator;
566     function sameMap(array, f) {
567         if (array) {
568             for (var i = 0; i < array.length; i++) {
569                 var item = array[i];
570                 var mapped = f(item, i);
571                 if (item !== mapped) {
572                     var result = array.slice(0, i);
573                     result.push(mapped);
574                     for (i++; i < array.length; i++) {
575                         result.push(f(array[i], i));
576                     }
577                     return result;
578                 }
579             }
580         }
581         return array;
582     }
583     ts.sameMap = sameMap;
584     /**
585      * Flattens an array containing a mix of array or non-array elements.
586      *
587      * @param array The array to flatten.
588      */
589     function flatten(array) {
590         var result = [];
591         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
592             var v = array_2[_i];
593             if (v) {
594                 if (isArray(v)) {
595                     addRange(result, v);
596                 }
597                 else {
598                     result.push(v);
599                 }
600             }
601         }
602         return result;
603     }
604     ts.flatten = flatten;
605     /**
606      * Maps an array. If the mapped value is an array, it is spread into the result.
607      *
608      * @param array The array to map.
609      * @param mapfn The callback used to map the result into one or more values.
610      */
611     function flatMap(array, mapfn) {
612         var result;
613         if (array) {
614             for (var i = 0; i < array.length; i++) {
615                 var v = mapfn(array[i], i);
616                 if (v) {
617                     if (isArray(v)) {
618                         result = addRange(result, v);
619                     }
620                     else {
621                         result = append(result, v);
622                     }
623                 }
624             }
625         }
626         return result || ts.emptyArray;
627     }
628     ts.flatMap = flatMap;
629     function flatMapToMutable(array, mapfn) {
630         var result = [];
631         if (array) {
632             for (var i = 0; i < array.length; i++) {
633                 var v = mapfn(array[i], i);
634                 if (v) {
635                     if (isArray(v)) {
636                         addRange(result, v);
637                     }
638                     else {
639                         result.push(v);
640                     }
641                 }
642             }
643         }
644         return result;
645     }
646     ts.flatMapToMutable = flatMapToMutable;
647     function flatMapIterator(iter, mapfn) {
648         var first = iter.next();
649         if (first.done) {
650             return ts.emptyIterator;
651         }
652         var currentIter = getIterator(first.value);
653         return {
654             next: function () {
655                 while (true) {
656                     var currentRes = currentIter.next();
657                     if (!currentRes.done) {
658                         return currentRes;
659                     }
660                     var iterRes = iter.next();
661                     if (iterRes.done) {
662                         return iterRes;
663                     }
664                     currentIter = getIterator(iterRes.value);
665                 }
666             },
667         };
668         function getIterator(x) {
669             var res = mapfn(x);
670             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
671         }
672     }
673     ts.flatMapIterator = flatMapIterator;
674     function sameFlatMap(array, mapfn) {
675         var result;
676         if (array) {
677             for (var i = 0; i < array.length; i++) {
678                 var item = array[i];
679                 var mapped = mapfn(item, i);
680                 if (result || item !== mapped || isArray(mapped)) {
681                     if (!result) {
682                         result = array.slice(0, i);
683                     }
684                     if (isArray(mapped)) {
685                         addRange(result, mapped);
686                     }
687                     else {
688                         result.push(mapped);
689                     }
690                 }
691             }
692         }
693         return result || array;
694     }
695     ts.sameFlatMap = sameFlatMap;
696     function mapAllOrFail(array, mapFn) {
697         var result = [];
698         for (var i = 0; i < array.length; i++) {
699             var mapped = mapFn(array[i], i);
700             if (mapped === undefined) {
701                 return undefined;
702             }
703             result.push(mapped);
704         }
705         return result;
706     }
707     ts.mapAllOrFail = mapAllOrFail;
708     function mapDefined(array, mapFn) {
709         var result = [];
710         if (array) {
711             for (var i = 0; i < array.length; i++) {
712                 var mapped = mapFn(array[i], i);
713                 if (mapped !== undefined) {
714                     result.push(mapped);
715                 }
716             }
717         }
718         return result;
719     }
720     ts.mapDefined = mapDefined;
721     function mapDefinedIterator(iter, mapFn) {
722         return {
723             next: function () {
724                 while (true) {
725                     var res = iter.next();
726                     if (res.done) {
727                         return res;
728                     }
729                     var value = mapFn(res.value);
730                     if (value !== undefined) {
731                         return { value: value, done: false };
732                     }
733                 }
734             }
735         };
736     }
737     ts.mapDefinedIterator = mapDefinedIterator;
738     function mapDefinedMap(map, mapValue, mapKey) {
739         if (mapKey === void 0) { mapKey = identity; }
740         var result = createMap();
741         map.forEach(function (value, key) {
742             var mapped = mapValue(value, key);
743             if (mapped !== undefined) {
744                 result.set(mapKey(key), mapped);
745             }
746         });
747         return result;
748     }
749     ts.mapDefinedMap = mapDefinedMap;
750     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
751     function singleIterator(value) {
752         var done = false;
753         return {
754             next: function () {
755                 var wasDone = done;
756                 done = true;
757                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
758             }
759         };
760     }
761     ts.singleIterator = singleIterator;
762     function spanMap(array, keyfn, mapfn) {
763         var result;
764         if (array) {
765             result = [];
766             var len = array.length;
767             var previousKey = void 0;
768             var key = void 0;
769             var start = 0;
770             var pos = 0;
771             while (start < len) {
772                 while (pos < len) {
773                     var value = array[pos];
774                     key = keyfn(value, pos);
775                     if (pos === 0) {
776                         previousKey = key;
777                     }
778                     else if (key !== previousKey) {
779                         break;
780                     }
781                     pos++;
782                 }
783                 if (start < pos) {
784                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
785                     if (v) {
786                         result.push(v);
787                     }
788                     start = pos;
789                 }
790                 previousKey = key;
791                 pos++;
792             }
793         }
794         return result;
795     }
796     ts.spanMap = spanMap;
797     function mapEntries(map, f) {
798         if (!map) {
799             return undefined;
800         }
801         var result = createMap();
802         map.forEach(function (value, key) {
803             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
804             result.set(newKey, newValue);
805         });
806         return result;
807     }
808     ts.mapEntries = mapEntries;
809     function some(array, predicate) {
810         if (array) {
811             if (predicate) {
812                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
813                     var v = array_3[_i];
814                     if (predicate(v)) {
815                         return true;
816                     }
817                 }
818             }
819             else {
820                 return array.length > 0;
821             }
822         }
823         return false;
824     }
825     ts.some = some;
826     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
827     function getRangesWhere(arr, pred, cb) {
828         var start;
829         for (var i = 0; i < arr.length; i++) {
830             if (pred(arr[i])) {
831                 start = start === undefined ? i : start;
832             }
833             else {
834                 if (start !== undefined) {
835                     cb(start, i);
836                     start = undefined;
837                 }
838             }
839         }
840         if (start !== undefined)
841             cb(start, arr.length);
842     }
843     ts.getRangesWhere = getRangesWhere;
844     function concatenate(array1, array2) {
845         if (!some(array2))
846             return array1;
847         if (!some(array1))
848             return array2;
849         return __spreadArrays(array1, array2);
850     }
851     ts.concatenate = concatenate;
852     function selectIndex(_, i) {
853         return i;
854     }
855     function indicesOf(array) {
856         return array.map(selectIndex);
857     }
858     ts.indicesOf = indicesOf;
859     function deduplicateRelational(array, equalityComparer, comparer) {
860         // Perform a stable sort of the array. This ensures the first entry in a list of
861         // duplicates remains the first entry in the result.
862         var indices = indicesOf(array);
863         stableSortIndices(array, indices, comparer);
864         var last = array[indices[0]];
865         var deduplicated = [indices[0]];
866         for (var i = 1; i < indices.length; i++) {
867             var index = indices[i];
868             var item = array[index];
869             if (!equalityComparer(last, item)) {
870                 deduplicated.push(index);
871                 last = item;
872             }
873         }
874         // restore original order
875         deduplicated.sort();
876         return deduplicated.map(function (i) { return array[i]; });
877     }
878     function deduplicateEquality(array, equalityComparer) {
879         var result = [];
880         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
881             var item = array_4[_i];
882             pushIfUnique(result, item, equalityComparer);
883         }
884         return result;
885     }
886     /**
887      * Deduplicates an unsorted array.
888      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
889      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
890      * result will remain in the original order in `array`.
891      */
892     function deduplicate(array, equalityComparer, comparer) {
893         return array.length === 0 ? [] :
894             array.length === 1 ? array.slice() :
895                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
896                     deduplicateEquality(array, equalityComparer);
897     }
898     ts.deduplicate = deduplicate;
899     /**
900      * Deduplicates an array that has already been sorted.
901      */
902     function deduplicateSorted(array, comparer) {
903         if (array.length === 0)
904             return ts.emptyArray;
905         var last = array[0];
906         var deduplicated = [last];
907         for (var i = 1; i < array.length; i++) {
908             var next = array[i];
909             switch (comparer(next, last)) {
910                 // equality comparison
911                 case true:
912                 // relational comparison
913                 // falls through
914                 case 0 /* EqualTo */:
915                     continue;
916                 case -1 /* LessThan */:
917                     // If `array` is sorted, `next` should **never** be less than `last`.
918                     return ts.Debug.fail("Array is unsorted.");
919             }
920             deduplicated.push(last = next);
921         }
922         return deduplicated;
923     }
924     function insertSorted(array, insert, compare) {
925         if (array.length === 0) {
926             array.push(insert);
927             return;
928         }
929         var insertIndex = binarySearch(array, insert, identity, compare);
930         if (insertIndex < 0) {
931             array.splice(~insertIndex, 0, insert);
932         }
933     }
934     ts.insertSorted = insertSorted;
935     function sortAndDeduplicate(array, comparer, equalityComparer) {
936         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
937     }
938     ts.sortAndDeduplicate = sortAndDeduplicate;
939     function arrayIsEqualTo(array1, array2, equalityComparer) {
940         if (equalityComparer === void 0) { equalityComparer = equateValues; }
941         if (!array1 || !array2) {
942             return array1 === array2;
943         }
944         if (array1.length !== array2.length) {
945             return false;
946         }
947         for (var i = 0; i < array1.length; i++) {
948             if (!equalityComparer(array1[i], array2[i], i)) {
949                 return false;
950             }
951         }
952         return true;
953     }
954     ts.arrayIsEqualTo = arrayIsEqualTo;
955     function compact(array) {
956         var result;
957         if (array) {
958             for (var i = 0; i < array.length; i++) {
959                 var v = array[i];
960                 if (result || !v) {
961                     if (!result) {
962                         result = array.slice(0, i);
963                     }
964                     if (v) {
965                         result.push(v);
966                     }
967                 }
968             }
969         }
970         return result || array;
971     }
972     ts.compact = compact;
973     /**
974      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
975      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
976      * based on the provided comparer.
977      */
978     function relativeComplement(arrayA, arrayB, comparer) {
979         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
980             return arrayB;
981         var result = [];
982         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
983             if (offsetB > 0) {
984                 // Ensure `arrayB` is properly sorted.
985                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
986             }
987             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
988                 if (offsetA > startA) {
989                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
990                     // `offsetA` has changed since we entered the loop.
991                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
992                 }
993                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
994                     case -1 /* LessThan */:
995                         // If B is less than A, B does not exist in arrayA. Add B to the result and
996                         // move to the next element in arrayB without changing the current position
997                         // in arrayA.
998                         result.push(arrayB[offsetB]);
999                         continue loopB;
1000                     case 0 /* EqualTo */:
1001                         // If B is equal to A, B exists in arrayA. Move to the next element in
1002                         // arrayB without adding B to the result or changing the current position
1003                         // in arrayA.
1004                         continue loopB;
1005                     case 1 /* GreaterThan */:
1006                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
1007                         // the next element in arrayA and recheck.
1008                         continue loopA;
1009                 }
1010             }
1011         }
1012         return result;
1013     }
1014     ts.relativeComplement = relativeComplement;
1015     function sum(array, prop) {
1016         var result = 0;
1017         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
1018             var v = array_5[_i];
1019             result += v[prop];
1020         }
1021         return result;
1022     }
1023     ts.sum = sum;
1024     function append(to, value) {
1025         if (value === undefined)
1026             return to;
1027         if (to === undefined)
1028             return [value];
1029         to.push(value);
1030         return to;
1031     }
1032     ts.append = append;
1033     function combine(xs, ys) {
1034         if (xs === undefined)
1035             return ys;
1036         if (ys === undefined)
1037             return xs;
1038         if (isArray(xs))
1039             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
1040         if (isArray(ys))
1041             return append(ys, xs);
1042         return [xs, ys];
1043     }
1044     ts.combine = combine;
1045     /**
1046      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
1047      * position offset from the end of the array.
1048      */
1049     function toOffset(array, offset) {
1050         return offset < 0 ? array.length + offset : offset;
1051     }
1052     function addRange(to, from, start, end) {
1053         if (from === undefined || from.length === 0)
1054             return to;
1055         if (to === undefined)
1056             return from.slice(start, end);
1057         start = start === undefined ? 0 : toOffset(from, start);
1058         end = end === undefined ? from.length : toOffset(from, end);
1059         for (var i = start; i < end && i < from.length; i++) {
1060             if (from[i] !== undefined) {
1061                 to.push(from[i]);
1062             }
1063         }
1064         return to;
1065     }
1066     ts.addRange = addRange;
1067     /**
1068      * @return Whether the value was added.
1069      */
1070     function pushIfUnique(array, toAdd, equalityComparer) {
1071         if (contains(array, toAdd, equalityComparer)) {
1072             return false;
1073         }
1074         else {
1075             array.push(toAdd);
1076             return true;
1077         }
1078     }
1079     ts.pushIfUnique = pushIfUnique;
1080     /**
1081      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
1082      */
1083     function appendIfUnique(array, toAdd, equalityComparer) {
1084         if (array) {
1085             pushIfUnique(array, toAdd, equalityComparer);
1086             return array;
1087         }
1088         else {
1089             return [toAdd];
1090         }
1091     }
1092     ts.appendIfUnique = appendIfUnique;
1093     function stableSortIndices(array, indices, comparer) {
1094         // sort indices by value then position
1095         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
1096     }
1097     /**
1098      * Returns a new sorted array.
1099      */
1100     function sort(array, comparer) {
1101         return (array.length === 0 ? array : array.slice().sort(comparer));
1102     }
1103     ts.sort = sort;
1104     function arrayIterator(array) {
1105         var i = 0;
1106         return { next: function () {
1107                 if (i === array.length) {
1108                     return { value: undefined, done: true };
1109                 }
1110                 else {
1111                     i++;
1112                     return { value: array[i - 1], done: false };
1113                 }
1114             } };
1115     }
1116     ts.arrayIterator = arrayIterator;
1117     function arrayReverseIterator(array) {
1118         var i = array.length;
1119         return {
1120             next: function () {
1121                 if (i === 0) {
1122                     return { value: undefined, done: true };
1123                 }
1124                 else {
1125                     i--;
1126                     return { value: array[i], done: false };
1127                 }
1128             }
1129         };
1130     }
1131     ts.arrayReverseIterator = arrayReverseIterator;
1132     /**
1133      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
1134      */
1135     function stableSort(array, comparer) {
1136         var indices = indicesOf(array);
1137         stableSortIndices(array, indices, comparer);
1138         return indices.map(function (i) { return array[i]; });
1139     }
1140     ts.stableSort = stableSort;
1141     function rangeEquals(array1, array2, pos, end) {
1142         while (pos < end) {
1143             if (array1[pos] !== array2[pos]) {
1144                 return false;
1145             }
1146             pos++;
1147         }
1148         return true;
1149     }
1150     ts.rangeEquals = rangeEquals;
1151     /**
1152      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1153      * A negative offset indicates the element should be retrieved from the end of the array.
1154      */
1155     function elementAt(array, offset) {
1156         if (array) {
1157             offset = toOffset(array, offset);
1158             if (offset < array.length) {
1159                 return array[offset];
1160             }
1161         }
1162         return undefined;
1163     }
1164     ts.elementAt = elementAt;
1165     /**
1166      * Returns the first element of an array if non-empty, `undefined` otherwise.
1167      */
1168     function firstOrUndefined(array) {
1169         return array.length === 0 ? undefined : array[0];
1170     }
1171     ts.firstOrUndefined = firstOrUndefined;
1172     function first(array) {
1173         ts.Debug.assert(array.length !== 0);
1174         return array[0];
1175     }
1176     ts.first = first;
1177     /**
1178      * Returns the last element of an array if non-empty, `undefined` otherwise.
1179      */
1180     function lastOrUndefined(array) {
1181         return array.length === 0 ? undefined : array[array.length - 1];
1182     }
1183     ts.lastOrUndefined = lastOrUndefined;
1184     function last(array) {
1185         ts.Debug.assert(array.length !== 0);
1186         return array[array.length - 1];
1187     }
1188     ts.last = last;
1189     /**
1190      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1191      */
1192     function singleOrUndefined(array) {
1193         return array && array.length === 1
1194             ? array[0]
1195             : undefined;
1196     }
1197     ts.singleOrUndefined = singleOrUndefined;
1198     function singleOrMany(array) {
1199         return array && array.length === 1
1200             ? array[0]
1201             : array;
1202     }
1203     ts.singleOrMany = singleOrMany;
1204     function replaceElement(array, index, value) {
1205         var result = array.slice(0);
1206         result[index] = value;
1207         return result;
1208     }
1209     ts.replaceElement = replaceElement;
1210     /**
1211      * Performs a binary search, finding the index at which `value` occurs in `array`.
1212      * If no such index is found, returns the 2's-complement of first index at which
1213      * `array[index]` exceeds `value`.
1214      * @param array A sorted array whose first element must be no larger than number
1215      * @param value The value to be searched for in the array.
1216      * @param keySelector A callback used to select the search key from `value` and each element of
1217      * `array`.
1218      * @param keyComparer A callback used to compare two keys in a sorted array.
1219      * @param offset An offset into `array` at which to start the search.
1220      */
1221     function binarySearch(array, value, keySelector, keyComparer, offset) {
1222         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1223     }
1224     ts.binarySearch = binarySearch;
1225     /**
1226      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1227      * If no such index is found, returns the 2's-complement of first index at which
1228      * `array[index]` exceeds `key`.
1229      * @param array A sorted array whose first element must be no larger than number
1230      * @param key The key to be searched for in the array.
1231      * @param keySelector A callback used to select the search key from each element of `array`.
1232      * @param keyComparer A callback used to compare two keys in a sorted array.
1233      * @param offset An offset into `array` at which to start the search.
1234      */
1235     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1236         if (!some(array)) {
1237             return -1;
1238         }
1239         var low = offset || 0;
1240         var high = array.length - 1;
1241         while (low <= high) {
1242             var middle = low + ((high - low) >> 1);
1243             var midKey = keySelector(array[middle]);
1244             switch (keyComparer(midKey, key)) {
1245                 case -1 /* LessThan */:
1246                     low = middle + 1;
1247                     break;
1248                 case 0 /* EqualTo */:
1249                     return middle;
1250                 case 1 /* GreaterThan */:
1251                     high = middle - 1;
1252                     break;
1253             }
1254         }
1255         return ~low;
1256     }
1257     ts.binarySearchKey = binarySearchKey;
1258     function reduceLeft(array, f, initial, start, count) {
1259         if (array && array.length > 0) {
1260             var size = array.length;
1261             if (size > 0) {
1262                 var pos = start === undefined || start < 0 ? 0 : start;
1263                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1264                 var result = void 0;
1265                 if (arguments.length <= 2) {
1266                     result = array[pos];
1267                     pos++;
1268                 }
1269                 else {
1270                     result = initial;
1271                 }
1272                 while (pos <= end) {
1273                     result = f(result, array[pos], pos);
1274                     pos++;
1275                 }
1276                 return result;
1277             }
1278         }
1279         return initial;
1280     }
1281     ts.reduceLeft = reduceLeft;
1282     var hasOwnProperty = Object.prototype.hasOwnProperty;
1283     /**
1284      * Indicates whether a map-like contains an own property with the specified key.
1285      *
1286      * @param map A map-like.
1287      * @param key A property key.
1288      */
1289     function hasProperty(map, key) {
1290         return hasOwnProperty.call(map, key);
1291     }
1292     ts.hasProperty = hasProperty;
1293     /**
1294      * Gets the value of an owned property in a map-like.
1295      *
1296      * @param map A map-like.
1297      * @param key A property key.
1298      */
1299     function getProperty(map, key) {
1300         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1301     }
1302     ts.getProperty = getProperty;
1303     /**
1304      * Gets the owned, enumerable property keys of a map-like.
1305      */
1306     function getOwnKeys(map) {
1307         var keys = [];
1308         for (var key in map) {
1309             if (hasOwnProperty.call(map, key)) {
1310                 keys.push(key);
1311             }
1312         }
1313         return keys;
1314     }
1315     ts.getOwnKeys = getOwnKeys;
1316     function getAllKeys(obj) {
1317         var result = [];
1318         do {
1319             var names = Object.getOwnPropertyNames(obj);
1320             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1321                 var name = names_1[_i];
1322                 pushIfUnique(result, name);
1323             }
1324         } while (obj = Object.getPrototypeOf(obj));
1325         return result;
1326     }
1327     ts.getAllKeys = getAllKeys;
1328     function getOwnValues(sparseArray) {
1329         var values = [];
1330         for (var key in sparseArray) {
1331             if (hasOwnProperty.call(sparseArray, key)) {
1332                 values.push(sparseArray[key]);
1333             }
1334         }
1335         return values;
1336     }
1337     ts.getOwnValues = getOwnValues;
1338     function arrayFrom(iterator, map) {
1339         var result = [];
1340         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1341             result.push(map ? map(iterResult.value) : iterResult.value);
1342         }
1343         return result;
1344     }
1345     ts.arrayFrom = arrayFrom;
1346     function assign(t) {
1347         var args = [];
1348         for (var _i = 1; _i < arguments.length; _i++) {
1349             args[_i - 1] = arguments[_i];
1350         }
1351         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1352             var arg = args_1[_a];
1353             if (arg === undefined)
1354                 continue;
1355             for (var p in arg) {
1356                 if (hasProperty(arg, p)) {
1357                     t[p] = arg[p];
1358                 }
1359             }
1360         }
1361         return t;
1362     }
1363     ts.assign = assign;
1364     /**
1365      * Performs a shallow equality comparison of the contents of two map-likes.
1366      *
1367      * @param left A map-like whose properties should be compared.
1368      * @param right A map-like whose properties should be compared.
1369      */
1370     function equalOwnProperties(left, right, equalityComparer) {
1371         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1372         if (left === right)
1373             return true;
1374         if (!left || !right)
1375             return false;
1376         for (var key in left) {
1377             if (hasOwnProperty.call(left, key)) {
1378                 if (!hasOwnProperty.call(right, key))
1379                     return false;
1380                 if (!equalityComparer(left[key], right[key]))
1381                     return false;
1382             }
1383         }
1384         for (var key in right) {
1385             if (hasOwnProperty.call(right, key)) {
1386                 if (!hasOwnProperty.call(left, key))
1387                     return false;
1388             }
1389         }
1390         return true;
1391     }
1392     ts.equalOwnProperties = equalOwnProperties;
1393     function arrayToMap(array, makeKey, makeValue) {
1394         if (makeValue === void 0) { makeValue = identity; }
1395         var result = createMap();
1396         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1397             var value = array_6[_i];
1398             var key = makeKey(value);
1399             if (key !== undefined)
1400                 result.set(key, makeValue(value));
1401         }
1402         return result;
1403     }
1404     ts.arrayToMap = arrayToMap;
1405     function arrayToNumericMap(array, makeKey, makeValue) {
1406         if (makeValue === void 0) { makeValue = identity; }
1407         var result = [];
1408         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1409             var value = array_7[_i];
1410             result[makeKey(value)] = makeValue(value);
1411         }
1412         return result;
1413     }
1414     ts.arrayToNumericMap = arrayToNumericMap;
1415     function arrayToMultiMap(values, makeKey, makeValue) {
1416         if (makeValue === void 0) { makeValue = identity; }
1417         var result = createMultiMap();
1418         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1419             var value = values_1[_i];
1420             result.add(makeKey(value), makeValue(value));
1421         }
1422         return result;
1423     }
1424     ts.arrayToMultiMap = arrayToMultiMap;
1425     function group(values, getGroupId, resultSelector) {
1426         if (resultSelector === void 0) { resultSelector = identity; }
1427         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1428     }
1429     ts.group = group;
1430     function clone(object) {
1431         var result = {};
1432         for (var id in object) {
1433             if (hasOwnProperty.call(object, id)) {
1434                 result[id] = object[id];
1435             }
1436         }
1437         return result;
1438     }
1439     ts.clone = clone;
1440     /**
1441      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1442      *
1443      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1444      */
1445     function extend(first, second) {
1446         var result = {};
1447         for (var id in second) {
1448             if (hasOwnProperty.call(second, id)) {
1449                 result[id] = second[id];
1450             }
1451         }
1452         for (var id in first) {
1453             if (hasOwnProperty.call(first, id)) {
1454                 result[id] = first[id];
1455             }
1456         }
1457         return result;
1458     }
1459     ts.extend = extend;
1460     function copyProperties(first, second) {
1461         for (var id in second) {
1462             if (hasOwnProperty.call(second, id)) {
1463                 first[id] = second[id];
1464             }
1465         }
1466     }
1467     ts.copyProperties = copyProperties;
1468     function maybeBind(obj, fn) {
1469         return fn ? fn.bind(obj) : undefined;
1470     }
1471     ts.maybeBind = maybeBind;
1472     function mapMap(map, f) {
1473         var result = createMap();
1474         map.forEach(function (t, key) { return result.set.apply(result, (f(t, key))); });
1475         return result;
1476     }
1477     ts.mapMap = mapMap;
1478     function createMultiMap() {
1479         var map = createMap();
1480         map.add = multiMapAdd;
1481         map.remove = multiMapRemove;
1482         return map;
1483     }
1484     ts.createMultiMap = createMultiMap;
1485     function multiMapAdd(key, value) {
1486         var values = this.get(key);
1487         if (values) {
1488             values.push(value);
1489         }
1490         else {
1491             this.set(key, values = [value]);
1492         }
1493         return values;
1494     }
1495     function multiMapRemove(key, value) {
1496         var values = this.get(key);
1497         if (values) {
1498             unorderedRemoveItem(values, value);
1499             if (!values.length) {
1500                 this.delete(key);
1501             }
1502         }
1503     }
1504     function createUnderscoreEscapedMultiMap() {
1505         return createMultiMap();
1506     }
1507     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1508     /**
1509      * Tests whether a value is an array.
1510      */
1511     function isArray(value) {
1512         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1513     }
1514     ts.isArray = isArray;
1515     function toArray(value) {
1516         return isArray(value) ? value : [value];
1517     }
1518     ts.toArray = toArray;
1519     /**
1520      * Tests whether a value is string
1521      */
1522     function isString(text) {
1523         return typeof text === "string";
1524     }
1525     ts.isString = isString;
1526     function isNumber(x) {
1527         return typeof x === "number";
1528     }
1529     ts.isNumber = isNumber;
1530     function tryCast(value, test) {
1531         return value !== undefined && test(value) ? value : undefined;
1532     }
1533     ts.tryCast = tryCast;
1534     function cast(value, test) {
1535         if (value !== undefined && test(value))
1536             return value;
1537         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1538     }
1539     ts.cast = cast;
1540     /** Does nothing. */
1541     function noop(_) { }
1542     ts.noop = noop;
1543     /** Do nothing and return false */
1544     function returnFalse() { return false; }
1545     ts.returnFalse = returnFalse;
1546     /** Do nothing and return true */
1547     function returnTrue() { return true; }
1548     ts.returnTrue = returnTrue;
1549     /** Do nothing and return undefined */
1550     function returnUndefined() { return undefined; }
1551     ts.returnUndefined = returnUndefined;
1552     /** Returns its argument. */
1553     function identity(x) { return x; }
1554     ts.identity = identity;
1555     /** Returns lower case string */
1556     function toLowerCase(x) { return x.toLowerCase(); }
1557     ts.toLowerCase = toLowerCase;
1558     // We convert the file names to lower case as key for file name on case insensitive file system
1559     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1560     // it to lower case, fileName with its lowercase form can exist along side it.
1561     // Handle special characters and make those case sensitive instead
1562     //
1563     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1564     // | 1. | i        | 105       | Ascii i                                                                |
1565     // | 2. | I        | 73        | Ascii I                                                                |
1566     // |-------- Special characters ------------------------------------------------------------------------|
1567     // | 3. | \u0130   | 304       | Uppper case I with dot above                                           |
1568     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1569     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1570     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1571     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1572     //
1573     // Because item 3 is special where in its lowercase character has its own
1574     // upper case form we cant convert its case.
1575     // Rest special characters are either already in lower case format or
1576     // they have corresponding upper case character so they dont need special handling
1577     //
1578     // But to avoid having to do string building for most common cases, also ignore
1579     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1580     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1581     /**
1582      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1583      * This function is used in places where we want to make file name as a key on these systems
1584      * 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
1585      * 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
1586      * Technically we would want this function to be platform sepcific as well but
1587      * 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
1588      * We could use upper case and we would still need to deal with the descripencies but
1589      * 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
1590      * 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
1591      */
1592     function toFileNameLowerCase(x) {
1593         return fileNameLowerCaseRegExp.test(x) ?
1594             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1595             x;
1596     }
1597     ts.toFileNameLowerCase = toFileNameLowerCase;
1598     /** Throws an error because a function is not implemented. */
1599     function notImplemented() {
1600         throw new Error("Not implemented");
1601     }
1602     ts.notImplemented = notImplemented;
1603     function memoize(callback) {
1604         var value;
1605         return function () {
1606             if (callback) {
1607                 value = callback();
1608                 callback = undefined;
1609             }
1610             return value;
1611         };
1612     }
1613     ts.memoize = memoize;
1614     function compose(a, b, c, d, e) {
1615         if (!!e) {
1616             var args_2 = [];
1617             for (var i = 0; i < arguments.length; i++) {
1618                 args_2[i] = arguments[i];
1619             }
1620             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1621         }
1622         else if (d) {
1623             return function (t) { return d(c(b(a(t)))); };
1624         }
1625         else if (c) {
1626             return function (t) { return c(b(a(t))); };
1627         }
1628         else if (b) {
1629             return function (t) { return b(a(t)); };
1630         }
1631         else if (a) {
1632             return function (t) { return a(t); };
1633         }
1634         else {
1635             return function (t) { return t; };
1636         }
1637     }
1638     ts.compose = compose;
1639     var AssertionLevel;
1640     (function (AssertionLevel) {
1641         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1642         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1643         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1644         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1645     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1646     function equateValues(a, b) {
1647         return a === b;
1648     }
1649     ts.equateValues = equateValues;
1650     /**
1651      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1652      *
1653      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1654      * value of each code-point after applying `toUpperCase` to each string. We always map both
1655      * strings to their upper-case form as some unicode characters do not properly round-trip to
1656      * lowercase (such as `ẞ` (German sharp capital s)).
1657      */
1658     function equateStringsCaseInsensitive(a, b) {
1659         return a === b
1660             || a !== undefined
1661                 && b !== undefined
1662                 && a.toUpperCase() === b.toUpperCase();
1663     }
1664     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1665     /**
1666      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1667      *
1668      * Case-sensitive comparisons compare both strings one code-point at a time using the
1669      * integer value of each code-point.
1670      */
1671     function equateStringsCaseSensitive(a, b) {
1672         return equateValues(a, b);
1673     }
1674     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1675     function compareComparableValues(a, b) {
1676         return a === b ? 0 /* EqualTo */ :
1677             a === undefined ? -1 /* LessThan */ :
1678                 b === undefined ? 1 /* GreaterThan */ :
1679                     a < b ? -1 /* LessThan */ :
1680                         1 /* GreaterThan */;
1681     }
1682     /**
1683      * Compare two numeric values for their order relative to each other.
1684      * To compare strings, use any of the `compareStrings` functions.
1685      */
1686     function compareValues(a, b) {
1687         return compareComparableValues(a, b);
1688     }
1689     ts.compareValues = compareValues;
1690     /**
1691      * Compare two TextSpans, first by `start`, then by `length`.
1692      */
1693     function compareTextSpans(a, b) {
1694         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);
1695     }
1696     ts.compareTextSpans = compareTextSpans;
1697     function min(a, b, compare) {
1698         return compare(a, b) === -1 /* LessThan */ ? a : b;
1699     }
1700     ts.min = min;
1701     /**
1702      * Compare two strings using a case-insensitive ordinal comparison.
1703      *
1704      * Ordinal comparisons are based on the difference between the unicode code points of both
1705      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1706      * comparisons provide predictable ordering, but place "a" after "B".
1707      *
1708      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1709      * value of each code-point after applying `toUpperCase` to each string. We always map both
1710      * strings to their upper-case form as some unicode characters do not properly round-trip to
1711      * lowercase (such as `ẞ` (German sharp capital s)).
1712      */
1713     function compareStringsCaseInsensitive(a, b) {
1714         if (a === b)
1715             return 0 /* EqualTo */;
1716         if (a === undefined)
1717             return -1 /* LessThan */;
1718         if (b === undefined)
1719             return 1 /* GreaterThan */;
1720         a = a.toUpperCase();
1721         b = b.toUpperCase();
1722         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1723     }
1724     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1725     /**
1726      * Compare two strings using a case-sensitive ordinal comparison.
1727      *
1728      * Ordinal comparisons are based on the difference between the unicode code points of both
1729      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1730      * comparisons provide predictable ordering, but place "a" after "B".
1731      *
1732      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1733      * value of each code-point.
1734      */
1735     function compareStringsCaseSensitive(a, b) {
1736         return compareComparableValues(a, b);
1737     }
1738     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1739     function getStringComparer(ignoreCase) {
1740         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1741     }
1742     ts.getStringComparer = getStringComparer;
1743     /**
1744      * Creates a string comparer for use with string collation in the UI.
1745      */
1746     var createUIStringComparer = (function () {
1747         var defaultComparer;
1748         var enUSComparer;
1749         var stringComparerFactory = getStringComparerFactory();
1750         return createStringComparer;
1751         function compareWithCallback(a, b, comparer) {
1752             if (a === b)
1753                 return 0 /* EqualTo */;
1754             if (a === undefined)
1755                 return -1 /* LessThan */;
1756             if (b === undefined)
1757                 return 1 /* GreaterThan */;
1758             var value = comparer(a, b);
1759             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1760         }
1761         function createIntlCollatorStringComparer(locale) {
1762             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1763             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1764             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1765             return function (a, b) { return compareWithCallback(a, b, comparer); };
1766         }
1767         function createLocaleCompareStringComparer(locale) {
1768             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1769             if (locale !== undefined)
1770                 return createFallbackStringComparer();
1771             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1772             function compareStrings(a, b) {
1773                 return a.localeCompare(b);
1774             }
1775         }
1776         function createFallbackStringComparer() {
1777             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1778             // We first sort case insensitively.  So "Aaa" will come before "baa".
1779             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1780             //
1781             // For case insensitive comparisons we always map both strings to their
1782             // upper-case form as some unicode characters do not properly round-trip to
1783             // lowercase (such as `ẞ` (German sharp capital s)).
1784             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1785             function compareDictionaryOrder(a, b) {
1786                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1787             }
1788             function compareStrings(a, b) {
1789                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1790             }
1791         }
1792         function getStringComparerFactory() {
1793             // If the host supports Intl, we use it for comparisons using the default locale.
1794             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1795                 return createIntlCollatorStringComparer;
1796             }
1797             // If the host does not support Intl, we fall back to localeCompare.
1798             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1799             if (typeof String.prototype.localeCompare === "function" &&
1800                 typeof String.prototype.toLocaleUpperCase === "function" &&
1801                 "a".localeCompare("B") < 0) {
1802                 return createLocaleCompareStringComparer;
1803             }
1804             // Otherwise, fall back to ordinal comparison:
1805             return createFallbackStringComparer;
1806         }
1807         function createStringComparer(locale) {
1808             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1809             // tests.
1810             if (locale === undefined) {
1811                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1812             }
1813             else if (locale === "en-US") {
1814                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1815             }
1816             else {
1817                 return stringComparerFactory(locale);
1818             }
1819         }
1820     })();
1821     var uiComparerCaseSensitive;
1822     var uiLocale;
1823     function getUILocale() {
1824         return uiLocale;
1825     }
1826     ts.getUILocale = getUILocale;
1827     function setUILocale(value) {
1828         if (uiLocale !== value) {
1829             uiLocale = value;
1830             uiComparerCaseSensitive = undefined;
1831         }
1832     }
1833     ts.setUILocale = setUILocale;
1834     /**
1835      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1836      *
1837      * Ordering is not predictable between different host locales, but is best for displaying
1838      * ordered data for UI presentation. Characters with multiple unicode representations may
1839      * be considered equal.
1840      *
1841      * Case-sensitive comparisons compare strings that differ in base characters, or
1842      * accents/diacritic marks, or case as unequal.
1843      */
1844     function compareStringsCaseSensitiveUI(a, b) {
1845         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1846         return comparer(a, b);
1847     }
1848     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1849     function compareProperties(a, b, key, comparer) {
1850         return a === b ? 0 /* EqualTo */ :
1851             a === undefined ? -1 /* LessThan */ :
1852                 b === undefined ? 1 /* GreaterThan */ :
1853                     comparer(a[key], b[key]);
1854     }
1855     ts.compareProperties = compareProperties;
1856     /** True is greater than false. */
1857     function compareBooleans(a, b) {
1858         return compareValues(a ? 1 : 0, b ? 1 : 0);
1859     }
1860     ts.compareBooleans = compareBooleans;
1861     /**
1862      * 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.
1863      * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1864      *
1865      * If there is a candidate that's the same except for case, return that.
1866      * If there is a candidate that's within one edit of the name, return that.
1867      * Otherwise, return the candidate with the smallest Levenshtein distance,
1868      *    except for candidates:
1869      *      * With no name
1870      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1871      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1872      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1873      *         and 1 insertion/deletion at 3 characters)
1874      */
1875     function getSpellingSuggestion(name, candidates, getName) {
1876         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1877         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1878         var bestCandidate;
1879         var justCheckExactMatches = false;
1880         var nameLowerCase = name.toLowerCase();
1881         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1882             var candidate = candidates_1[_i];
1883             var candidateName = getName(candidate);
1884             if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1885                 var candidateNameLowerCase = candidateName.toLowerCase();
1886                 if (candidateNameLowerCase === nameLowerCase) {
1887                     if (candidateName === name) {
1888                         continue;
1889                     }
1890                     return candidate;
1891                 }
1892                 if (justCheckExactMatches) {
1893                     continue;
1894                 }
1895                 if (candidateName.length < 3) {
1896                     // Don't bother, user would have noticed a 2-character name having an extra character
1897                     continue;
1898                 }
1899                 // Only care about a result better than the best so far.
1900                 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1901                 if (distance === undefined) {
1902                     continue;
1903                 }
1904                 if (distance < 3) {
1905                     justCheckExactMatches = true;
1906                     bestCandidate = candidate;
1907                 }
1908                 else {
1909                     ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1910                     bestDistance = distance;
1911                     bestCandidate = candidate;
1912                 }
1913             }
1914         }
1915         return bestCandidate;
1916     }
1917     ts.getSpellingSuggestion = getSpellingSuggestion;
1918     function levenshteinWithMax(s1, s2, max) {
1919         var previous = new Array(s2.length + 1);
1920         var current = new Array(s2.length + 1);
1921         /** Represents any value > max. We don't care about the particular value. */
1922         var big = max + 1;
1923         for (var i = 0; i <= s2.length; i++) {
1924             previous[i] = i;
1925         }
1926         for (var i = 1; i <= s1.length; i++) {
1927             var c1 = s1.charCodeAt(i - 1);
1928             var minJ = i > max ? i - max : 1;
1929             var maxJ = s2.length > max + i ? max + i : s2.length;
1930             current[0] = i;
1931             /** Smallest value of the matrix in the ith column. */
1932             var colMin = i;
1933             for (var j = 1; j < minJ; j++) {
1934                 current[j] = big;
1935             }
1936             for (var j = minJ; j <= maxJ; j++) {
1937                 var dist = c1 === s2.charCodeAt(j - 1)
1938                     ? previous[j - 1]
1939                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1940                 current[j] = dist;
1941                 colMin = Math.min(colMin, dist);
1942             }
1943             for (var j = maxJ + 1; j <= s2.length; j++) {
1944                 current[j] = big;
1945             }
1946             if (colMin > max) {
1947                 // Give up -- everything in this column is > max and it can't get better in future columns.
1948                 return undefined;
1949             }
1950             var temp = previous;
1951             previous = current;
1952             current = temp;
1953         }
1954         var res = previous[s2.length];
1955         return res > max ? undefined : res;
1956     }
1957     function endsWith(str, suffix) {
1958         var expectedPos = str.length - suffix.length;
1959         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1960     }
1961     ts.endsWith = endsWith;
1962     function removeSuffix(str, suffix) {
1963         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1964     }
1965     ts.removeSuffix = removeSuffix;
1966     function tryRemoveSuffix(str, suffix) {
1967         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1968     }
1969     ts.tryRemoveSuffix = tryRemoveSuffix;
1970     function stringContains(str, substring) {
1971         return str.indexOf(substring) !== -1;
1972     }
1973     ts.stringContains = stringContains;
1974     /**
1975      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1976      */
1977     function removeMinAndVersionNumbers(fileName) {
1978         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1979         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1980         // The "min" or version may both be present, in either order, so try applying the above twice.
1981         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1982     }
1983     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1984     /** Remove an item from an array, moving everything to its right one space left. */
1985     function orderedRemoveItem(array, item) {
1986         for (var i = 0; i < array.length; i++) {
1987             if (array[i] === item) {
1988                 orderedRemoveItemAt(array, i);
1989                 return true;
1990             }
1991         }
1992         return false;
1993     }
1994     ts.orderedRemoveItem = orderedRemoveItem;
1995     /** Remove an item by index from an array, moving everything to its right one space left. */
1996     function orderedRemoveItemAt(array, index) {
1997         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1998         for (var i = index; i < array.length - 1; i++) {
1999             array[i] = array[i + 1];
2000         }
2001         array.pop();
2002     }
2003     ts.orderedRemoveItemAt = orderedRemoveItemAt;
2004     function unorderedRemoveItemAt(array, index) {
2005         // Fill in the "hole" left at `index`.
2006         array[index] = array[array.length - 1];
2007         array.pop();
2008     }
2009     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
2010     /** Remove the *first* occurrence of `item` from the array. */
2011     function unorderedRemoveItem(array, item) {
2012         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
2013     }
2014     ts.unorderedRemoveItem = unorderedRemoveItem;
2015     /** Remove the *first* element satisfying `predicate`. */
2016     function unorderedRemoveFirstItemWhere(array, predicate) {
2017         for (var i = 0; i < array.length; i++) {
2018             if (predicate(array[i])) {
2019                 unorderedRemoveItemAt(array, i);
2020                 return true;
2021             }
2022         }
2023         return false;
2024     }
2025     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
2026         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
2027     }
2028     ts.createGetCanonicalFileName = createGetCanonicalFileName;
2029     function patternText(_a) {
2030         var prefix = _a.prefix, suffix = _a.suffix;
2031         return prefix + "*" + suffix;
2032     }
2033     ts.patternText = patternText;
2034     /**
2035      * Given that candidate matches pattern, returns the text matching the '*'.
2036      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
2037      */
2038     function matchedText(pattern, candidate) {
2039         ts.Debug.assert(isPatternMatch(pattern, candidate));
2040         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
2041     }
2042     ts.matchedText = matchedText;
2043     /** Return the object corresponding to the best pattern to match `candidate`. */
2044     function findBestPatternMatch(values, getPattern, candidate) {
2045         var matchedValue;
2046         // use length of prefix as betterness criteria
2047         var longestMatchPrefixLength = -1;
2048         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2049             var v = values_2[_i];
2050             var pattern = getPattern(v);
2051             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2052                 longestMatchPrefixLength = pattern.prefix.length;
2053                 matchedValue = v;
2054             }
2055         }
2056         return matchedValue;
2057     }
2058     ts.findBestPatternMatch = findBestPatternMatch;
2059     function startsWith(str, prefix) {
2060         return str.lastIndexOf(prefix, 0) === 0;
2061     }
2062     ts.startsWith = startsWith;
2063     function removePrefix(str, prefix) {
2064         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2065     }
2066     ts.removePrefix = removePrefix;
2067     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2068         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2069         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2070     }
2071     ts.tryRemovePrefix = tryRemovePrefix;
2072     function isPatternMatch(_a, candidate) {
2073         var prefix = _a.prefix, suffix = _a.suffix;
2074         return candidate.length >= prefix.length + suffix.length &&
2075             startsWith(candidate, prefix) &&
2076             endsWith(candidate, suffix);
2077     }
2078     function and(f, g) {
2079         return function (arg) { return f(arg) && g(arg); };
2080     }
2081     ts.and = and;
2082     function or() {
2083         var fs = [];
2084         for (var _i = 0; _i < arguments.length; _i++) {
2085             fs[_i] = arguments[_i];
2086         }
2087         return function () {
2088             var args = [];
2089             for (var _i = 0; _i < arguments.length; _i++) {
2090                 args[_i] = arguments[_i];
2091             }
2092             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
2093                 var f = fs_1[_a];
2094                 if (f.apply(void 0, args)) {
2095                     return true;
2096                 }
2097             }
2098             return false;
2099         };
2100     }
2101     ts.or = or;
2102     function not(fn) {
2103         return function () {
2104             var args = [];
2105             for (var _i = 0; _i < arguments.length; _i++) {
2106                 args[_i] = arguments[_i];
2107             }
2108             return !fn.apply(void 0, args);
2109         };
2110     }
2111     ts.not = not;
2112     function assertType(_) { }
2113     ts.assertType = assertType;
2114     function singleElementArray(t) {
2115         return t === undefined ? undefined : [t];
2116     }
2117     ts.singleElementArray = singleElementArray;
2118     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2119         unchanged = unchanged || noop;
2120         var newIndex = 0;
2121         var oldIndex = 0;
2122         var newLen = newItems.length;
2123         var oldLen = oldItems.length;
2124         while (newIndex < newLen && oldIndex < oldLen) {
2125             var newItem = newItems[newIndex];
2126             var oldItem = oldItems[oldIndex];
2127             var compareResult = comparer(newItem, oldItem);
2128             if (compareResult === -1 /* LessThan */) {
2129                 inserted(newItem);
2130                 newIndex++;
2131             }
2132             else if (compareResult === 1 /* GreaterThan */) {
2133                 deleted(oldItem);
2134                 oldIndex++;
2135             }
2136             else {
2137                 unchanged(oldItem, newItem);
2138                 newIndex++;
2139                 oldIndex++;
2140             }
2141         }
2142         while (newIndex < newLen) {
2143             inserted(newItems[newIndex++]);
2144         }
2145         while (oldIndex < oldLen) {
2146             deleted(oldItems[oldIndex++]);
2147         }
2148     }
2149     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2150     function fill(length, cb) {
2151         var result = Array(length);
2152         for (var i = 0; i < length; i++) {
2153             result[i] = cb(i);
2154         }
2155         return result;
2156     }
2157     ts.fill = fill;
2158     function cartesianProduct(arrays) {
2159         var result = [];
2160         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2161         return result;
2162     }
2163     ts.cartesianProduct = cartesianProduct;
2164     function cartesianProductWorker(arrays, result, outer, index) {
2165         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2166             var element = _a[_i];
2167             var inner = void 0;
2168             if (outer) {
2169                 inner = outer.slice();
2170                 inner.push(element);
2171             }
2172             else {
2173                 inner = [element];
2174             }
2175             if (index === arrays.length - 1) {
2176                 result.push(inner);
2177             }
2178             else {
2179                 cartesianProductWorker(arrays, result, inner, index + 1);
2180             }
2181         }
2182     }
2183     function padLeft(s, length) {
2184         while (s.length < length) {
2185             s = " " + s;
2186         }
2187         return s;
2188     }
2189     ts.padLeft = padLeft;
2190     function padRight(s, length) {
2191         while (s.length < length) {
2192             s = s + " ";
2193         }
2194         return s;
2195     }
2196     ts.padRight = padRight;
2197 })(ts || (ts = {}));
2198 /* @internal */
2199 var ts;
2200 (function (ts) {
2201     var Debug;
2202     (function (Debug) {
2203         var currentAssertionLevel = 0 /* None */;
2204         // eslint-disable-next-line prefer-const
2205         Debug.isDebugging = false;
2206         var assertionCache = {};
2207         function getAssertionLevel() {
2208             return currentAssertionLevel;
2209         }
2210         Debug.getAssertionLevel = getAssertionLevel;
2211         function setAssertionLevel(level) {
2212             var prevAssertionLevel = currentAssertionLevel;
2213             currentAssertionLevel = level;
2214             if (level > prevAssertionLevel) {
2215                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2216                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2217                     var key = _a[_i];
2218                     var cachedFunc = assertionCache[key];
2219                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2220                         Debug[key] = cachedFunc;
2221                         assertionCache[key] = undefined;
2222                     }
2223                 }
2224             }
2225         }
2226         Debug.setAssertionLevel = setAssertionLevel;
2227         function shouldAssert(level) {
2228             return currentAssertionLevel >= level;
2229         }
2230         Debug.shouldAssert = shouldAssert;
2231         /**
2232          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2233          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2234          * @param level The minimum assertion level required.
2235          * @param name The name of the current assertion function.
2236          */
2237         function shouldAssertFunction(level, name) {
2238             if (!shouldAssert(level)) {
2239                 assertionCache[name] = { level: level, assertion: Debug[name] };
2240                 Debug[name] = ts.noop;
2241                 return false;
2242             }
2243             return true;
2244         }
2245         function fail(message, stackCrawlMark) {
2246             debugger;
2247             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2248             if (Error.captureStackTrace) {
2249                 Error.captureStackTrace(e, stackCrawlMark || fail);
2250             }
2251             throw e;
2252         }
2253         Debug.fail = fail;
2254         function failBadSyntaxKind(node, message, stackCrawlMark) {
2255             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2256         }
2257         Debug.failBadSyntaxKind = failBadSyntaxKind;
2258         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2259             if (!expression) {
2260                 message = message ? "False expression: " + message : "False expression.";
2261                 if (verboseDebugInfo) {
2262                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2263                 }
2264                 fail(message, stackCrawlMark || assert);
2265             }
2266         }
2267         Debug.assert = assert;
2268         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2269             if (a !== b) {
2270                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2271                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2272             }
2273         }
2274         Debug.assertEqual = assertEqual;
2275         function assertLessThan(a, b, msg, stackCrawlMark) {
2276             if (a >= b) {
2277                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2278             }
2279         }
2280         Debug.assertLessThan = assertLessThan;
2281         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2282             if (a > b) {
2283                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2284             }
2285         }
2286         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2287         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2288             if (a < b) {
2289                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2290             }
2291         }
2292         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2293         function assertIsDefined(value, message, stackCrawlMark) {
2294             // eslint-disable-next-line no-null/no-null
2295             if (value === undefined || value === null) {
2296                 fail(message, stackCrawlMark || assertIsDefined);
2297             }
2298         }
2299         Debug.assertIsDefined = assertIsDefined;
2300         function checkDefined(value, message, stackCrawlMark) {
2301             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2302             return value;
2303         }
2304         Debug.checkDefined = checkDefined;
2305         /**
2306          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2307          * a value is defined at the statement level.
2308          */
2309         Debug.assertDefined = checkDefined;
2310         function assertEachIsDefined(value, message, stackCrawlMark) {
2311             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2312                 var v = value_1[_i];
2313                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2314             }
2315         }
2316         Debug.assertEachIsDefined = assertEachIsDefined;
2317         function checkEachDefined(value, message, stackCrawlMark) {
2318             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2319             return value;
2320         }
2321         Debug.checkEachDefined = checkEachDefined;
2322         /**
2323          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2324          * the elements of an array are defined at the statement level.
2325          */
2326         Debug.assertEachDefined = checkEachDefined;
2327         function assertNever(member, message, stackCrawlMark) {
2328             if (message === void 0) { message = "Illegal value:"; }
2329             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2330             return fail(message + " " + detail, stackCrawlMark || assertNever);
2331         }
2332         Debug.assertNever = assertNever;
2333         function assertEachNode(nodes, test, message, stackCrawlMark) {
2334             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2335                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2336             }
2337         }
2338         Debug.assertEachNode = assertEachNode;
2339         function assertNode(node, test, message, stackCrawlMark) {
2340             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2341                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2342             }
2343         }
2344         Debug.assertNode = assertNode;
2345         function assertNotNode(node, test, message, stackCrawlMark) {
2346             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2347                 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);
2348             }
2349         }
2350         Debug.assertNotNode = assertNotNode;
2351         function assertOptionalNode(node, test, message, stackCrawlMark) {
2352             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2353                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2354             }
2355         }
2356         Debug.assertOptionalNode = assertOptionalNode;
2357         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2358             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2359                 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);
2360             }
2361         }
2362         Debug.assertOptionalToken = assertOptionalToken;
2363         function assertMissingNode(node, message, stackCrawlMark) {
2364             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2365                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2366             }
2367         }
2368         Debug.assertMissingNode = assertMissingNode;
2369         function getFunctionName(func) {
2370             if (typeof func !== "function") {
2371                 return "";
2372             }
2373             else if (func.hasOwnProperty("name")) {
2374                 return func.name;
2375             }
2376             else {
2377                 var text = Function.prototype.toString.call(func);
2378                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2379                 return match ? match[1] : "";
2380             }
2381         }
2382         Debug.getFunctionName = getFunctionName;
2383         function formatSymbol(symbol) {
2384             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2385         }
2386         Debug.formatSymbol = formatSymbol;
2387         /**
2388          * Formats an enum value as a string for debugging and debug assertions.
2389          */
2390         function formatEnum(value, enumObject, isFlags) {
2391             if (value === void 0) { value = 0; }
2392             var members = getEnumMembers(enumObject);
2393             if (value === 0) {
2394                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2395             }
2396             if (isFlags) {
2397                 var result = "";
2398                 var remainingFlags = value;
2399                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2400                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2401                     if (enumValue > value) {
2402                         break;
2403                     }
2404                     if (enumValue !== 0 && enumValue & value) {
2405                         result = "" + result + (result ? "|" : "") + enumName;
2406                         remainingFlags &= ~enumValue;
2407                     }
2408                 }
2409                 if (remainingFlags === 0) {
2410                     return result;
2411                 }
2412             }
2413             else {
2414                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2415                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2416                     if (enumValue === value) {
2417                         return enumName;
2418                     }
2419                 }
2420             }
2421             return value.toString();
2422         }
2423         Debug.formatEnum = formatEnum;
2424         function getEnumMembers(enumObject) {
2425             var result = [];
2426             for (var name in enumObject) {
2427                 var value = enumObject[name];
2428                 if (typeof value === "number") {
2429                     result.push([value, name]);
2430                 }
2431             }
2432             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2433         }
2434         function formatSyntaxKind(kind) {
2435             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2436         }
2437         Debug.formatSyntaxKind = formatSyntaxKind;
2438         function formatNodeFlags(flags) {
2439             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2440         }
2441         Debug.formatNodeFlags = formatNodeFlags;
2442         function formatModifierFlags(flags) {
2443             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2444         }
2445         Debug.formatModifierFlags = formatModifierFlags;
2446         function formatTransformFlags(flags) {
2447             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2448         }
2449         Debug.formatTransformFlags = formatTransformFlags;
2450         function formatEmitFlags(flags) {
2451             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2452         }
2453         Debug.formatEmitFlags = formatEmitFlags;
2454         function formatSymbolFlags(flags) {
2455             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2456         }
2457         Debug.formatSymbolFlags = formatSymbolFlags;
2458         function formatTypeFlags(flags) {
2459             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2460         }
2461         Debug.formatTypeFlags = formatTypeFlags;
2462         function formatObjectFlags(flags) {
2463             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2464         }
2465         Debug.formatObjectFlags = formatObjectFlags;
2466         var isDebugInfoEnabled = false;
2467         var extendedDebugModule;
2468         function extendedDebug() {
2469             enableDebugInfo();
2470             if (!extendedDebugModule) {
2471                 throw new Error("Debugging helpers could not be loaded.");
2472             }
2473             return extendedDebugModule;
2474         }
2475         function printControlFlowGraph(flowNode) {
2476             return console.log(formatControlFlowGraph(flowNode));
2477         }
2478         Debug.printControlFlowGraph = printControlFlowGraph;
2479         function formatControlFlowGraph(flowNode) {
2480             return extendedDebug().formatControlFlowGraph(flowNode);
2481         }
2482         Debug.formatControlFlowGraph = formatControlFlowGraph;
2483         function attachFlowNodeDebugInfo(flowNode) {
2484             if (isDebugInfoEnabled) {
2485                 if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2486                     Object.defineProperties(flowNode, {
2487                         __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2488                         __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2489                     });
2490                 }
2491             }
2492         }
2493         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2494         /**
2495          * Injects debug information into frequently used types.
2496          */
2497         function enableDebugInfo() {
2498             if (isDebugInfoEnabled)
2499                 return;
2500             // Add additional properties in debug mode to assist with debugging.
2501             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2502                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2503             });
2504             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2505                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2506                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2507                 __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
2508             });
2509             var nodeConstructors = [
2510                 ts.objectAllocator.getNodeConstructor(),
2511                 ts.objectAllocator.getIdentifierConstructor(),
2512                 ts.objectAllocator.getTokenConstructor(),
2513                 ts.objectAllocator.getSourceFileConstructor()
2514             ];
2515             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2516                 var ctor = nodeConstructors_1[_i];
2517                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2518                     Object.defineProperties(ctor.prototype, {
2519                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2520                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2521                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
2522                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2523                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2524                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2525                         __debugGetText: {
2526                             value: function (includeTrivia) {
2527                                 if (ts.nodeIsSynthesized(this))
2528                                     return "";
2529                                 var parseNode = ts.getParseTreeNode(this);
2530                                 var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2531                                 return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2532                             }
2533                         }
2534                     });
2535                 }
2536             }
2537             // attempt to load extended debugging information
2538             try {
2539                 if (ts.sys && ts.sys.require) {
2540                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2541                     var result = ts.sys.require(basePath, "./compiler-debug");
2542                     if (!result.error) {
2543                         result.module.init(ts);
2544                         extendedDebugModule = result.module;
2545                     }
2546                 }
2547             }
2548             catch (_a) {
2549                 // do nothing
2550             }
2551             isDebugInfoEnabled = true;
2552         }
2553         Debug.enableDebugInfo = enableDebugInfo;
2554     })(Debug = ts.Debug || (ts.Debug = {}));
2555 })(ts || (ts = {}));
2556 /*@internal*/
2557 var ts;
2558 (function (ts) {
2559     /** Gets a timestamp with (at least) ms resolution */
2560     ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
2561 })(ts || (ts = {}));
2562 /*@internal*/
2563 /** Performance measurements for the compiler. */
2564 var ts;
2565 (function (ts) {
2566     var performance;
2567     (function (performance) {
2568         // NOTE: cannot use ts.noop as core.ts loads after this
2569         var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
2570         var enabled = false;
2571         var profilerStart = 0;
2572         var counts;
2573         var marks;
2574         var measures;
2575         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
2576             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
2577         }
2578         performance.createTimerIf = createTimerIf;
2579         function createTimer(measureName, startMarkName, endMarkName) {
2580             var enterCount = 0;
2581             return {
2582                 enter: enter,
2583                 exit: exit
2584             };
2585             function enter() {
2586                 if (++enterCount === 1) {
2587                     mark(startMarkName);
2588                 }
2589             }
2590             function exit() {
2591                 if (--enterCount === 0) {
2592                     mark(endMarkName);
2593                     measure(measureName, startMarkName, endMarkName);
2594                 }
2595                 else if (enterCount < 0) {
2596                     ts.Debug.fail("enter/exit count does not match.");
2597                 }
2598             }
2599         }
2600         performance.createTimer = createTimer;
2601         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
2602         /**
2603          * Marks a performance event.
2604          *
2605          * @param markName The name of the mark.
2606          */
2607         function mark(markName) {
2608             if (enabled) {
2609                 marks.set(markName, ts.timestamp());
2610                 counts.set(markName, (counts.get(markName) || 0) + 1);
2611                 profilerEvent(markName);
2612             }
2613         }
2614         performance.mark = mark;
2615         /**
2616          * Adds a performance measurement with the specified name.
2617          *
2618          * @param measureName The name of the performance measurement.
2619          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
2620          *      profiler was enabled is used.
2621          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
2622          *      used.
2623          */
2624         function measure(measureName, startMarkName, endMarkName) {
2625             if (enabled) {
2626                 var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
2627                 var start = startMarkName && marks.get(startMarkName) || profilerStart;
2628                 measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
2629             }
2630         }
2631         performance.measure = measure;
2632         /**
2633          * Gets the number of times a marker was encountered.
2634          *
2635          * @param markName The name of the mark.
2636          */
2637         function getCount(markName) {
2638             return counts && counts.get(markName) || 0;
2639         }
2640         performance.getCount = getCount;
2641         /**
2642          * Gets the total duration of all measurements with the supplied name.
2643          *
2644          * @param measureName The name of the measure whose durations should be accumulated.
2645          */
2646         function getDuration(measureName) {
2647             return measures && measures.get(measureName) || 0;
2648         }
2649         performance.getDuration = getDuration;
2650         /**
2651          * Iterate over each measure, performing some action
2652          *
2653          * @param cb The action to perform for each measure
2654          */
2655         function forEachMeasure(cb) {
2656             measures.forEach(function (measure, key) {
2657                 cb(key, measure);
2658             });
2659         }
2660         performance.forEachMeasure = forEachMeasure;
2661         /** Enables (and resets) performance measurements for the compiler. */
2662         function enable() {
2663             counts = ts.createMap();
2664             marks = ts.createMap();
2665             measures = ts.createMap();
2666             enabled = true;
2667             profilerStart = ts.timestamp();
2668         }
2669         performance.enable = enable;
2670         /** Disables performance measurements for the compiler. */
2671         function disable() {
2672             enabled = false;
2673         }
2674         performance.disable = disable;
2675     })(performance = ts.performance || (ts.performance = {}));
2676 })(ts || (ts = {}));
2677 /* @internal */
2678 var ts;
2679 (function (ts) {
2680     var nullLogger = {
2681         logEvent: ts.noop,
2682         logErrEvent: ts.noop,
2683         logPerfEvent: ts.noop,
2684         logInfoEvent: ts.noop,
2685         logStartCommand: ts.noop,
2686         logStopCommand: ts.noop,
2687         logStartUpdateProgram: ts.noop,
2688         logStopUpdateProgram: ts.noop,
2689         logStartUpdateGraph: ts.noop,
2690         logStopUpdateGraph: ts.noop,
2691         logStartResolveModule: ts.noop,
2692         logStopResolveModule: ts.noop,
2693         logStartParseSourceFile: ts.noop,
2694         logStopParseSourceFile: ts.noop,
2695         logStartReadFile: ts.noop,
2696         logStopReadFile: ts.noop,
2697         logStartBindFile: ts.noop,
2698         logStopBindFile: ts.noop,
2699         logStartScheduledOperation: ts.noop,
2700         logStopScheduledOperation: ts.noop,
2701     };
2702     // Load optional module to enable Event Tracing for Windows
2703     // See https://github.com/microsoft/typescript-etw for more information
2704     var etwModule;
2705     try {
2706         // require() will throw an exception if the module is not installed
2707         // It may also return undefined if not installed properly
2708         etwModule = require("@microsoft/typescript-etw");
2709     }
2710     catch (e) {
2711         etwModule = undefined;
2712     }
2713     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
2714     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
2715 })(ts || (ts = {}));
2716 /* @internal */
2717 var ts;
2718 (function (ts) {
2719     // https://semver.org/#spec-item-2
2720     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2721     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2722     // > version, and Z is the patch version. Each element MUST increase numerically.
2723     //
2724     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2725     // value of `0`.
2726     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2727     // https://semver.org/#spec-item-9
2728     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2729     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2730     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2731     // > MUST NOT include leading zeroes.
2732     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2733     // https://semver.org/#spec-item-10
2734     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2735     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2736     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2737     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2738     // https://semver.org/#spec-item-9
2739     // > Numeric identifiers MUST NOT include leading zeroes.
2740     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2741     /**
2742      * Describes a precise semantic version number, https://semver.org
2743      */
2744     var Version = /** @class */ (function () {
2745         function Version(major, minor, patch, prerelease, build) {
2746             if (minor === void 0) { minor = 0; }
2747             if (patch === void 0) { patch = 0; }
2748             if (prerelease === void 0) { prerelease = ""; }
2749             if (build === void 0) { build = ""; }
2750             if (typeof major === "string") {
2751                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2752                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2753             }
2754             ts.Debug.assert(major >= 0, "Invalid argument: major");
2755             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2756             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2757             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2758             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2759             this.major = major;
2760             this.minor = minor;
2761             this.patch = patch;
2762             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2763             this.build = build ? build.split(".") : ts.emptyArray;
2764         }
2765         Version.tryParse = function (text) {
2766             var result = tryParseComponents(text);
2767             if (!result)
2768                 return undefined;
2769             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2770             return new Version(major, minor, patch, prerelease, build);
2771         };
2772         Version.prototype.compareTo = function (other) {
2773             // https://semver.org/#spec-item-11
2774             // > Precedence is determined by the first difference when comparing each of these
2775             // > identifiers from left to right as follows: Major, minor, and patch versions are
2776             // > always compared numerically.
2777             //
2778             // https://semver.org/#spec-item-11
2779             // > Precedence for two pre-release versions with the same major, minor, and patch version
2780             // > MUST be determined by comparing each dot separated identifier from left to right until
2781             // > a difference is found [...]
2782             //
2783             // https://semver.org/#spec-item-11
2784             // > Build metadata does not figure into precedence
2785             if (this === other)
2786                 return 0 /* EqualTo */;
2787             if (other === undefined)
2788                 return 1 /* GreaterThan */;
2789             return ts.compareValues(this.major, other.major)
2790                 || ts.compareValues(this.minor, other.minor)
2791                 || ts.compareValues(this.patch, other.patch)
2792                 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2793         };
2794         Version.prototype.increment = function (field) {
2795             switch (field) {
2796                 case "major": return new Version(this.major + 1, 0, 0);
2797                 case "minor": return new Version(this.major, this.minor + 1, 0);
2798                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2799                 default: return ts.Debug.assertNever(field);
2800             }
2801         };
2802         Version.prototype.toString = function () {
2803             var result = this.major + "." + this.minor + "." + this.patch;
2804             if (ts.some(this.prerelease))
2805                 result += "-" + this.prerelease.join(".");
2806             if (ts.some(this.build))
2807                 result += "+" + this.build.join(".");
2808             return result;
2809         };
2810         Version.zero = new Version(0, 0, 0);
2811         return Version;
2812     }());
2813     ts.Version = Version;
2814     function tryParseComponents(text) {
2815         var match = versionRegExp.exec(text);
2816         if (!match)
2817             return undefined;
2818         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;
2819         if (prerelease && !prereleaseRegExp.test(prerelease))
2820             return undefined;
2821         if (build && !buildRegExp.test(build))
2822             return undefined;
2823         return {
2824             major: parseInt(major, 10),
2825             minor: parseInt(minor, 10),
2826             patch: parseInt(patch, 10),
2827             prerelease: prerelease,
2828             build: build
2829         };
2830     }
2831     function comparePrerelaseIdentifiers(left, right) {
2832         // https://semver.org/#spec-item-11
2833         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2834         // > than a normal version.
2835         if (left === right)
2836             return 0 /* EqualTo */;
2837         if (left.length === 0)
2838             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2839         if (right.length === 0)
2840             return -1 /* LessThan */;
2841         // https://semver.org/#spec-item-11
2842         // > Precedence for two pre-release versions with the same major, minor, and patch version
2843         // > MUST be determined by comparing each dot separated identifier from left to right until
2844         // > a difference is found [...]
2845         var length = Math.min(left.length, right.length);
2846         for (var i = 0; i < length; i++) {
2847             var leftIdentifier = left[i];
2848             var rightIdentifier = right[i];
2849             if (leftIdentifier === rightIdentifier)
2850                 continue;
2851             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2852             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2853             if (leftIsNumeric || rightIsNumeric) {
2854                 // https://semver.org/#spec-item-11
2855                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2856                 if (leftIsNumeric !== rightIsNumeric)
2857                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2858                 // https://semver.org/#spec-item-11
2859                 // > identifiers consisting of only digits are compared numerically
2860                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2861                 if (result)
2862                     return result;
2863             }
2864             else {
2865                 // https://semver.org/#spec-item-11
2866                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2867                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2868                 if (result)
2869                     return result;
2870             }
2871         }
2872         // https://semver.org/#spec-item-11
2873         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2874         // > of the preceding identifiers are equal.
2875         return ts.compareValues(left.length, right.length);
2876     }
2877     /**
2878      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2879      */
2880     var VersionRange = /** @class */ (function () {
2881         function VersionRange(spec) {
2882             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2883         }
2884         VersionRange.tryParse = function (text) {
2885             var sets = parseRange(text);
2886             if (sets) {
2887                 var range = new VersionRange("");
2888                 range._alternatives = sets;
2889                 return range;
2890             }
2891             return undefined;
2892         };
2893         VersionRange.prototype.test = function (version) {
2894             if (typeof version === "string")
2895                 version = new Version(version);
2896             return testDisjunction(version, this._alternatives);
2897         };
2898         VersionRange.prototype.toString = function () {
2899             return formatDisjunction(this._alternatives);
2900         };
2901         return VersionRange;
2902     }());
2903     ts.VersionRange = VersionRange;
2904     // https://github.com/npm/node-semver#range-grammar
2905     //
2906     // range-set    ::= range ( logical-or range ) *
2907     // range        ::= hyphen | simple ( ' ' simple ) * | ''
2908     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
2909     var logicalOrRegExp = /\s*\|\|\s*/g;
2910     var whitespaceRegExp = /\s+/g;
2911     // https://github.com/npm/node-semver#range-grammar
2912     //
2913     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2914     // xr           ::= 'x' | 'X' | '*' | nr
2915     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2916     // qualifier    ::= ( '-' pre )? ( '+' build )?
2917     // pre          ::= parts
2918     // build        ::= parts
2919     // parts        ::= part ( '.' part ) *
2920     // part         ::= nr | [-0-9A-Za-z]+
2921     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2922     // https://github.com/npm/node-semver#range-grammar
2923     //
2924     // hyphen       ::= partial ' - ' partial
2925     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2926     // https://github.com/npm/node-semver#range-grammar
2927     //
2928     // simple       ::= primitive | partial | tilde | caret
2929     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2930     // tilde        ::= '~' partial
2931     // caret        ::= '^' partial
2932     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2933     function parseRange(text) {
2934         var alternatives = [];
2935         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
2936             var range = _a[_i];
2937             if (!range)
2938                 continue;
2939             var comparators = [];
2940             var match = hyphenRegExp.exec(range);
2941             if (match) {
2942                 if (!parseHyphen(match[1], match[2], comparators))
2943                     return undefined;
2944             }
2945             else {
2946                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
2947                     var simple = _c[_b];
2948                     var match_1 = rangeRegExp.exec(simple);
2949                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
2950                         return undefined;
2951                 }
2952             }
2953             alternatives.push(comparators);
2954         }
2955         return alternatives;
2956     }
2957     function parsePartial(text) {
2958         var match = partialRegExp.exec(text);
2959         if (!match)
2960             return undefined;
2961         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];
2962         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);
2963         return { version: version, major: major, minor: minor, patch: patch };
2964     }
2965     function parseHyphen(left, right, comparators) {
2966         var leftResult = parsePartial(left);
2967         if (!leftResult)
2968             return false;
2969         var rightResult = parsePartial(right);
2970         if (!rightResult)
2971             return false;
2972         if (!isWildcard(leftResult.major)) {
2973             comparators.push(createComparator(">=", leftResult.version));
2974         }
2975         if (!isWildcard(rightResult.major)) {
2976             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
2977                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
2978                     createComparator("<=", rightResult.version));
2979         }
2980         return true;
2981     }
2982     function parseComparator(operator, text, comparators) {
2983         var result = parsePartial(text);
2984         if (!result)
2985             return false;
2986         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
2987         if (!isWildcard(major)) {
2988             switch (operator) {
2989                 case "~":
2990                     comparators.push(createComparator(">=", version));
2991                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
2992                         "minor")));
2993                     break;
2994                 case "^":
2995                     comparators.push(createComparator(">=", version));
2996                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
2997                         version.minor > 0 || isWildcard(patch) ? "minor" :
2998                             "patch")));
2999                     break;
3000                 case "<":
3001                 case ">=":
3002                     comparators.push(createComparator(operator, version));
3003                     break;
3004                 case "<=":
3005                 case ">":
3006                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
3007                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
3008                             createComparator(operator, version));
3009                     break;
3010                 case "=":
3011                 case undefined:
3012                     if (isWildcard(minor) || isWildcard(patch)) {
3013                         comparators.push(createComparator(">=", version));
3014                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
3015                     }
3016                     else {
3017                         comparators.push(createComparator("=", version));
3018                     }
3019                     break;
3020                 default:
3021                     // unrecognized
3022                     return false;
3023             }
3024         }
3025         else if (operator === "<" || operator === ">") {
3026             comparators.push(createComparator("<", Version.zero));
3027         }
3028         return true;
3029     }
3030     function isWildcard(part) {
3031         return part === "*" || part === "x" || part === "X";
3032     }
3033     function createComparator(operator, operand) {
3034         return { operator: operator, operand: operand };
3035     }
3036     function testDisjunction(version, alternatives) {
3037         // an empty disjunction is treated as "*" (all versions)
3038         if (alternatives.length === 0)
3039             return true;
3040         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
3041             var alternative = alternatives_1[_i];
3042             if (testAlternative(version, alternative))
3043                 return true;
3044         }
3045         return false;
3046     }
3047     function testAlternative(version, comparators) {
3048         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
3049             var comparator = comparators_1[_i];
3050             if (!testComparator(version, comparator.operator, comparator.operand))
3051                 return false;
3052         }
3053         return true;
3054     }
3055     function testComparator(version, operator, operand) {
3056         var cmp = version.compareTo(operand);
3057         switch (operator) {
3058             case "<": return cmp < 0;
3059             case "<=": return cmp <= 0;
3060             case ">": return cmp > 0;
3061             case ">=": return cmp >= 0;
3062             case "=": return cmp === 0;
3063             default: return ts.Debug.assertNever(operator);
3064         }
3065     }
3066     function formatDisjunction(alternatives) {
3067         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
3068     }
3069     function formatAlternative(comparators) {
3070         return ts.map(comparators, formatComparator).join(" ");
3071     }
3072     function formatComparator(comparator) {
3073         return "" + comparator.operator + comparator.operand;
3074     }
3075 })(ts || (ts = {}));
3076 var ts;
3077 (function (ts) {
3078     // token > SyntaxKind.Identifier => token is a keyword
3079     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
3080     var SyntaxKind;
3081     (function (SyntaxKind) {
3082         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
3083         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
3084         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
3085         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
3086         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
3087         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
3088         // We detect and preserve #! on the first line
3089         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
3090         // We detect and provide better error recovery when we encounter a git merge marker.  This
3091         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
3092         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
3093         // Literals
3094         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
3095         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
3096         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
3097         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
3098         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
3099         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
3100         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
3101         // Pseudo-literals
3102         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
3103         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
3104         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
3105         // Punctuation
3106         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
3107         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
3108         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
3109         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
3110         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
3111         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
3112         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
3113         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
3114         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
3115         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
3116         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
3117         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
3118         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
3119         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
3120         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
3121         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
3122         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
3123         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
3124         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
3125         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
3126         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
3127         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
3128         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
3129         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
3130         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
3131         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
3132         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
3133         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
3134         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
3135         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
3136         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
3137         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
3138         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
3139         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
3140         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
3141         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
3142         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
3143         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
3144         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
3145         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
3146         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
3147         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
3148         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
3149         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3150         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3151         // Assignments
3152         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
3153         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
3154         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
3155         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
3156         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
3157         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
3158         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3159         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3160         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3161         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3162         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3163         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3164         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
3165         // Identifiers and PrivateIdentifiers
3166         SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
3167         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
3168         // Reserved words
3169         SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
3170         SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
3171         SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
3172         SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
3173         SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
3174         SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
3175         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
3176         SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
3177         SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
3178         SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
3179         SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
3180         SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
3181         SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
3182         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
3183         SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
3184         SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
3185         SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
3186         SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
3187         SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
3188         SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
3189         SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
3190         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
3191         SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
3192         SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
3193         SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
3194         SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
3195         SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
3196         SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
3197         SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
3198         SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
3199         SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
3200         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
3201         SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
3202         SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
3203         SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
3204         SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
3205         // Strict mode reserved words
3206         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
3207         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
3208         SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
3209         SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
3210         SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
3211         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
3212         SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
3213         SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
3214         SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
3215         // Contextual keywords
3216         SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
3217         SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
3218         SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
3219         SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
3220         SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
3221         SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
3222         SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
3223         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
3224         SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
3225         SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
3226         SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
3227         SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
3228         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
3229         SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
3230         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
3231         SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
3232         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
3233         SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
3234         SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
3235         SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
3236         SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
3237         SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
3238         SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
3239         SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
3240         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
3241         SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
3242         SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
3243         SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
3244         SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
3245         SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
3246         SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
3247         // Parse tree nodes
3248         // Names
3249         SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
3250         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
3251         // Signature elements
3252         SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
3253         SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
3254         SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
3255         // TypeMember
3256         SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
3257         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
3258         SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
3259         SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
3260         SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
3261         SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
3262         SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
3263         SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
3264         SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
3265         SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
3266         // Type
3267         SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
3268         SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
3269         SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
3270         SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
3271         SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
3272         SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
3273         SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
3274         SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
3275         SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
3276         SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
3277         SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
3278         SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
3279         SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
3280         SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
3281         SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
3282         SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
3283         SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
3284         SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
3285         SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
3286         SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
3287         SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
3288         // Binding patterns
3289         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
3290         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
3291         SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
3292         // Expression
3293         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
3294         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
3295         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
3296         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
3297         SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
3298         SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
3299         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
3300         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
3301         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
3302         SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
3303         SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
3304         SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
3305         SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
3306         SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
3307         SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
3308         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
3309         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
3310         SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
3311         SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
3312         SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
3313         SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
3314         SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
3315         SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
3316         SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
3317         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
3318         SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
3319         SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
3320         SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
3321         SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
3322         // Misc
3323         SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
3324         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
3325         // Element
3326         SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
3327         SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
3328         SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
3329         SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
3330         SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
3331         SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
3332         SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
3333         SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
3334         SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
3335         SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
3336         SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
3337         SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
3338         SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
3339         SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
3340         SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
3341         SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
3342         SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
3343         SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
3344         SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
3345         SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
3346         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
3347         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
3348         SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
3349         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
3350         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
3351         SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
3352         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
3353         SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
3354         SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
3355         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
3356         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
3357         SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
3358         SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
3359         SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
3360         SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
3361         SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
3362         SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
3363         SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
3364         SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
3365         SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
3366         SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
3367         SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
3368         // Module references
3369         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
3370         // JSX
3371         SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
3372         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
3373         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
3374         SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
3375         SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
3376         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
3377         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
3378         SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
3379         SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
3380         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
3381         SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
3382         // Clauses
3383         SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
3384         SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
3385         SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
3386         SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
3387         // Property assignments
3388         SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
3389         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
3390         SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
3391         // Enum
3392         SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
3393         // Unparsed
3394         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
3395         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
3396         SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
3397         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
3398         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
3399         // Top-level nodes
3400         SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
3401         SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
3402         SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
3403         SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
3404         // JSDoc nodes
3405         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
3406         // The * type
3407         SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
3408         // The ? type
3409         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
3410         SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
3411         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
3412         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
3413         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
3414         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
3415         // https://jsdoc.app/about-namepaths.html
3416         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
3417         SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
3418         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
3419         SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
3420         SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
3421         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
3422         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag";
3423         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag";
3424         SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag";
3425         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag";
3426         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag";
3427         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag";
3428         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag";
3429         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag";
3430         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag";
3431         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag";
3432         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag";
3433         SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag";
3434         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag";
3435         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag";
3436         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag";
3437         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag";
3438         // Synthesized list
3439         SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList";
3440         // Transformation nodes
3441         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement";
3442         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression";
3443         SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression";
3444         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker";
3445         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker";
3446         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression";
3447         // Enum value count
3448         SyntaxKind[SyntaxKind["Count"] = 331] = "Count";
3449         // Markers
3450         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
3451         SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
3452         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
3453         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
3454         SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
3455         SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
3456         SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
3457         SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
3458         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
3459         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
3460         SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
3461         SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
3462         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
3463         SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
3464         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
3465         SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
3466         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
3467         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
3468         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
3469         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
3470         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
3471         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
3472         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
3473         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
3474         SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
3475         SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
3476         SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
3477         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
3478         SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode";
3479         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
3480         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode";
3481         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
3482         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
3483     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
3484     var NodeFlags;
3485     (function (NodeFlags) {
3486         NodeFlags[NodeFlags["None"] = 0] = "None";
3487         NodeFlags[NodeFlags["Let"] = 1] = "Let";
3488         NodeFlags[NodeFlags["Const"] = 2] = "Const";
3489         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
3490         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
3491         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
3492         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
3493         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
3494         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
3495         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
3496         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
3497         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
3498         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
3499         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
3500         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
3501         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
3502         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
3503         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
3504         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
3505         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
3506         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
3507         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
3508         // walking the tree if the flags are not set. However, these flags are just a approximation
3509         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
3510         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
3511         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
3512         // However, the removal operation should not occur often and in the case of the
3513         // removal, it is likely that users will add the import anyway.
3514         // The advantage of this approach is its simplicity. For the case of batch compilation,
3515         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3516         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
3517         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
3518         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
3519         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
3520         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
3521         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
3522         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
3523         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3524         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
3525         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
3526         // Parsing context flags
3527         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
3528         // Exclude these flags when parsing a Type
3529         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
3530         // Represents all flags that are potentially set once and
3531         // never cleared on SourceFiles which get re-used in between incremental parses.
3532         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3533         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
3534     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3535     var ModifierFlags;
3536     (function (ModifierFlags) {
3537         ModifierFlags[ModifierFlags["None"] = 0] = "None";
3538         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3539         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3540         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3541         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3542         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3543         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3544         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3545         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3546         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3547         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3548         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3549         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3550         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3551         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3552         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3553         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3554         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3555         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3556         ModifierFlags[ModifierFlags["All"] = 3071] = "All";
3557     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3558     var JsxFlags;
3559     (function (JsxFlags) {
3560         JsxFlags[JsxFlags["None"] = 0] = "None";
3561         /** An element from a named property of the JSX.IntrinsicElements interface */
3562         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3563         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3564         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3565         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3566     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3567     /* @internal */
3568     var RelationComparisonResult;
3569     (function (RelationComparisonResult) {
3570         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3571         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3572         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
3573         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
3574         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
3575         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
3576     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3577     /*@internal*/
3578     var GeneratedIdentifierFlags;
3579     (function (GeneratedIdentifierFlags) {
3580         // Kinds
3581         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3582         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3583         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3584         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3585         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3586         GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3587         // Flags
3588         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3589         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3590         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3591     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3592     var TokenFlags;
3593     (function (TokenFlags) {
3594         TokenFlags[TokenFlags["None"] = 0] = "None";
3595         /* @internal */
3596         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3597         /* @internal */
3598         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3599         /* @internal */
3600         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3601         /* @internal */
3602         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3603         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3604         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3605         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3606         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3607         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3608         /* @internal */
3609         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3610         /* @internal */
3611         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
3612         /* @internal */
3613         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
3614         /* @internal */
3615         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3616         /* @internal */
3617         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3618     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3619     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
3620     var FlowFlags;
3621     (function (FlowFlags) {
3622         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3623         FlowFlags[FlowFlags["Start"] = 2] = "Start";
3624         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3625         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3626         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3627         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3628         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3629         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3630         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3631         FlowFlags[FlowFlags["Call"] = 512] = "Call";
3632         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
3633         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
3634         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
3635         FlowFlags[FlowFlags["Label"] = 12] = "Label";
3636         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3637     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3638     /* @internal */
3639     var CommentDirectiveType;
3640     (function (CommentDirectiveType) {
3641         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
3642         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
3643     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
3644     var OperationCanceledException = /** @class */ (function () {
3645         function OperationCanceledException() {
3646         }
3647         return OperationCanceledException;
3648     }());
3649     ts.OperationCanceledException = OperationCanceledException;
3650     /*@internal*/
3651     var RefFileKind;
3652     (function (RefFileKind) {
3653         RefFileKind[RefFileKind["Import"] = 0] = "Import";
3654         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
3655         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
3656     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
3657     /* @internal */
3658     var StructureIsReused;
3659     (function (StructureIsReused) {
3660         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3661         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3662         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3663     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3664     /** Return code used by getEmitOutput function to indicate status of the function */
3665     var ExitStatus;
3666     (function (ExitStatus) {
3667         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
3668         // when -version or -help was provided, or this was a normal compilation, no diagnostics
3669         // were produced, and all outputs were generated successfully.
3670         ExitStatus[ExitStatus["Success"] = 0] = "Success";
3671         // Diagnostics were produced and because of them no code was generated.
3672         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3673         // Diagnostics were produced and outputs were generated in spite of them.
3674         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3675         // When build skipped because passed in project is invalid
3676         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
3677         // When build is skipped because project references form cycle
3678         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
3679         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
3680         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
3681     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3682     /* @internal */
3683     var UnionReduction;
3684     (function (UnionReduction) {
3685         UnionReduction[UnionReduction["None"] = 0] = "None";
3686         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3687         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3688     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3689     /* @internal */
3690     var ContextFlags;
3691     (function (ContextFlags) {
3692         ContextFlags[ContextFlags["None"] = 0] = "None";
3693         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
3694         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
3695         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
3696     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
3697     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3698     var NodeBuilderFlags;
3699     (function (NodeBuilderFlags) {
3700         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3701         // Options
3702         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3703         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3704         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3705         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3706         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3707         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3708         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3709         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3710         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3711         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3712         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3713         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3714         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3715         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3716         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3717         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3718         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3719         // Error handling
3720         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3721         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3722         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3723         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3724         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3725         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3726         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3727         // Errors (cont.)
3728         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3729         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3730         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3731         // State
3732         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3733         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3734         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3735         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3736     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3737     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3738     var TypeFormatFlags;
3739     (function (TypeFormatFlags) {
3740         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3741         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3742         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3743         // hole because there's a hole in node builder flags
3744         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3745         // hole because there's a hole in node builder flags
3746         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3747         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3748         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3749         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3750         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3751         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3752         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3753         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3754         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3755         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3756         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3757         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3758         // Error Handling
3759         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3760         // TypeFormatFlags exclusive
3761         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3762         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3763         // State
3764         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3765         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3766         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3767         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3768         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3769         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
3770     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3771     var SymbolFormatFlags;
3772     (function (SymbolFormatFlags) {
3773         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3774         // Write symbols's type argument if it is instantiated symbol
3775         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
3776         //     var a: C<number>;
3777         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3778         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3779         // Use only external alias information to get the symbol name in the given context
3780         // eg.  module m { export class c { } } import x = m.c;
3781         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3782         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3783         // Build symbol name using any nodes needed, instead of just components of an entity name
3784         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3785         // Prefer aliases which are not directly visible
3786         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3787         // Skip building an accessible symbol chain
3788         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3789     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3790     /* @internal */
3791     var SymbolAccessibility;
3792     (function (SymbolAccessibility) {
3793         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3794         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3795         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3796     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3797     /* @internal */
3798     var SyntheticSymbolKind;
3799     (function (SyntheticSymbolKind) {
3800         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3801         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3802     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3803     var TypePredicateKind;
3804     (function (TypePredicateKind) {
3805         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3806         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3807         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
3808         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
3809     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3810     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3811     /* @internal */
3812     var TypeReferenceSerializationKind;
3813     (function (TypeReferenceSerializationKind) {
3814         // The TypeReferenceNode could not be resolved.
3815         // The type name should be emitted using a safe fallback.
3816         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3817         // The TypeReferenceNode resolves to a type with a constructor
3818         // function that can be reached at runtime (e.g. a `class`
3819         // declaration or a `var` declaration for the static side
3820         // of a type, such as the global `Promise` type in lib.d.ts).
3821         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3822         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
3823         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3824         // The TypeReferenceNode resolves to a Number-like type.
3825         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3826         // The TypeReferenceNode resolves to a BigInt-like type.
3827         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3828         // The TypeReferenceNode resolves to a String-like type.
3829         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3830         // The TypeReferenceNode resolves to a Boolean-like type.
3831         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3832         // The TypeReferenceNode resolves to an Array-like type.
3833         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3834         // The TypeReferenceNode resolves to the ESSymbol type.
3835         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3836         // The TypeReferenceNode resolved to the global Promise constructor symbol.
3837         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3838         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
3839         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3840         // The TypeReferenceNode resolves to any other type.
3841         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3842     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3843     var SymbolFlags;
3844     (function (SymbolFlags) {
3845         SymbolFlags[SymbolFlags["None"] = 0] = "None";
3846         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3847         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3848         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3849         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3850         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3851         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3852         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3853         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3854         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3855         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3856         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3857         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3858         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3859         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3860         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3861         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3862         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3863         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3864         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3865         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3866         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3867         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3868         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3869         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3870         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3871         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3872         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3873         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3874         /* @internal */
3875         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3876         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3877         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3878         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
3879         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
3880         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3881         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3882         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3883         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3884         // same name, or any other value that is not a variable, e.g. ValueModule or Class
3885         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
3886         // Block-scoped declarations are not allowed to be re-declared
3887         // they can not merge with anything in the value space
3888         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
3889         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
3890         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3891         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
3892         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
3893         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
3894         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
3895         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
3896         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
3897         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3898         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3899         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
3900         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
3901         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
3902         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
3903         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
3904         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3905         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3906         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3907         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3908         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3909         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3910         /* @internal */
3911         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
3912         /* @internal */
3913         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
3914         /* @internal */
3915         // The set of things we consider semantically classifiable.  Used to speed up the LS during
3916         // classification.
3917         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3918         /* @internal */
3919         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
3920     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3921     /* @internal */
3922     var EnumKind;
3923     (function (EnumKind) {
3924         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
3925         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
3926     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
3927     /* @internal */
3928     var CheckFlags;
3929     (function (CheckFlags) {
3930         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
3931         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
3932         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
3933         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
3934         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
3935         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
3936         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
3937         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
3938         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
3939         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
3940         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
3941         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
3942         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
3943         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
3944         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
3945         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
3946         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
3947         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
3948         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
3949         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
3950         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
3951         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
3952         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
3953     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
3954     var InternalSymbolName;
3955     (function (InternalSymbolName) {
3956         InternalSymbolName["Call"] = "__call";
3957         InternalSymbolName["Constructor"] = "__constructor";
3958         InternalSymbolName["New"] = "__new";
3959         InternalSymbolName["Index"] = "__index";
3960         InternalSymbolName["ExportStar"] = "__export";
3961         InternalSymbolName["Global"] = "__global";
3962         InternalSymbolName["Missing"] = "__missing";
3963         InternalSymbolName["Type"] = "__type";
3964         InternalSymbolName["Object"] = "__object";
3965         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
3966         InternalSymbolName["Class"] = "__class";
3967         InternalSymbolName["Function"] = "__function";
3968         InternalSymbolName["Computed"] = "__computed";
3969         InternalSymbolName["Resolving"] = "__resolving__";
3970         InternalSymbolName["ExportEquals"] = "export=";
3971         InternalSymbolName["Default"] = "default";
3972         InternalSymbolName["This"] = "this";
3973     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
3974     /* @internal */
3975     var NodeCheckFlags;
3976     (function (NodeCheckFlags) {
3977         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
3978         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
3979         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
3980         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
3981         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
3982         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
3983         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
3984         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
3985         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
3986         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
3987         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
3988         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
3989         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
3990         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
3991         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
3992         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
3993         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
3994         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
3995         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
3996         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
3997         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
3998         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
3999         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
4000     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
4001     var TypeFlags;
4002     (function (TypeFlags) {
4003         TypeFlags[TypeFlags["Any"] = 1] = "Any";
4004         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
4005         TypeFlags[TypeFlags["String"] = 4] = "String";
4006         TypeFlags[TypeFlags["Number"] = 8] = "Number";
4007         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
4008         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
4009         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
4010         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
4011         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
4012         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
4013         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
4014         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
4015         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
4016         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
4017         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
4018         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
4019         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
4020         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
4021         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
4022         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
4023         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
4024         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
4025         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
4026         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
4027         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
4028         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
4029         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
4030         /* @internal */
4031         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
4032         /* @internal */
4033         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
4034         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
4035         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
4036         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
4037         /* @internal */
4038         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
4039         /* @internal */
4040         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
4041         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
4042         /* @internal */
4043         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
4044         /* @internal */
4045         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
4046         TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
4047         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
4048         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
4049         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
4050         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
4051         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
4052         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
4053         /* @internal */
4054         TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
4055         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
4056         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
4057         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
4058         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
4059         TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
4060         TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
4061         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
4062         /* @internal */
4063         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
4064         /* @internal */
4065         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
4066         /* @internal */
4067         TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
4068         // 'Narrowable' types are types where narrowing actually narrows.
4069         // This *should* be every type other than null, undefined, void, and never
4070         TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
4071         TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
4072         /* @internal */
4073         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
4074         // The following flags are aggregated during union and intersection type construction
4075         /* @internal */
4076         TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
4077         // The following flags are used for different purposes during union and intersection type construction
4078         /* @internal */
4079         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
4080         /* @internal */
4081         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
4082         /* @internal */
4083         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
4084         /* @internal */
4085         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
4086     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
4087     var ObjectFlags;
4088     (function (ObjectFlags) {
4089         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
4090         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
4091         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
4092         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
4093         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
4094         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
4095         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
4096         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
4097         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
4098         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
4099         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
4100         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
4101         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
4102         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
4103         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
4104         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
4105         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
4106         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
4107         /* @internal */
4108         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
4109         /* @internal */
4110         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
4111         /* @internal */
4112         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
4113         /* @internal */
4114         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
4115         /* @internal */
4116         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
4117         /* @internal */
4118         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4119         /* @internal */
4120         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
4121         /* @internal */
4122         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
4123         /* @internal */
4124         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
4125         /* @internal */
4126         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
4127         /* @internal */
4128         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
4129         /* @internal */
4130         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
4131         /* @internal */
4132         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
4133         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
4134         /* @internal */
4135         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
4136         /* @internal */
4137         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
4138     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
4139     /* @internal */
4140     var VarianceFlags;
4141     (function (VarianceFlags) {
4142         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
4143         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
4144         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
4145         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
4146         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
4147         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
4148         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
4149         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4150         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4151     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4152     /* @internal */
4153     var JsxReferenceKind;
4154     (function (JsxReferenceKind) {
4155         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4156         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4157         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4158     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4159     var SignatureKind;
4160     (function (SignatureKind) {
4161         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4162         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4163     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4164     /* @internal */
4165     var SignatureFlags;
4166     (function (SignatureFlags) {
4167         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4168         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4169         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4170         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4171         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4172         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4173         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4174         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4175         // instantiating the return type.
4176         SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
4177         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4178     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4179     var IndexKind;
4180     (function (IndexKind) {
4181         IndexKind[IndexKind["String"] = 0] = "String";
4182         IndexKind[IndexKind["Number"] = 1] = "Number";
4183     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4184     /* @internal */
4185     var TypeMapKind;
4186     (function (TypeMapKind) {
4187         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4188         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4189         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4190         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4191         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4192     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4193     var InferencePriority;
4194     (function (InferencePriority) {
4195         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4196         InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
4197         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
4198         InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
4199         InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
4200         InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
4201         InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
4202         InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
4203         InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
4204         InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
4205         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
4206         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4207     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4208     /* @internal */
4209     var InferenceFlags;
4210     (function (InferenceFlags) {
4211         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4212         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4213         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4214         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4215     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4216     /**
4217      * Ternary values are defined such that
4218      * x & y is False if either x or y is False.
4219      * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
4220      * x & y is True if both x and y are True.
4221      * x | y is False if both x and y are False.
4222      * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
4223      * x | y is True if either x or y is True.
4224      */
4225     /* @internal */
4226     var Ternary;
4227     (function (Ternary) {
4228         Ternary[Ternary["False"] = 0] = "False";
4229         Ternary[Ternary["Maybe"] = 1] = "Maybe";
4230         Ternary[Ternary["True"] = -1] = "True";
4231     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4232     /* @internal */
4233     var AssignmentDeclarationKind;
4234     (function (AssignmentDeclarationKind) {
4235         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4236         /// exports.name = expr
4237         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4238         /// module.exports = expr
4239         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4240         /// className.prototype.name = expr
4241         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4242         /// this.name = expr
4243         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4244         // F.name = expr
4245         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4246         // F.prototype = { ... }
4247         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4248         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4249         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4250         // Object.defineProperty(x, 'name', { get: Function });
4251         // Object.defineProperty(x, 'name', { set: Function });
4252         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4253         // Object.defineProperty(exports || module.exports, 'name', ...);
4254         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4255         // Object.defineProperty(Foo.prototype, 'name', ...);
4256         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4257     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4258     var DiagnosticCategory;
4259     (function (DiagnosticCategory) {
4260         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4261         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4262         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4263         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4264     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4265     /* @internal */
4266     function diagnosticCategoryName(d, lowerCase) {
4267         if (lowerCase === void 0) { lowerCase = true; }
4268         var name = DiagnosticCategory[d.category];
4269         return lowerCase ? name.toLowerCase() : name;
4270     }
4271     ts.diagnosticCategoryName = diagnosticCategoryName;
4272     var ModuleResolutionKind;
4273     (function (ModuleResolutionKind) {
4274         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4275         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4276     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4277     var WatchFileKind;
4278     (function (WatchFileKind) {
4279         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4280         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4281         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4282         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4283         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4284     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4285     var WatchDirectoryKind;
4286     (function (WatchDirectoryKind) {
4287         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4288         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4289         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4290     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4291     var PollingWatchKind;
4292     (function (PollingWatchKind) {
4293         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4294         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4295         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4296     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4297     var ModuleKind;
4298     (function (ModuleKind) {
4299         ModuleKind[ModuleKind["None"] = 0] = "None";
4300         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4301         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4302         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4303         ModuleKind[ModuleKind["System"] = 4] = "System";
4304         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4305         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4306         //       module kind).
4307         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4308         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4309         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4310     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4311     var JsxEmit;
4312     (function (JsxEmit) {
4313         JsxEmit[JsxEmit["None"] = 0] = "None";
4314         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4315         JsxEmit[JsxEmit["React"] = 2] = "React";
4316         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4317     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4318     var ImportsNotUsedAsValues;
4319     (function (ImportsNotUsedAsValues) {
4320         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4321         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4322         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4323     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4324     var NewLineKind;
4325     (function (NewLineKind) {
4326         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4327         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4328     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4329     var ScriptKind;
4330     (function (ScriptKind) {
4331         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4332         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4333         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4334         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4335         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4336         ScriptKind[ScriptKind["External"] = 5] = "External";
4337         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4338         /**
4339          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4340          * Deferred extensions are going to be included in all project contexts.
4341          */
4342         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4343     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4344     var ScriptTarget;
4345     (function (ScriptTarget) {
4346         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4347         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4348         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4349         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4350         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4351         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4352         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4353         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4354         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4355         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4356         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4357     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4358     var LanguageVariant;
4359     (function (LanguageVariant) {
4360         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4361         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4362     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4363     var WatchDirectoryFlags;
4364     (function (WatchDirectoryFlags) {
4365         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4366         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4367     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4368     /* @internal */
4369     var CharacterCodes;
4370     (function (CharacterCodes) {
4371         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4372         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4373         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4374         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
4375         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
4376         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
4377         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
4378         // Unicode 3.0 space characters
4379         CharacterCodes[CharacterCodes["space"] = 32] = "space";
4380         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
4381         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
4382         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
4383         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
4384         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
4385         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
4386         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
4387         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
4388         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
4389         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
4390         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
4391         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
4392         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
4393         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
4394         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
4395         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
4396         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
4397         CharacterCodes[CharacterCodes["_"] = 95] = "_";
4398         CharacterCodes[CharacterCodes["$"] = 36] = "$";
4399         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
4400         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
4401         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
4402         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
4403         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
4404         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
4405         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
4406         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
4407         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
4408         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
4409         CharacterCodes[CharacterCodes["a"] = 97] = "a";
4410         CharacterCodes[CharacterCodes["b"] = 98] = "b";
4411         CharacterCodes[CharacterCodes["c"] = 99] = "c";
4412         CharacterCodes[CharacterCodes["d"] = 100] = "d";
4413         CharacterCodes[CharacterCodes["e"] = 101] = "e";
4414         CharacterCodes[CharacterCodes["f"] = 102] = "f";
4415         CharacterCodes[CharacterCodes["g"] = 103] = "g";
4416         CharacterCodes[CharacterCodes["h"] = 104] = "h";
4417         CharacterCodes[CharacterCodes["i"] = 105] = "i";
4418         CharacterCodes[CharacterCodes["j"] = 106] = "j";
4419         CharacterCodes[CharacterCodes["k"] = 107] = "k";
4420         CharacterCodes[CharacterCodes["l"] = 108] = "l";
4421         CharacterCodes[CharacterCodes["m"] = 109] = "m";
4422         CharacterCodes[CharacterCodes["n"] = 110] = "n";
4423         CharacterCodes[CharacterCodes["o"] = 111] = "o";
4424         CharacterCodes[CharacterCodes["p"] = 112] = "p";
4425         CharacterCodes[CharacterCodes["q"] = 113] = "q";
4426         CharacterCodes[CharacterCodes["r"] = 114] = "r";
4427         CharacterCodes[CharacterCodes["s"] = 115] = "s";
4428         CharacterCodes[CharacterCodes["t"] = 116] = "t";
4429         CharacterCodes[CharacterCodes["u"] = 117] = "u";
4430         CharacterCodes[CharacterCodes["v"] = 118] = "v";
4431         CharacterCodes[CharacterCodes["w"] = 119] = "w";
4432         CharacterCodes[CharacterCodes["x"] = 120] = "x";
4433         CharacterCodes[CharacterCodes["y"] = 121] = "y";
4434         CharacterCodes[CharacterCodes["z"] = 122] = "z";
4435         CharacterCodes[CharacterCodes["A"] = 65] = "A";
4436         CharacterCodes[CharacterCodes["B"] = 66] = "B";
4437         CharacterCodes[CharacterCodes["C"] = 67] = "C";
4438         CharacterCodes[CharacterCodes["D"] = 68] = "D";
4439         CharacterCodes[CharacterCodes["E"] = 69] = "E";
4440         CharacterCodes[CharacterCodes["F"] = 70] = "F";
4441         CharacterCodes[CharacterCodes["G"] = 71] = "G";
4442         CharacterCodes[CharacterCodes["H"] = 72] = "H";
4443         CharacterCodes[CharacterCodes["I"] = 73] = "I";
4444         CharacterCodes[CharacterCodes["J"] = 74] = "J";
4445         CharacterCodes[CharacterCodes["K"] = 75] = "K";
4446         CharacterCodes[CharacterCodes["L"] = 76] = "L";
4447         CharacterCodes[CharacterCodes["M"] = 77] = "M";
4448         CharacterCodes[CharacterCodes["N"] = 78] = "N";
4449         CharacterCodes[CharacterCodes["O"] = 79] = "O";
4450         CharacterCodes[CharacterCodes["P"] = 80] = "P";
4451         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
4452         CharacterCodes[CharacterCodes["R"] = 82] = "R";
4453         CharacterCodes[CharacterCodes["S"] = 83] = "S";
4454         CharacterCodes[CharacterCodes["T"] = 84] = "T";
4455         CharacterCodes[CharacterCodes["U"] = 85] = "U";
4456         CharacterCodes[CharacterCodes["V"] = 86] = "V";
4457         CharacterCodes[CharacterCodes["W"] = 87] = "W";
4458         CharacterCodes[CharacterCodes["X"] = 88] = "X";
4459         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
4460         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
4461         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
4462         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
4463         CharacterCodes[CharacterCodes["at"] = 64] = "at";
4464         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
4465         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
4466         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
4467         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
4468         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
4469         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
4470         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
4471         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
4472         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
4473         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
4474         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
4475         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
4476         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
4477         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
4478         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
4479         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
4480         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
4481         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
4482         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
4483         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
4484         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
4485         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
4486         CharacterCodes[CharacterCodes["question"] = 63] = "question";
4487         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
4488         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
4489         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
4490         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
4491         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
4492         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
4493         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
4494         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
4495         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
4496     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
4497     var Extension;
4498     (function (Extension) {
4499         Extension["Ts"] = ".ts";
4500         Extension["Tsx"] = ".tsx";
4501         Extension["Dts"] = ".d.ts";
4502         Extension["Js"] = ".js";
4503         Extension["Jsx"] = ".jsx";
4504         Extension["Json"] = ".json";
4505         Extension["TsBuildInfo"] = ".tsbuildinfo";
4506     })(Extension = ts.Extension || (ts.Extension = {}));
4507     /* @internal */
4508     var TransformFlags;
4509     (function (TransformFlags) {
4510         TransformFlags[TransformFlags["None"] = 0] = "None";
4511         // Facts
4512         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
4513         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
4514         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
4515         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
4516         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
4517         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
4518         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
4519         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
4520         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
4521         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
4522         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
4523         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
4524         // Markers
4525         // - Flags used to indicate that a subtree contains a specific transformation.
4526         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
4527         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
4528         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
4529         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
4530         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
4531         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
4532         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
4533         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
4534         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
4535         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
4536         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
4537         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
4538         // Please leave this as 1 << 29.
4539         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
4540         // It is a good reminder of how much room we have left
4541         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4542         // Assertions
4543         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
4544         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
4545         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
4546         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
4547         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
4548         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
4549         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
4550         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
4551         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
4552         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
4553         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
4554         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
4555         // Scope Exclusions
4556         // - Bitmasks that exclude flags from propagating out of a specific context
4557         //   into the subtree flags of their container.
4558         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
4559         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
4560         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
4561         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
4562         TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
4563         TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
4564         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
4565         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
4566         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
4567         TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
4568         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
4569         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
4570         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
4571         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
4572         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
4573         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
4574         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
4575         // Propagating flags
4576         // - Bitmasks for flags that should propagate from a child
4577         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
4578         // Masks
4579         // - Additional bitmasks
4580     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
4581     var EmitFlags;
4582     (function (EmitFlags) {
4583         EmitFlags[EmitFlags["None"] = 0] = "None";
4584         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
4585         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
4586         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
4587         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
4588         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
4589         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
4590         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
4591         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
4592         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
4593         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
4594         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
4595         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
4596         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
4597         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
4598         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
4599         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
4600         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
4601         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
4602         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
4603         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
4604         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
4605         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
4606         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
4607         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
4608         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
4609         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
4610         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
4611         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
4612         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
4613         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
4614         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
4615     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
4616     /**
4617      * Used by the checker, this enum keeps track of external emit helpers that should be type
4618      * checked.
4619      */
4620     /* @internal */
4621     var ExternalEmitHelpers;
4622     (function (ExternalEmitHelpers) {
4623         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
4624         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
4625         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
4626         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
4627         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
4628         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
4629         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
4630         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
4631         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
4632         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
4633         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
4634         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
4635         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
4636         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
4637         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
4638         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
4639         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
4640         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
4641         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
4642         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
4643         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding";
4644         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
4645         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper";
4646         // Helpers included by ES2015 for..of
4647         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
4648         // Helpers included by ES2017 for..await..of
4649         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
4650         // Helpers included by ES2017 async generators
4651         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
4652         // Helpers included by yield* in ES2017 async generators
4653         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
4654         // Helpers included by ES2015 spread
4655         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
4656     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
4657     var EmitHint;
4658     (function (EmitHint) {
4659         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
4660         EmitHint[EmitHint["Expression"] = 1] = "Expression";
4661         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
4662         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
4663         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
4664         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
4665         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
4666     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
4667     /* @internal */
4668     var LexicalEnvironmentFlags;
4669     (function (LexicalEnvironmentFlags) {
4670         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
4671         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
4672         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
4673     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
4674     /*@internal*/
4675     var BundleFileSectionKind;
4676     (function (BundleFileSectionKind) {
4677         BundleFileSectionKind["Prologue"] = "prologue";
4678         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
4679         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4680         BundleFileSectionKind["Reference"] = "reference";
4681         BundleFileSectionKind["Type"] = "type";
4682         BundleFileSectionKind["Lib"] = "lib";
4683         BundleFileSectionKind["Prepend"] = "prepend";
4684         BundleFileSectionKind["Text"] = "text";
4685         BundleFileSectionKind["Internal"] = "internal";
4686         // comments?
4687     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4688     var ListFormat;
4689     (function (ListFormat) {
4690         ListFormat[ListFormat["None"] = 0] = "None";
4691         // Line separators
4692         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4693         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4694         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4695         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4696         // Delimiters
4697         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4698         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4699         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4700         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4701         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4702         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4703         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4704         // Whitespace
4705         ListFormat[ListFormat["Indented"] = 128] = "Indented";
4706         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4707         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4708         // Brackets/Braces
4709         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4710         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4711         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4712         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4713         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4714         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4715         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4716         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4717         // Other
4718         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4719         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4720         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4721         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4722         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4723         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
4724         // Precomputed Formats
4725         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4726         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4727         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4728         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4729         ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
4730         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4731         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4732         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4733         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4734         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4735         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4736         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4737         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4738         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4739         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4740         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4741         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4742         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4743         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4744         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4745         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4746         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4747         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4748         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4749         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4750         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4751         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4752         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4753         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4754         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4755         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4756         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
4757         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4758         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4759         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4760         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4761         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4762     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4763     /* @internal */
4764     var PragmaKindFlags;
4765     (function (PragmaKindFlags) {
4766         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4767         /**
4768          * Triple slash comment of the form
4769          * /// <pragma-name argname="value" />
4770          */
4771         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4772         /**
4773          * Single line comment of the form
4774          * // @pragma-name argval1 argval2
4775          * or
4776          * /// @pragma-name argval1 argval2
4777          */
4778         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4779         /**
4780          * Multiline non-jsdoc pragma of the form
4781          * /* @pragma-name argval1 argval2 * /
4782          */
4783         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4784         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4785         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4786     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4787     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4788     //  fancy effectively defining it twice, once in value-space and once in type-space
4789     /* @internal */
4790     ts.commentPragmas = {
4791         "reference": {
4792             args: [
4793                 { name: "types", optional: true, captureSpan: true },
4794                 { name: "lib", optional: true, captureSpan: true },
4795                 { name: "path", optional: true, captureSpan: true },
4796                 { name: "no-default-lib", optional: true }
4797             ],
4798             kind: 1 /* TripleSlashXML */
4799         },
4800         "amd-dependency": {
4801             args: [{ name: "path" }, { name: "name", optional: true }],
4802             kind: 1 /* TripleSlashXML */
4803         },
4804         "amd-module": {
4805             args: [{ name: "name" }],
4806             kind: 1 /* TripleSlashXML */
4807         },
4808         "ts-check": {
4809             kind: 2 /* SingleLine */
4810         },
4811         "ts-nocheck": {
4812             kind: 2 /* SingleLine */
4813         },
4814         "jsx": {
4815             args: [{ name: "factory" }],
4816             kind: 4 /* MultiLine */
4817         },
4818     };
4819 })(ts || (ts = {}));
4820 var ts;
4821 (function (ts) {
4822     /**
4823      * djb2 hashing algorithm
4824      * http://www.cse.yorku.ca/~oz/hash.html
4825      */
4826     /* @internal */
4827     function generateDjb2Hash(data) {
4828         var acc = 5381;
4829         for (var i = 0; i < data.length; i++) {
4830             acc = ((acc << 5) + acc) + data.charCodeAt(i);
4831         }
4832         return acc.toString();
4833     }
4834     ts.generateDjb2Hash = generateDjb2Hash;
4835     /**
4836      * Set a high stack trace limit to provide more information in case of an error.
4837      * Called for command-line and server use cases.
4838      * Not called if TypeScript is used as a library.
4839      */
4840     /* @internal */
4841     function setStackTraceLimit() {
4842         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4843             Error.stackTraceLimit = 100;
4844         }
4845     }
4846     ts.setStackTraceLimit = setStackTraceLimit;
4847     var FileWatcherEventKind;
4848     (function (FileWatcherEventKind) {
4849         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4850         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4851         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4852     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4853     /* @internal */
4854     var PollingInterval;
4855     (function (PollingInterval) {
4856         PollingInterval[PollingInterval["High"] = 2000] = "High";
4857         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4858         PollingInterval[PollingInterval["Low"] = 250] = "Low";
4859     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4860     /* @internal */
4861     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4862     function createPollingIntervalBasedLevels(levels) {
4863         var _a;
4864         return _a = {},
4865             _a[PollingInterval.Low] = levels.Low,
4866             _a[PollingInterval.Medium] = levels.Medium,
4867             _a[PollingInterval.High] = levels.High,
4868             _a;
4869     }
4870     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4871     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4872     /* @internal */
4873     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4874     /* @internal */
4875     function setCustomPollingValues(system) {
4876         if (!system.getEnvironmentVariable) {
4877             return;
4878         }
4879         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4880         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4881         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4882         function getLevel(envVar, level) {
4883             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4884         }
4885         function getCustomLevels(baseVariable) {
4886             var customLevels;
4887             setCustomLevel("Low");
4888             setCustomLevel("Medium");
4889             setCustomLevel("High");
4890             return customLevels;
4891             function setCustomLevel(level) {
4892                 var customLevel = getLevel(baseVariable, level);
4893                 if (customLevel) {
4894                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
4895                 }
4896             }
4897         }
4898         function setCustomLevels(baseVariable, levels) {
4899             var customLevels = getCustomLevels(baseVariable);
4900             if (customLevels) {
4901                 setLevel("Low");
4902                 setLevel("Medium");
4903                 setLevel("High");
4904                 return true;
4905             }
4906             return false;
4907             function setLevel(level) {
4908                 levels[level] = customLevels[level] || levels[level];
4909             }
4910         }
4911         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
4912             var customLevels = getCustomLevels(baseVariable);
4913             return (pollingIntervalChanged || customLevels) &&
4914                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
4915         }
4916     }
4917     ts.setCustomPollingValues = setCustomPollingValues;
4918     /* @internal */
4919     function createDynamicPriorityPollingWatchFile(host) {
4920         var watchedFiles = [];
4921         var changedFilesInLastPoll = [];
4922         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
4923         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
4924         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
4925         return watchFile;
4926         function watchFile(fileName, callback, defaultPollingInterval) {
4927             var file = {
4928                 fileName: fileName,
4929                 callback: callback,
4930                 unchangedPolls: 0,
4931                 mtime: getModifiedTime(fileName)
4932             };
4933             watchedFiles.push(file);
4934             addToPollingIntervalQueue(file, defaultPollingInterval);
4935             return {
4936                 close: function () {
4937                     file.isClosed = true;
4938                     // Remove from watchedFiles
4939                     ts.unorderedRemoveItem(watchedFiles, file);
4940                     // Do not update polling interval queue since that will happen as part of polling
4941                 }
4942             };
4943         }
4944         function createPollingIntervalQueue(pollingInterval) {
4945             var queue = [];
4946             queue.pollingInterval = pollingInterval;
4947             queue.pollIndex = 0;
4948             queue.pollScheduled = false;
4949             return queue;
4950         }
4951         function pollPollingIntervalQueue(queue) {
4952             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
4953             // Set the next polling index and timeout
4954             if (queue.length) {
4955                 scheduleNextPoll(queue.pollingInterval);
4956             }
4957             else {
4958                 ts.Debug.assert(queue.pollIndex === 0);
4959                 queue.pollScheduled = false;
4960             }
4961         }
4962         function pollLowPollingIntervalQueue(queue) {
4963             // Always poll complete list of changedFilesInLastPoll
4964             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
4965             // Finally do the actual polling of the queue
4966             pollPollingIntervalQueue(queue);
4967             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
4968             // as pollPollingIntervalQueue wont schedule for next poll
4969             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
4970                 scheduleNextPoll(PollingInterval.Low);
4971             }
4972         }
4973         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
4974             // Max visit would be all elements of the queue
4975             var needsVisit = queue.length;
4976             var definedValueCopyToIndex = pollIndex;
4977             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
4978                 var watchedFile = queue[pollIndex];
4979                 if (!watchedFile) {
4980                     continue;
4981                 }
4982                 else if (watchedFile.isClosed) {
4983                     queue[pollIndex] = undefined;
4984                     continue;
4985                 }
4986                 polled++;
4987                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
4988                 if (watchedFile.isClosed) {
4989                     // Closed watcher as part of callback
4990                     queue[pollIndex] = undefined;
4991                 }
4992                 else if (fileChanged) {
4993                     watchedFile.unchangedPolls = 0;
4994                     // Changed files go to changedFilesInLastPoll queue
4995                     if (queue !== changedFilesInLastPoll) {
4996                         queue[pollIndex] = undefined;
4997                         addChangedFileToLowPollingIntervalQueue(watchedFile);
4998                     }
4999                 }
5000                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
5001                     watchedFile.unchangedPolls++;
5002                 }
5003                 else if (queue === changedFilesInLastPoll) {
5004                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
5005                     watchedFile.unchangedPolls = 1;
5006                     queue[pollIndex] = undefined;
5007                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
5008                 }
5009                 else if (pollingInterval !== PollingInterval.High) {
5010                     watchedFile.unchangedPolls++;
5011                     queue[pollIndex] = undefined;
5012                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
5013                 }
5014                 if (queue[pollIndex]) {
5015                     // Copy this file to the non hole location
5016                     if (definedValueCopyToIndex < pollIndex) {
5017                         queue[definedValueCopyToIndex] = watchedFile;
5018                         queue[pollIndex] = undefined;
5019                     }
5020                     definedValueCopyToIndex++;
5021                 }
5022             }
5023             // Return next poll index
5024             return pollIndex;
5025             function nextPollIndex() {
5026                 pollIndex++;
5027                 if (pollIndex === queue.length) {
5028                     if (definedValueCopyToIndex < pollIndex) {
5029                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
5030                         queue.length = definedValueCopyToIndex;
5031                     }
5032                     pollIndex = 0;
5033                     definedValueCopyToIndex = 0;
5034                 }
5035             }
5036         }
5037         function pollingIntervalQueue(pollingInterval) {
5038             switch (pollingInterval) {
5039                 case PollingInterval.Low:
5040                     return lowPollingIntervalQueue;
5041                 case PollingInterval.Medium:
5042                     return mediumPollingIntervalQueue;
5043                 case PollingInterval.High:
5044                     return highPollingIntervalQueue;
5045             }
5046         }
5047         function addToPollingIntervalQueue(file, pollingInterval) {
5048             pollingIntervalQueue(pollingInterval).push(file);
5049             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
5050         }
5051         function addChangedFileToLowPollingIntervalQueue(file) {
5052             changedFilesInLastPoll.push(file);
5053             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
5054         }
5055         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
5056             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
5057                 scheduleNextPoll(pollingInterval);
5058             }
5059         }
5060         function scheduleNextPoll(pollingInterval) {
5061             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
5062         }
5063         function getModifiedTime(fileName) {
5064             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
5065         }
5066     }
5067     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
5068     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
5069         // One file can have multiple watchers
5070         var fileWatcherCallbacks = ts.createMultiMap();
5071         var dirWatchers = ts.createMap();
5072         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
5073         return nonPollingWatchFile;
5074         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
5075             var filePath = toCanonicalName(fileName);
5076             fileWatcherCallbacks.add(filePath, callback);
5077             var dirPath = ts.getDirectoryPath(filePath) || ".";
5078             var watcher = dirWatchers.get(dirPath) ||
5079                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
5080             watcher.referenceCount++;
5081             return {
5082                 close: function () {
5083                     if (watcher.referenceCount === 1) {
5084                         watcher.close();
5085                         dirWatchers.delete(dirPath);
5086                     }
5087                     else {
5088                         watcher.referenceCount--;
5089                     }
5090                     fileWatcherCallbacks.remove(filePath, callback);
5091                 }
5092             };
5093         }
5094         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
5095             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
5096                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
5097                 if (!ts.isString(relativeFileName)) {
5098                     return;
5099                 }
5100                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
5101                 // Some applications save a working file via rename operations
5102                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
5103                 if (callbacks) {
5104                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
5105                         var fileCallback = callbacks_1[_i];
5106                         fileCallback(fileName, FileWatcherEventKind.Changed);
5107                     }
5108                 }
5109             }, 
5110             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
5111             watcher.referenceCount = 0;
5112             dirWatchers.set(dirPath, watcher);
5113             return watcher;
5114         }
5115     }
5116     /* @internal */
5117     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
5118         var cache = ts.createMap();
5119         var callbacksCache = ts.createMultiMap();
5120         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
5121         return function (fileName, callback, pollingInterval, options) {
5122             var path = toCanonicalFileName(fileName);
5123             var existing = cache.get(path);
5124             if (existing) {
5125                 existing.refCount++;
5126             }
5127             else {
5128                 cache.set(path, {
5129                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
5130                     refCount: 1
5131                 });
5132             }
5133             callbacksCache.add(path, callback);
5134             return {
5135                 close: function () {
5136                     var watcher = ts.Debug.checkDefined(cache.get(path));
5137                     callbacksCache.remove(path, callback);
5138                     watcher.refCount--;
5139                     if (watcher.refCount)
5140                         return;
5141                     cache.delete(path);
5142                     ts.closeFileWatcherOf(watcher);
5143                 }
5144             };
5145         };
5146     }
5147     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
5148     /**
5149      * Returns true if file status changed
5150      */
5151     /*@internal*/
5152     function onWatchedFileStat(watchedFile, modifiedTime) {
5153         var oldTime = watchedFile.mtime.getTime();
5154         var newTime = modifiedTime.getTime();
5155         if (oldTime !== newTime) {
5156             watchedFile.mtime = modifiedTime;
5157             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
5158             return true;
5159         }
5160         return false;
5161     }
5162     ts.onWatchedFileStat = onWatchedFileStat;
5163     /*@internal*/
5164     function getFileWatcherEventKind(oldTime, newTime) {
5165         return oldTime === 0
5166             ? FileWatcherEventKind.Created
5167             : newTime === 0
5168                 ? FileWatcherEventKind.Deleted
5169                 : FileWatcherEventKind.Changed;
5170     }
5171     ts.getFileWatcherEventKind = getFileWatcherEventKind;
5172     /*@internal*/
5173     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
5174     /*@internal*/
5175     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
5176     /*@internal*/
5177     function setSysLog(logger) {
5178         ts.sysLog = logger;
5179     }
5180     ts.setSysLog = setSysLog;
5181     /**
5182      * Watch the directory recursively using host provided method to watch child directories
5183      * that means if this is recursive watcher, watch the children directories as well
5184      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
5185      */
5186     /*@internal*/
5187     function createDirectoryWatcherSupportingRecursive(host) {
5188         var cache = ts.createMap();
5189         var callbackCache = ts.createMultiMap();
5190         var cacheToUpdateChildWatches = ts.createMap();
5191         var timerToUpdateChildWatches;
5192         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
5193         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
5194         return function (dirName, callback, recursive, options) { return recursive ?
5195             createDirectoryWatcher(dirName, options, callback) :
5196             host.watchDirectory(dirName, callback, recursive, options); };
5197         /**
5198          * Create the directory watcher for the dirPath.
5199          */
5200         function createDirectoryWatcher(dirName, options, callback) {
5201             var dirPath = toCanonicalFilePath(dirName);
5202             var directoryWatcher = cache.get(dirPath);
5203             if (directoryWatcher) {
5204                 directoryWatcher.refCount++;
5205             }
5206             else {
5207                 directoryWatcher = {
5208                     watcher: host.watchDirectory(dirName, function (fileName) {
5209                         if (isIgnoredPath(fileName))
5210                             return;
5211                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
5212                             // Call the actual callback
5213                             invokeCallbacks(dirPath, fileName);
5214                             // Iterate through existing children and update the watches if needed
5215                             updateChildWatches(dirName, dirPath, options);
5216                         }
5217                         else {
5218                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
5219                         }
5220                     }, /*recursive*/ false, options),
5221                     refCount: 1,
5222                     childWatches: ts.emptyArray
5223                 };
5224                 cache.set(dirPath, directoryWatcher);
5225                 updateChildWatches(dirName, dirPath, options);
5226             }
5227             var callbackToAdd = callback && { dirName: dirName, callback: callback };
5228             if (callbackToAdd) {
5229                 callbackCache.add(dirPath, callbackToAdd);
5230             }
5231             return {
5232                 dirName: dirName,
5233                 close: function () {
5234                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
5235                     if (callbackToAdd)
5236                         callbackCache.remove(dirPath, callbackToAdd);
5237                     directoryWatcher.refCount--;
5238                     if (directoryWatcher.refCount)
5239                         return;
5240                     cache.delete(dirPath);
5241                     ts.closeFileWatcherOf(directoryWatcher);
5242                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
5243                 }
5244             };
5245         }
5246         function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
5247             var fileName;
5248             var invokeMap;
5249             if (ts.isString(fileNameOrInvokeMap)) {
5250                 fileName = fileNameOrInvokeMap;
5251             }
5252             else {
5253                 invokeMap = fileNameOrInvokeMap;
5254             }
5255             // Call the actual callback
5256             callbackCache.forEach(function (callbacks, rootDirName) {
5257                 if (invokeMap && invokeMap.has(rootDirName))
5258                     return;
5259                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
5260                     if (invokeMap) {
5261                         invokeMap.set(rootDirName, true);
5262                     }
5263                     else {
5264                         callbacks.forEach(function (_a) {
5265                             var callback = _a.callback;
5266                             return callback(fileName);
5267                         });
5268                     }
5269                 }
5270             });
5271         }
5272         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
5273             // Iterate through existing children and update the watches if needed
5274             var parentWatcher = cache.get(dirPath);
5275             if (parentWatcher && host.directoryExists(dirName)) {
5276                 // Schedule the update and postpone invoke for callbacks
5277                 scheduleUpdateChildWatches(dirName, dirPath, options);
5278                 return;
5279             }
5280             // Call the actual callbacks and remove child watches
5281             invokeCallbacks(dirPath, fileName);
5282             removeChildWatches(parentWatcher);
5283         }
5284         function scheduleUpdateChildWatches(dirName, dirPath, options) {
5285             if (!cacheToUpdateChildWatches.has(dirPath)) {
5286                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
5287             }
5288             if (timerToUpdateChildWatches) {
5289                 host.clearTimeout(timerToUpdateChildWatches);
5290                 timerToUpdateChildWatches = undefined;
5291             }
5292             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
5293         }
5294         function onTimerToUpdateChildWatches() {
5295             timerToUpdateChildWatches = undefined;
5296             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
5297             var start = ts.timestamp();
5298             var invokeMap = ts.createMap();
5299             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
5300                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
5301                 ts.Debug.assert(!done);
5302                 cacheToUpdateChildWatches.delete(dirPath);
5303                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
5304                 // to ensure that all the changes are reflected at this time
5305                 invokeCallbacks(dirPath, invokeMap);
5306                 updateChildWatches(dirName, dirPath, options);
5307             }
5308             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
5309             callbackCache.forEach(function (callbacks, rootDirName) {
5310                 if (invokeMap.has(rootDirName)) {
5311                     callbacks.forEach(function (_a) {
5312                         var callback = _a.callback, dirName = _a.dirName;
5313                         return callback(dirName);
5314                     });
5315                 }
5316             });
5317             var elapsed = ts.timestamp() - start;
5318             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
5319         }
5320         function removeChildWatches(parentWatcher) {
5321             if (!parentWatcher)
5322                 return;
5323             var existingChildWatches = parentWatcher.childWatches;
5324             parentWatcher.childWatches = ts.emptyArray;
5325             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
5326                 var childWatcher = existingChildWatches_1[_i];
5327                 childWatcher.close();
5328                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
5329             }
5330         }
5331         function updateChildWatches(dirName, dirPath, options) {
5332             // Iterate through existing children and update the watches if needed
5333             var parentWatcher = cache.get(dirPath);
5334             if (parentWatcher) {
5335                 parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
5336             }
5337         }
5338         /**
5339          * Watch the directories in the parentDir
5340          */
5341         function watchChildDirectories(parentDir, existingChildWatches, options) {
5342             var newChildWatches;
5343             ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
5344                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
5345                 // Filter our the symbolic link directories since those arent included in recursive watch
5346                 // which is same behaviour when recursive: true is passed to fs.watch
5347                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
5348             }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
5349             return newChildWatches || ts.emptyArray;
5350             /**
5351              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
5352              */
5353             function createAndAddChildDirectoryWatcher(childName) {
5354                 var result = createDirectoryWatcher(childName, options);
5355                 addChildDirectoryWatcher(result);
5356             }
5357             /**
5358              * Add child directory watcher to the new ChildDirectoryWatcher list
5359              */
5360             function addChildDirectoryWatcher(childWatcher) {
5361                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
5362             }
5363         }
5364         function isIgnoredPath(path) {
5365             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
5366         }
5367         function isInPath(path, searchPath) {
5368             if (ts.stringContains(path, searchPath))
5369                 return true;
5370             if (host.useCaseSensitiveFileNames)
5371                 return false;
5372             return ts.stringContains(toCanonicalFilePath(path), searchPath);
5373         }
5374     }
5375     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
5376     /*@internal*/
5377     var FileSystemEntryKind;
5378     (function (FileSystemEntryKind) {
5379         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
5380         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
5381     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
5382     /*@internal*/
5383     function createFileWatcherCallback(callback) {
5384         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
5385     }
5386     ts.createFileWatcherCallback = createFileWatcherCallback;
5387     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
5388         return function (eventName) {
5389             if (eventName === "rename") {
5390                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
5391             }
5392             else {
5393                 // Change
5394                 callback(fileName, FileWatcherEventKind.Changed);
5395             }
5396         };
5397     }
5398     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
5399         return function (eventName, relativeFileName) {
5400             // In watchDirectory we only care about adding and removing files (when event name is
5401             // "rename"); changes made within files are handled by corresponding fileWatchers (when
5402             // event name is "change")
5403             if (eventName === "rename") {
5404                 // When deleting a file, the passed baseFileName is null
5405                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
5406             }
5407         };
5408     }
5409     /*@internal*/
5410     function createSystemWatchFunctions(_a) {
5411         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;
5412         var dynamicPollingWatchFile;
5413         var nonPollingWatchFile;
5414         var hostRecursiveDirectoryWatcher;
5415         return {
5416             watchFile: watchFile,
5417             watchDirectory: watchDirectory
5418         };
5419         function watchFile(fileName, callback, pollingInterval, options) {
5420             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
5421             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
5422             switch (watchFileKind) {
5423                 case ts.WatchFileKind.FixedPollingInterval:
5424                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
5425                 case ts.WatchFileKind.PriorityPollingInterval:
5426                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
5427                 case ts.WatchFileKind.DynamicPriorityPolling:
5428                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
5429                 case ts.WatchFileKind.UseFsEvents:
5430                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
5431                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
5432                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
5433                     if (!nonPollingWatchFile) {
5434                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
5435                     }
5436                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
5437                 default:
5438                     ts.Debug.assertNever(watchFileKind);
5439             }
5440         }
5441         function ensureDynamicPollingWatchFile() {
5442             return dynamicPollingWatchFile ||
5443                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
5444         }
5445         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
5446             if (options && options.watchFile !== undefined)
5447                 return options;
5448             switch (tscWatchFile) {
5449                 case "PriorityPollingInterval":
5450                     // Use polling interval based on priority when create watch using host.watchFile
5451                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
5452                 case "DynamicPriorityPolling":
5453                     // Use polling interval but change the interval depending on file changes and their default polling interval
5454                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
5455                 case "UseFsEvents":
5456                     // Use notifications from FS to watch with falling back to fs.watchFile
5457                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
5458                 case "UseFsEventsWithFallbackDynamicPolling":
5459                     // Use notifications from FS to watch with falling back to dynamic watch file
5460                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
5461                 case "UseFsEventsOnParentDirectory":
5462                     useNonPollingWatchers = true;
5463                 // fall through
5464                 default:
5465                     return useNonPollingWatchers ?
5466                         // Use notifications from FS to watch with falling back to fs.watchFile
5467                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
5468                         // Default to do not use fixed polling interval
5469                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
5470             }
5471         }
5472         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
5473             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5474             return {
5475                 watchFile: watchFile,
5476                 fallbackPolling: defaultFallbackPolling === undefined ?
5477                     fallbackPolling :
5478                     defaultFallbackPolling
5479             };
5480         }
5481         function watchDirectory(directoryName, callback, recursive, options) {
5482             if (fsSupportsRecursiveFsWatch) {
5483                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5484             }
5485             if (!hostRecursiveDirectoryWatcher) {
5486                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
5487                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5488                     directoryExists: directoryExists,
5489                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
5490                     watchDirectory: nonRecursiveWatchDirectory,
5491                     realpath: realpath,
5492                     setTimeout: setTimeout,
5493                     clearTimeout: clearTimeout
5494                 });
5495             }
5496             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
5497         }
5498         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
5499             ts.Debug.assert(!recursive);
5500             options = updateOptionsForWatchDirectory(options);
5501             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
5502             switch (watchDirectoryKind) {
5503                 case ts.WatchDirectoryKind.FixedPollingInterval:
5504                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5505                     /*options*/ undefined);
5506                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
5507                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5508                     /*options*/ undefined);
5509                 case ts.WatchDirectoryKind.UseFsEvents:
5510                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5511                 default:
5512                     ts.Debug.assertNever(watchDirectoryKind);
5513             }
5514         }
5515         function updateOptionsForWatchDirectory(options) {
5516             if (options && options.watchDirectory !== undefined)
5517                 return options;
5518             switch (tscWatchDirectory) {
5519                 case "RecursiveDirectoryUsingFsWatchFile":
5520                     // Use polling interval based on priority when create watch using host.watchFile
5521                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
5522                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
5523                     // Use polling interval but change the interval depending on file changes and their default polling interval
5524                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
5525                 default:
5526                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5527                     return {
5528                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
5529                         fallbackPolling: defaultFallbackPolling !== undefined ?
5530                             defaultFallbackPolling :
5531                             undefined
5532                     };
5533             }
5534         }
5535     }
5536     ts.createSystemWatchFunctions = createSystemWatchFunctions;
5537     /**
5538      * patch writefile to create folder before writing the file
5539      */
5540     /*@internal*/
5541     function patchWriteFileEnsuringDirectory(sys) {
5542         // patch writefile to create folder before writing the file
5543         var originalWriteFile = sys.writeFile;
5544         sys.writeFile = function (path, data, writeBom) {
5545             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); });
5546         };
5547     }
5548     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
5549     function getNodeMajorVersion() {
5550         if (typeof process === "undefined") {
5551             return undefined;
5552         }
5553         var version = process.version;
5554         if (!version) {
5555             return undefined;
5556         }
5557         var dot = version.indexOf(".");
5558         if (dot === -1) {
5559             return undefined;
5560         }
5561         return parseInt(version.substring(1, dot));
5562     }
5563     ts.getNodeMajorVersion = getNodeMajorVersion;
5564     // TODO: GH#18217 this is used as if it's certainly defined in many places.
5565     // eslint-disable-next-line prefer-const
5566     ts.sys = (function () {
5567         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
5568         // byte order mark from the specified encoding. Using any other byte order mark does
5569         // not actually work.
5570         var byteOrderMarkIndicator = "\uFEFF";
5571         function getNodeSystem() {
5572             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
5573             var _fs = require("fs");
5574             var _path = require("path");
5575             var _os = require("os");
5576             // crypto can be absent on reduced node installations
5577             var _crypto;
5578             try {
5579                 _crypto = require("crypto");
5580             }
5581             catch (_a) {
5582                 _crypto = undefined;
5583             }
5584             var activeSession;
5585             var profilePath = "./profile.cpuprofile";
5586             var Buffer = require("buffer").Buffer;
5587             var nodeVersion = getNodeMajorVersion();
5588             var isNode4OrLater = nodeVersion >= 4;
5589             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
5590             var platform = _os.platform();
5591             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
5592             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
5593             var _b = createSystemWatchFunctions({
5594                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
5595                 getModifiedTime: getModifiedTime,
5596                 setTimeout: setTimeout,
5597                 clearTimeout: clearTimeout,
5598                 fsWatch: fsWatch,
5599                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5600                 fileExists: fileExists,
5601                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5602                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5603                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
5604                 directoryExists: directoryExists,
5605                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
5606                 realpath: realpath,
5607                 tscWatchFile: process.env.TSC_WATCHFILE,
5608                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
5609                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
5610             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
5611             var nodeSystem = {
5612                 args: process.argv.slice(2),
5613                 newLine: _os.EOL,
5614                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5615                 write: function (s) {
5616                     process.stdout.write(s);
5617                 },
5618                 writeOutputIsTTY: function () {
5619                     return process.stdout.isTTY;
5620                 },
5621                 readFile: readFile,
5622                 writeFile: writeFile,
5623                 watchFile: watchFile,
5624                 watchDirectory: watchDirectory,
5625                 resolvePath: function (path) { return _path.resolve(path); },
5626                 fileExists: fileExists,
5627                 directoryExists: directoryExists,
5628                 createDirectory: function (directoryName) {
5629                     if (!nodeSystem.directoryExists(directoryName)) {
5630                         // Wrapped in a try-catch to prevent crashing if we are in a race
5631                         // with another copy of ourselves to create the same directory
5632                         try {
5633                             _fs.mkdirSync(directoryName);
5634                         }
5635                         catch (e) {
5636                             if (e.code !== "EEXIST") {
5637                                 // Failed for some other reason (access denied?); still throw
5638                                 throw e;
5639                             }
5640                         }
5641                     }
5642                 },
5643                 getExecutingFilePath: function () {
5644                     return __filename;
5645                 },
5646                 getCurrentDirectory: function () {
5647                     return process.cwd();
5648                 },
5649                 getDirectories: getDirectories,
5650                 getEnvironmentVariable: function (name) {
5651                     return process.env[name] || "";
5652                 },
5653                 readDirectory: readDirectory,
5654                 getModifiedTime: getModifiedTime,
5655                 setModifiedTime: setModifiedTime,
5656                 deleteFile: deleteFile,
5657                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
5658                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
5659                 getMemoryUsage: function () {
5660                     if (global.gc) {
5661                         global.gc();
5662                     }
5663                     return process.memoryUsage().heapUsed;
5664                 },
5665                 getFileSize: function (path) {
5666                     try {
5667                         var stat = _fs.statSync(path);
5668                         if (stat.isFile()) {
5669                             return stat.size;
5670                         }
5671                     }
5672                     catch ( /*ignore*/_a) { /*ignore*/ }
5673                     return 0;
5674                 },
5675                 exit: function (exitCode) {
5676                     disableCPUProfiler(function () { return process.exit(exitCode); });
5677                 },
5678                 enableCPUProfiler: enableCPUProfiler,
5679                 disableCPUProfiler: disableCPUProfiler,
5680                 realpath: realpath,
5681                 debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
5682                 tryEnableSourceMapsForHost: function () {
5683                     try {
5684                         require("source-map-support").install();
5685                     }
5686                     catch (_a) {
5687                         // Could not enable source maps.
5688                     }
5689                 },
5690                 setTimeout: setTimeout,
5691                 clearTimeout: clearTimeout,
5692                 clearScreen: function () {
5693                     process.stdout.write("\x1Bc");
5694                 },
5695                 setBlocking: function () {
5696                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
5697                         process.stdout._handle.setBlocking(true);
5698                     }
5699                 },
5700                 bufferFrom: bufferFrom,
5701                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
5702                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
5703                 require: function (baseDir, moduleName) {
5704                     try {
5705                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
5706                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
5707                     }
5708                     catch (error) {
5709                         return { module: undefined, modulePath: undefined, error: error };
5710                     }
5711                 }
5712             };
5713             return nodeSystem;
5714             /**
5715              * Uses the builtin inspector APIs to capture a CPU profile
5716              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
5717              */
5718             function enableCPUProfiler(path, cb) {
5719                 if (activeSession) {
5720                     cb();
5721                     return false;
5722                 }
5723                 var inspector = require("inspector");
5724                 if (!inspector || !inspector.Session) {
5725                     cb();
5726                     return false;
5727                 }
5728                 var session = new inspector.Session();
5729                 session.connect();
5730                 session.post("Profiler.enable", function () {
5731                     session.post("Profiler.start", function () {
5732                         activeSession = session;
5733                         profilePath = path;
5734                         cb();
5735                     });
5736                 });
5737                 return true;
5738             }
5739             /**
5740              * Strips non-TS paths from the profile, so users with private projects shouldn't
5741              * need to worry about leaking paths by submitting a cpu profile to us
5742              */
5743             function cleanupPaths(profile) {
5744                 var externalFileCounter = 0;
5745                 var remappedPaths = ts.createMap();
5746                 var normalizedDir = ts.normalizeSlashes(__dirname);
5747                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
5748                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
5749                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
5750                     var node = _a[_i];
5751                     if (node.callFrame.url) {
5752                         var url = ts.normalizeSlashes(node.callFrame.url);
5753                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
5754                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
5755                         }
5756                         else if (!nativePattern.test(url)) {
5757                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
5758                             externalFileCounter++;
5759                         }
5760                     }
5761                 }
5762                 return profile;
5763             }
5764             function disableCPUProfiler(cb) {
5765                 if (activeSession && activeSession !== "stopping") {
5766                     var s_1 = activeSession;
5767                     activeSession.post("Profiler.stop", function (err, _a) {
5768                         var profile = _a.profile;
5769                         if (!err) {
5770                             try {
5771                                 if (_fs.statSync(profilePath).isDirectory()) {
5772                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
5773                                 }
5774                             }
5775                             catch (_b) {
5776                                 // do nothing and ignore fallible fs operation
5777                             }
5778                             try {
5779                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
5780                             }
5781                             catch (_c) {
5782                                 // do nothing and ignore fallible fs operation
5783                             }
5784                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
5785                         }
5786                         activeSession = undefined;
5787                         s_1.disconnect();
5788                         cb();
5789                     });
5790                     activeSession = "stopping";
5791                     return true;
5792                 }
5793                 else {
5794                     cb();
5795                     return false;
5796                 }
5797             }
5798             function bufferFrom(input, encoding) {
5799                 // See https://github.com/Microsoft/TypeScript/issues/25652
5800                 return Buffer.from && Buffer.from !== Int8Array.from
5801                     ? Buffer.from(input, encoding)
5802                     : new Buffer(input, encoding);
5803             }
5804             function isFileSystemCaseSensitive() {
5805                 // win32\win64 are case insensitive platforms
5806                 if (platform === "win32" || platform === "win64") {
5807                     return false;
5808                 }
5809                 // If this file exists under a different case, we must be case-insensitve.
5810                 return !fileExists(swapCase(__filename));
5811             }
5812             /** Convert all lowercase chars to uppercase, and vice-versa */
5813             function swapCase(s) {
5814                 return s.replace(/\w/g, function (ch) {
5815                     var up = ch.toUpperCase();
5816                     return ch === up ? ch.toLowerCase() : up;
5817                 });
5818             }
5819             function fsWatchFileWorker(fileName, callback, pollingInterval) {
5820                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
5821                 var eventKind;
5822                 return {
5823                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
5824                 };
5825                 function fileChanged(curr, prev) {
5826                     // 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)
5827                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
5828                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
5829                     if (+curr.mtime === 0) {
5830                         if (isPreviouslyDeleted) {
5831                             // Already deleted file, no need to callback again
5832                             return;
5833                         }
5834                         eventKind = FileWatcherEventKind.Deleted;
5835                     }
5836                     else if (isPreviouslyDeleted) {
5837                         eventKind = FileWatcherEventKind.Created;
5838                     }
5839                     // If there is no change in modified time, ignore the event
5840                     else if (+curr.mtime === +prev.mtime) {
5841                         return;
5842                     }
5843                     else {
5844                         // File changed
5845                         eventKind = FileWatcherEventKind.Changed;
5846                     }
5847                     callback(fileName, eventKind);
5848                 }
5849             }
5850             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
5851                 var options;
5852                 var lastDirectoryPartWithDirectorySeparator;
5853                 var lastDirectoryPart;
5854                 if (isLinuxOrMacOs) {
5855                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
5856                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
5857                 }
5858                 /** Watcher for the file system entry depending on whether it is missing or present */
5859                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5860                     watchMissingFileSystemEntry() :
5861                     watchPresentFileSystemEntry();
5862                 return {
5863                     close: function () {
5864                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
5865                         watcher.close();
5866                         watcher = undefined;
5867                     }
5868                 };
5869                 /**
5870                  * Invoke the callback with rename and update the watcher if not closed
5871                  * @param createWatcher
5872                  */
5873                 function invokeCallbackAndUpdateWatcher(createWatcher) {
5874                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
5875                     // Call the callback for current directory
5876                     callback("rename", "");
5877                     // If watcher is not closed, update it
5878                     if (watcher) {
5879                         watcher.close();
5880                         watcher = createWatcher();
5881                     }
5882                 }
5883                 /**
5884                  * Watch the file or directory that is currently present
5885                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
5886                  */
5887                 function watchPresentFileSystemEntry() {
5888                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5889                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5890                     if (options === undefined) {
5891                         if (fsSupportsRecursiveFsWatch) {
5892                             options = { persistent: true, recursive: !!recursive };
5893                         }
5894                         else {
5895                             options = { persistent: true };
5896                         }
5897                     }
5898                     try {
5899                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
5900                             callbackChangingToMissingFileSystemEntry :
5901                             callback);
5902                         // Watch the missing file or directory or error
5903                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
5904                         return presentWatcher;
5905                     }
5906                     catch (e) {
5907                         // Catch the exception and use polling instead
5908                         // 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
5909                         // so instead of throwing error, use fs.watchFile
5910                         return watchPresentFileSystemEntryWithFsWatchFile();
5911                     }
5912                 }
5913                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
5914                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
5915                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
5916                     return event === "rename" &&
5917                         (!relativeName ||
5918                             relativeName === lastDirectoryPart ||
5919                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
5920                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5921                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
5922                         callback(event, relativeName);
5923                 }
5924                 /**
5925                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
5926                  * 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
5927                  */
5928                 function watchPresentFileSystemEntryWithFsWatchFile() {
5929                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
5930                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
5931                 }
5932                 /**
5933                  * Watch the file or directory that is missing
5934                  * and switch to existing file or directory when the missing filesystem entry is created
5935                  */
5936                 function watchMissingFileSystemEntry() {
5937                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
5938                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
5939                             // Call the callback for current file or directory
5940                             // For now it could be callback for the inner directory creation,
5941                             // but just return current directory, better than current no-op
5942                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
5943                         }
5944                     }, fallbackPollingInterval, fallbackOptions);
5945                 }
5946             }
5947             function readFileWorker(fileName, _encoding) {
5948                 var buffer;
5949                 try {
5950                     buffer = _fs.readFileSync(fileName);
5951                 }
5952                 catch (e) {
5953                     return undefined;
5954                 }
5955                 var len = buffer.length;
5956                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
5957                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
5958                     // flip all byte pairs and treat as little endian.
5959                     len &= ~1; // Round down to a multiple of 2
5960                     for (var i = 0; i < len; i += 2) {
5961                         var temp = buffer[i];
5962                         buffer[i] = buffer[i + 1];
5963                         buffer[i + 1] = temp;
5964                     }
5965                     return buffer.toString("utf16le", 2);
5966                 }
5967                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
5968                     // Little endian UTF-16 byte order mark detected
5969                     return buffer.toString("utf16le", 2);
5970                 }
5971                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
5972                     // UTF-8 byte order mark detected
5973                     return buffer.toString("utf8", 3);
5974                 }
5975                 // Default is UTF-8 with no byte order mark
5976                 return buffer.toString("utf8");
5977             }
5978             function readFile(fileName, _encoding) {
5979                 ts.perfLogger.logStartReadFile(fileName);
5980                 var file = readFileWorker(fileName, _encoding);
5981                 ts.perfLogger.logStopReadFile();
5982                 return file;
5983             }
5984             function writeFile(fileName, data, writeByteOrderMark) {
5985                 ts.perfLogger.logEvent("WriteFile: " + fileName);
5986                 // If a BOM is required, emit one
5987                 if (writeByteOrderMark) {
5988                     data = byteOrderMarkIndicator + data;
5989                 }
5990                 var fd;
5991                 try {
5992                     fd = _fs.openSync(fileName, "w");
5993                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
5994                 }
5995                 finally {
5996                     if (fd !== undefined) {
5997                         _fs.closeSync(fd);
5998                     }
5999                 }
6000             }
6001             function getAccessibleFileSystemEntries(path) {
6002                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
6003                 try {
6004                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
6005                     var files = [];
6006                     var directories = [];
6007                     for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
6008                         var dirent = entries_2[_i];
6009                         // withFileTypes is not supported before Node 10.10.
6010                         var entry = typeof dirent === "string" ? dirent : dirent.name;
6011                         // This is necessary because on some file system node fails to exclude
6012                         // "." and "..". See https://github.com/nodejs/node/issues/4002
6013                         if (entry === "." || entry === "..") {
6014                             continue;
6015                         }
6016                         var stat = void 0;
6017                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
6018                             var name = ts.combinePaths(path, entry);
6019                             try {
6020                                 stat = _fs.statSync(name);
6021                             }
6022                             catch (e) {
6023                                 continue;
6024                             }
6025                         }
6026                         else {
6027                             stat = dirent;
6028                         }
6029                         if (stat.isFile()) {
6030                             files.push(entry);
6031                         }
6032                         else if (stat.isDirectory()) {
6033                             directories.push(entry);
6034                         }
6035                     }
6036                     files.sort();
6037                     directories.sort();
6038                     return { files: files, directories: directories };
6039                 }
6040                 catch (e) {
6041                     return ts.emptyFileSystemEntries;
6042                 }
6043             }
6044             function readDirectory(path, extensions, excludes, includes, depth) {
6045                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
6046             }
6047             function fileSystemEntryExists(path, entryKind) {
6048                 try {
6049                     var stat = _fs.statSync(path);
6050                     switch (entryKind) {
6051                         case 0 /* File */: return stat.isFile();
6052                         case 1 /* Directory */: return stat.isDirectory();
6053                         default: return false;
6054                     }
6055                 }
6056                 catch (e) {
6057                     return false;
6058                 }
6059             }
6060             function fileExists(path) {
6061                 return fileSystemEntryExists(path, 0 /* File */);
6062             }
6063             function directoryExists(path) {
6064                 return fileSystemEntryExists(path, 1 /* Directory */);
6065             }
6066             function getDirectories(path) {
6067                 return getAccessibleFileSystemEntries(path).directories.slice();
6068             }
6069             function realpath(path) {
6070                 try {
6071                     return _fs.realpathSync(path);
6072                 }
6073                 catch (_a) {
6074                     return path;
6075                 }
6076             }
6077             function getModifiedTime(path) {
6078                 try {
6079                     return _fs.statSync(path).mtime;
6080                 }
6081                 catch (e) {
6082                     return undefined;
6083                 }
6084             }
6085             function setModifiedTime(path, time) {
6086                 try {
6087                     _fs.utimesSync(path, time, time);
6088                 }
6089                 catch (e) {
6090                     return;
6091                 }
6092             }
6093             function deleteFile(path) {
6094                 try {
6095                     return _fs.unlinkSync(path);
6096                 }
6097                 catch (e) {
6098                     return;
6099                 }
6100             }
6101             function createSHA256Hash(data) {
6102                 var hash = _crypto.createHash("sha256");
6103                 hash.update(data);
6104                 return hash.digest("hex");
6105             }
6106         }
6107         var sys;
6108         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
6109             // process and process.nextTick checks if current environment is node-like
6110             // process.browser check excludes webpack and browserify
6111             sys = getNodeSystem();
6112         }
6113         if (sys) {
6114             // patch writefile to create folder before writing the file
6115             patchWriteFileEnsuringDirectory(sys);
6116         }
6117         return sys;
6118     })();
6119     if (ts.sys && ts.sys.getEnvironmentVariable) {
6120         setCustomPollingValues(ts.sys);
6121         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
6122             ? 1 /* Normal */
6123             : 0 /* None */);
6124     }
6125     if (ts.sys && ts.sys.debugMode) {
6126         ts.Debug.isDebugging = true;
6127     }
6128 })(ts || (ts = {}));
6129 /* @internal */
6130 var ts;
6131 (function (ts) {
6132     /**
6133      * Internally, we represent paths as strings with '/' as the directory separator.
6134      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
6135      * we expect the host to correctly handle paths in our specified format.
6136      */
6137     ts.directorySeparator = "/";
6138     var altDirectorySeparator = "\\";
6139     var urlSchemeSeparator = "://";
6140     var backslashRegExp = /\\/g;
6141     //// Path Tests
6142     /**
6143      * Determines whether a charCode corresponds to `/` or `\`.
6144      */
6145     function isAnyDirectorySeparator(charCode) {
6146         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
6147     }
6148     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
6149     /**
6150      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
6151      */
6152     function isUrl(path) {
6153         return getEncodedRootLength(path) < 0;
6154     }
6155     ts.isUrl = isUrl;
6156     /**
6157      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
6158      * like `c:`, `c:\` or `c:/`).
6159      */
6160     function isRootedDiskPath(path) {
6161         return getEncodedRootLength(path) > 0;
6162     }
6163     ts.isRootedDiskPath = isRootedDiskPath;
6164     /**
6165      * Determines whether a path consists only of a path root.
6166      */
6167     function isDiskPathRoot(path) {
6168         var rootLength = getEncodedRootLength(path);
6169         return rootLength > 0 && rootLength === path.length;
6170     }
6171     ts.isDiskPathRoot = isDiskPathRoot;
6172     /**
6173      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
6174      *
6175      * ```ts
6176      * // POSIX
6177      * pathIsAbsolute("/path/to/file.ext") === true
6178      * // DOS
6179      * pathIsAbsolute("c:/path/to/file.ext") === true
6180      * // URL
6181      * pathIsAbsolute("file:///path/to/file.ext") === true
6182      * // Non-absolute
6183      * pathIsAbsolute("path/to/file.ext") === false
6184      * pathIsAbsolute("./path/to/file.ext") === false
6185      * ```
6186      */
6187     function pathIsAbsolute(path) {
6188         return getEncodedRootLength(path) !== 0;
6189     }
6190     ts.pathIsAbsolute = pathIsAbsolute;
6191     /**
6192      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
6193      */
6194     function pathIsRelative(path) {
6195         return /^\.\.?($|[\\/])/.test(path);
6196     }
6197     ts.pathIsRelative = pathIsRelative;
6198     function hasExtension(fileName) {
6199         return ts.stringContains(getBaseFileName(fileName), ".");
6200     }
6201     ts.hasExtension = hasExtension;
6202     function fileExtensionIs(path, extension) {
6203         return path.length > extension.length && ts.endsWith(path, extension);
6204     }
6205     ts.fileExtensionIs = fileExtensionIs;
6206     function fileExtensionIsOneOf(path, extensions) {
6207         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
6208             var extension = extensions_1[_i];
6209             if (fileExtensionIs(path, extension)) {
6210                 return true;
6211             }
6212         }
6213         return false;
6214     }
6215     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
6216     /**
6217      * Determines whether a path has a trailing separator (`/` or `\\`).
6218      */
6219     function hasTrailingDirectorySeparator(path) {
6220         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
6221     }
6222     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
6223     //// Path Parsing
6224     function isVolumeCharacter(charCode) {
6225         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
6226             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
6227     }
6228     function getFileUrlVolumeSeparatorEnd(url, start) {
6229         var ch0 = url.charCodeAt(start);
6230         if (ch0 === 58 /* colon */)
6231             return start + 1;
6232         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
6233             var ch2 = url.charCodeAt(start + 2);
6234             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
6235                 return start + 3;
6236         }
6237         return -1;
6238     }
6239     /**
6240      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6241      * If the root is part of a URL, the twos-complement of the root length is returned.
6242      */
6243     function getEncodedRootLength(path) {
6244         if (!path)
6245             return 0;
6246         var ch0 = path.charCodeAt(0);
6247         // POSIX or UNC
6248         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
6249             if (path.charCodeAt(1) !== ch0)
6250                 return 1; // POSIX: "/" (or non-normalized "\")
6251             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
6252             if (p1 < 0)
6253                 return path.length; // UNC: "//server" or "\\server"
6254             return p1 + 1; // UNC: "//server/" or "\\server\"
6255         }
6256         // DOS
6257         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
6258             var ch2 = path.charCodeAt(2);
6259             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
6260                 return 3; // DOS: "c:/" or "c:\"
6261             if (path.length === 2)
6262                 return 2; // DOS: "c:" (but not "c:d")
6263         }
6264         // URL
6265         var schemeEnd = path.indexOf(urlSchemeSeparator);
6266         if (schemeEnd !== -1) {
6267             var authorityStart = schemeEnd + urlSchemeSeparator.length;
6268             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
6269             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
6270                 // For local "file" URLs, include the leading DOS volume (if present).
6271                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
6272                 // special case interpreted as "the machine from which the URL is being interpreted".
6273                 var scheme = path.slice(0, schemeEnd);
6274                 var authority = path.slice(authorityStart, authorityEnd);
6275                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
6276                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
6277                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
6278                     if (volumeSeparatorEnd !== -1) {
6279                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
6280                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
6281                             return ~(volumeSeparatorEnd + 1);
6282                         }
6283                         if (volumeSeparatorEnd === path.length) {
6284                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
6285                             // but not "file:///c:d" or "file:///c%3ad"
6286                             return ~volumeSeparatorEnd;
6287                         }
6288                     }
6289                 }
6290                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
6291             }
6292             return ~path.length; // URL: "file://server", "http://server"
6293         }
6294         // relative
6295         return 0;
6296     }
6297     /**
6298      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6299      *
6300      * For example:
6301      * ```ts
6302      * getRootLength("a") === 0                   // ""
6303      * getRootLength("/") === 1                   // "/"
6304      * getRootLength("c:") === 2                  // "c:"
6305      * getRootLength("c:d") === 0                 // ""
6306      * getRootLength("c:/") === 3                 // "c:/"
6307      * getRootLength("c:\\") === 3                // "c:\\"
6308      * getRootLength("//server") === 7            // "//server"
6309      * getRootLength("//server/share") === 8      // "//server/"
6310      * getRootLength("\\\\server") === 7          // "\\\\server"
6311      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
6312      * getRootLength("file:///path") === 8        // "file:///"
6313      * getRootLength("file:///c:") === 10         // "file:///c:"
6314      * getRootLength("file:///c:d") === 8         // "file:///"
6315      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
6316      * getRootLength("file://server") === 13      // "file://server"
6317      * getRootLength("file://server/path") === 14 // "file://server/"
6318      * getRootLength("http://server") === 13      // "http://server"
6319      * getRootLength("http://server/path") === 14 // "http://server/"
6320      * ```
6321      */
6322     function getRootLength(path) {
6323         var rootLength = getEncodedRootLength(path);
6324         return rootLength < 0 ? ~rootLength : rootLength;
6325     }
6326     ts.getRootLength = getRootLength;
6327     function getDirectoryPath(path) {
6328         path = normalizeSlashes(path);
6329         // If the path provided is itself the root, then return it.
6330         var rootLength = getRootLength(path);
6331         if (rootLength === path.length)
6332             return path;
6333         // return the leading portion of the path up to the last (non-terminal) directory separator
6334         // but not including any trailing directory separator.
6335         path = removeTrailingDirectorySeparator(path);
6336         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
6337     }
6338     ts.getDirectoryPath = getDirectoryPath;
6339     function getBaseFileName(path, extensions, ignoreCase) {
6340         path = normalizeSlashes(path);
6341         // if the path provided is itself the root, then it has not file name.
6342         var rootLength = getRootLength(path);
6343         if (rootLength === path.length)
6344             return "";
6345         // return the trailing portion of the path starting after the last (non-terminal) directory
6346         // separator but not including any trailing directory separator.
6347         path = removeTrailingDirectorySeparator(path);
6348         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
6349         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
6350         return extension ? name.slice(0, name.length - extension.length) : name;
6351     }
6352     ts.getBaseFileName = getBaseFileName;
6353     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
6354         if (!ts.startsWith(extension, "."))
6355             extension = "." + extension;
6356         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
6357             var pathExtension = path.slice(path.length - extension.length);
6358             if (stringEqualityComparer(pathExtension, extension)) {
6359                 return pathExtension;
6360             }
6361         }
6362     }
6363     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
6364         if (typeof extensions === "string") {
6365             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
6366         }
6367         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
6368             var extension = extensions_2[_i];
6369             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
6370             if (result)
6371                 return result;
6372         }
6373         return "";
6374     }
6375     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
6376         // Retrieves any string from the final "." onwards from a base file name.
6377         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
6378         if (extensions) {
6379             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
6380         }
6381         var baseFileName = getBaseFileName(path);
6382         var extensionIndex = baseFileName.lastIndexOf(".");
6383         if (extensionIndex >= 0) {
6384             return baseFileName.substring(extensionIndex);
6385         }
6386         return "";
6387     }
6388     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
6389     function pathComponents(path, rootLength) {
6390         var root = path.substring(0, rootLength);
6391         var rest = path.substring(rootLength).split(ts.directorySeparator);
6392         if (rest.length && !ts.lastOrUndefined(rest))
6393             rest.pop();
6394         return __spreadArrays([root], rest);
6395     }
6396     /**
6397      * Parse a path into an array containing a root component (at index 0) and zero or more path
6398      * components (at indices > 0). The result is not normalized.
6399      * If the path is relative, the root component is `""`.
6400      * If the path is absolute, the root component includes the first path separator (`/`).
6401      *
6402      * ```ts
6403      * // POSIX
6404      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6405      * getPathComponents("/path/to/") === ["/", "path", "to"]
6406      * getPathComponents("/") === ["/"]
6407      * // DOS
6408      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6409      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6410      * getPathComponents("c:/") === ["c:/"]
6411      * getPathComponents("c:") === ["c:"]
6412      * // URL
6413      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6414      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6415      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6416      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6417      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6418      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6419      * getPathComponents("file://server/") === ["file://server/"]
6420      * getPathComponents("file://server") === ["file://server"]
6421      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6422      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6423      * getPathComponents("file:///") === ["file:///"]
6424      * getPathComponents("file://") === ["file://"]
6425      */
6426     function getPathComponents(path, currentDirectory) {
6427         if (currentDirectory === void 0) { currentDirectory = ""; }
6428         path = combinePaths(currentDirectory, path);
6429         return pathComponents(path, getRootLength(path));
6430     }
6431     ts.getPathComponents = getPathComponents;
6432     //// Path Formatting
6433     /**
6434      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6435      * segments (at indices > 0).
6436      *
6437      * ```ts
6438      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6439      * ```
6440      */
6441     function getPathFromPathComponents(pathComponents) {
6442         if (pathComponents.length === 0)
6443             return "";
6444         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6445         return root + pathComponents.slice(1).join(ts.directorySeparator);
6446     }
6447     ts.getPathFromPathComponents = getPathFromPathComponents;
6448     //// Path Normalization
6449     /**
6450      * Normalize path separators, converting `\` into `/`.
6451      */
6452     function normalizeSlashes(path) {
6453         return path.replace(backslashRegExp, ts.directorySeparator);
6454     }
6455     ts.normalizeSlashes = normalizeSlashes;
6456     /**
6457      * Reduce an array of path components to a more simplified path by navigating any
6458      * `"."` or `".."` entries in the path.
6459      */
6460     function reducePathComponents(components) {
6461         if (!ts.some(components))
6462             return [];
6463         var reduced = [components[0]];
6464         for (var i = 1; i < components.length; i++) {
6465             var component = components[i];
6466             if (!component)
6467                 continue;
6468             if (component === ".")
6469                 continue;
6470             if (component === "..") {
6471                 if (reduced.length > 1) {
6472                     if (reduced[reduced.length - 1] !== "..") {
6473                         reduced.pop();
6474                         continue;
6475                     }
6476                 }
6477                 else if (reduced[0])
6478                     continue;
6479             }
6480             reduced.push(component);
6481         }
6482         return reduced;
6483     }
6484     ts.reducePathComponents = reducePathComponents;
6485     /**
6486      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6487      *
6488      * ```ts
6489      * // Non-rooted
6490      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6491      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6492      * // POSIX
6493      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6494      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6495      * // DOS
6496      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6497      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6498      * // URL
6499      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6500      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6501      * ```
6502      */
6503     function combinePaths(path) {
6504         var paths = [];
6505         for (var _i = 1; _i < arguments.length; _i++) {
6506             paths[_i - 1] = arguments[_i];
6507         }
6508         if (path)
6509             path = normalizeSlashes(path);
6510         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6511             var relativePath = paths_1[_a];
6512             if (!relativePath)
6513                 continue;
6514             relativePath = normalizeSlashes(relativePath);
6515             if (!path || getRootLength(relativePath) !== 0) {
6516                 path = relativePath;
6517             }
6518             else {
6519                 path = ensureTrailingDirectorySeparator(path) + relativePath;
6520             }
6521         }
6522         return path;
6523     }
6524     ts.combinePaths = combinePaths;
6525     /**
6526      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6527      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6528      *
6529      * ```ts
6530      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6531      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6532      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6533      * ```
6534      */
6535     function resolvePath(path) {
6536         var paths = [];
6537         for (var _i = 1; _i < arguments.length; _i++) {
6538             paths[_i - 1] = arguments[_i];
6539         }
6540         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
6541     }
6542     ts.resolvePath = resolvePath;
6543     /**
6544      * Parse a path into an array containing a root component (at index 0) and zero or more path
6545      * components (at indices > 0). The result is normalized.
6546      * If the path is relative, the root component is `""`.
6547      * If the path is absolute, the root component includes the first path separator (`/`).
6548      *
6549      * ```ts
6550      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6551      * ```
6552      */
6553     function getNormalizedPathComponents(path, currentDirectory) {
6554         return reducePathComponents(getPathComponents(path, currentDirectory));
6555     }
6556     ts.getNormalizedPathComponents = getNormalizedPathComponents;
6557     function getNormalizedAbsolutePath(fileName, currentDirectory) {
6558         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6559     }
6560     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6561     function normalizePath(path) {
6562         path = normalizeSlashes(path);
6563         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6564         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6565     }
6566     ts.normalizePath = normalizePath;
6567     function getPathWithoutRoot(pathComponents) {
6568         if (pathComponents.length === 0)
6569             return "";
6570         return pathComponents.slice(1).join(ts.directorySeparator);
6571     }
6572     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6573         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6574     }
6575     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6576     function toPath(fileName, basePath, getCanonicalFileName) {
6577         var nonCanonicalizedPath = isRootedDiskPath(fileName)
6578             ? normalizePath(fileName)
6579             : getNormalizedAbsolutePath(fileName, basePath);
6580         return getCanonicalFileName(nonCanonicalizedPath);
6581     }
6582     ts.toPath = toPath;
6583     function normalizePathAndParts(path) {
6584         path = normalizeSlashes(path);
6585         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6586         if (parts.length) {
6587             var joinedParts = root + parts.join(ts.directorySeparator);
6588             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6589         }
6590         else {
6591             return { path: root, parts: parts };
6592         }
6593     }
6594     ts.normalizePathAndParts = normalizePathAndParts;
6595     function removeTrailingDirectorySeparator(path) {
6596         if (hasTrailingDirectorySeparator(path)) {
6597             return path.substr(0, path.length - 1);
6598         }
6599         return path;
6600     }
6601     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6602     function ensureTrailingDirectorySeparator(path) {
6603         if (!hasTrailingDirectorySeparator(path)) {
6604             return path + ts.directorySeparator;
6605         }
6606         return path;
6607     }
6608     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6609     /**
6610      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6611      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6612      *
6613      * ```ts
6614      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6615      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6616      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6617      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6618      * ```
6619      */
6620     function ensurePathIsNonModuleName(path) {
6621         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6622     }
6623     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6624     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6625         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6626         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6627     }
6628     ts.changeAnyExtension = changeAnyExtension;
6629     //// Path Comparisons
6630     // check path for these segments: '', '.'. '..'
6631     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6632     function comparePathsWorker(a, b, componentComparer) {
6633         if (a === b)
6634             return 0 /* EqualTo */;
6635         if (a === undefined)
6636             return -1 /* LessThan */;
6637         if (b === undefined)
6638             return 1 /* GreaterThan */;
6639         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6640         //       need to perform path reduction.
6641         var aRoot = a.substring(0, getRootLength(a));
6642         var bRoot = b.substring(0, getRootLength(b));
6643         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6644         if (result !== 0 /* EqualTo */) {
6645             return result;
6646         }
6647         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6648         //       the non-root portion of the path
6649         var aRest = a.substring(aRoot.length);
6650         var bRest = b.substring(bRoot.length);
6651         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6652             return componentComparer(aRest, bRest);
6653         }
6654         // The path contains a relative path segment. Normalize the paths and perform a slower component
6655         // by component comparison.
6656         var aComponents = reducePathComponents(getPathComponents(a));
6657         var bComponents = reducePathComponents(getPathComponents(b));
6658         var sharedLength = Math.min(aComponents.length, bComponents.length);
6659         for (var i = 1; i < sharedLength; i++) {
6660             var result_1 = componentComparer(aComponents[i], bComponents[i]);
6661             if (result_1 !== 0 /* EqualTo */) {
6662                 return result_1;
6663             }
6664         }
6665         return ts.compareValues(aComponents.length, bComponents.length);
6666     }
6667     /**
6668      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6669      */
6670     function comparePathsCaseSensitive(a, b) {
6671         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6672     }
6673     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6674     /**
6675      * Performs a case-insensitive comparison of two paths.
6676      */
6677     function comparePathsCaseInsensitive(a, b) {
6678         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6679     }
6680     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6681     function comparePaths(a, b, currentDirectory, ignoreCase) {
6682         if (typeof currentDirectory === "string") {
6683             a = combinePaths(currentDirectory, a);
6684             b = combinePaths(currentDirectory, b);
6685         }
6686         else if (typeof currentDirectory === "boolean") {
6687             ignoreCase = currentDirectory;
6688         }
6689         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6690     }
6691     ts.comparePaths = comparePaths;
6692     function containsPath(parent, child, currentDirectory, ignoreCase) {
6693         if (typeof currentDirectory === "string") {
6694             parent = combinePaths(currentDirectory, parent);
6695             child = combinePaths(currentDirectory, child);
6696         }
6697         else if (typeof currentDirectory === "boolean") {
6698             ignoreCase = currentDirectory;
6699         }
6700         if (parent === undefined || child === undefined)
6701             return false;
6702         if (parent === child)
6703             return true;
6704         var parentComponents = reducePathComponents(getPathComponents(parent));
6705         var childComponents = reducePathComponents(getPathComponents(child));
6706         if (childComponents.length < parentComponents.length) {
6707             return false;
6708         }
6709         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6710         for (var i = 0; i < parentComponents.length; i++) {
6711             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6712             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6713                 return false;
6714             }
6715         }
6716         return true;
6717     }
6718     ts.containsPath = containsPath;
6719     /**
6720      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6721      * Comparison is case-sensitive between the canonical paths.
6722      *
6723      * @deprecated Use `containsPath` if possible.
6724      */
6725     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6726         var canonicalFileName = getCanonicalFileName(fileName);
6727         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6728         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6729     }
6730     ts.startsWithDirectory = startsWithDirectory;
6731     //// Relative Paths
6732     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6733         var fromComponents = reducePathComponents(getPathComponents(from));
6734         var toComponents = reducePathComponents(getPathComponents(to));
6735         var start;
6736         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6737             var fromComponent = getCanonicalFileName(fromComponents[start]);
6738             var toComponent = getCanonicalFileName(toComponents[start]);
6739             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6740             if (!comparer(fromComponent, toComponent))
6741                 break;
6742         }
6743         if (start === 0) {
6744             return toComponents;
6745         }
6746         var components = toComponents.slice(start);
6747         var relative = [];
6748         for (; start < fromComponents.length; start++) {
6749             relative.push("..");
6750         }
6751         return __spreadArrays([""], relative, components);
6752     }
6753     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6754     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6755         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6756         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6757         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6758         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6759         return getPathFromPathComponents(pathComponents);
6760     }
6761     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6762     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6763         return !isRootedDiskPath(absoluteOrRelativePath)
6764             ? absoluteOrRelativePath
6765             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6766     }
6767     ts.convertToRelativePath = convertToRelativePath;
6768     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6769         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6770     }
6771     ts.getRelativePathFromFile = getRelativePathFromFile;
6772     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6773         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6774         var firstComponent = pathComponents[0];
6775         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6776             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6777             pathComponents[0] = prefix + firstComponent;
6778         }
6779         return getPathFromPathComponents(pathComponents);
6780     }
6781     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6782     function forEachAncestorDirectory(directory, callback) {
6783         while (true) {
6784             var result = callback(directory);
6785             if (result !== undefined) {
6786                 return result;
6787             }
6788             var parentPath = getDirectoryPath(directory);
6789             if (parentPath === directory) {
6790                 return undefined;
6791             }
6792             directory = parentPath;
6793         }
6794     }
6795     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6796     function isNodeModulesDirectory(dirPath) {
6797         return ts.endsWith(dirPath, "/node_modules");
6798     }
6799     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6800 })(ts || (ts = {}));
6801 // <auto-generated />
6802 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
6803 /* @internal */
6804 var ts;
6805 (function (ts) {
6806     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
6807         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
6808     }
6809     ts.Diagnostics = {
6810         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
6811         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
6812         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
6813         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."),
6814         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."),
6815         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
6816         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
6817         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."),
6818         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
6819         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."),
6820         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."),
6821         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."),
6822         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."),
6823         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."),
6824         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."),
6825         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."),
6826         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."),
6827         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."),
6828         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."),
6829         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'."),
6830         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."),
6831         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."),
6832         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
6833         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
6834         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
6835         _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."),
6836         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."),
6837         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."),
6838         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."),
6839         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."),
6840         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."),
6841         _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."),
6842         _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."),
6843         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
6844         _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."),
6845         _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."),
6846         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."),
6847         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."),
6848         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
6849         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."),
6850         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."),
6851         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."),
6852         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."),
6853         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."),
6854         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
6855         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."),
6856         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."),
6857         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."),
6858         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."),
6859         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."),
6860         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."),
6861         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
6862         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."),
6863         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."),
6864         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."),
6865         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."),
6866         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."),
6867         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."),
6868         _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."),
6869         _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."),
6870         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."),
6871         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
6872         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}'."),
6873         _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."),
6874         _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."),
6875         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."),
6876         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."),
6877         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."),
6878         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
6879         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."),
6880         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."),
6881         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
6882         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
6883         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
6884         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."),
6885         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."),
6886         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."),
6887         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."),
6888         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."),
6889         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."),
6890         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
6891         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."),
6892         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
6893         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
6894         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."),
6895         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
6896         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."),
6897         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."),
6898         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."),
6899         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."),
6900         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."),
6901         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
6902         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."),
6903         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
6904         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
6905         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
6906         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
6907         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
6908         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
6909         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
6910         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
6911         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
6912         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
6913         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
6914         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
6915         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
6916         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
6917         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
6918         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
6919         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
6920         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
6921         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
6922         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
6923         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
6924         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."),
6925         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'."),
6926         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."),
6927         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
6928         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."),
6929         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."),
6930         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
6931         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
6932         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."),
6933         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."),
6934         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."),
6935         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."),
6936         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."),
6937         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."),
6938         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."),
6939         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."),
6940         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."),
6941         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
6942         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
6943         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."),
6944         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
6945         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
6946         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
6947         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
6948         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
6949         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
6950         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
6951         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."),
6952         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."),
6953         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
6954         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
6955         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."),
6956         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."),
6957         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."),
6958         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."),
6959         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."),
6960         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
6961         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
6962         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
6963         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."),
6964         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."),
6965         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."),
6966         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."),
6967         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."),
6968         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
6969         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
6970         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."),
6971         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."),
6972         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'."),
6973         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
6974         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."),
6975         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."),
6976         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."),
6977         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."),
6978         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."),
6979         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."),
6980         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."),
6981         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."),
6982         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."),
6983         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'."),
6984         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."),
6985         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."),
6986         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."),
6987         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."),
6988         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
6989         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."),
6990         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
6991         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}'."),
6992         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}'."),
6993         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."),
6994         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."),
6995         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."),
6996         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."),
6997         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."),
6998         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."),
6999         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."),
7000         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."),
7001         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'."),
7002         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'."),
7003         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."),
7004         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."),
7005         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."),
7006         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."),
7007         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."),
7008         _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."),
7009         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."),
7010         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."),
7011         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."),
7012         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."),
7013         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."),
7014         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."),
7015         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'."),
7016         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."),
7017         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."),
7018         _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."),
7019         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."),
7020         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."),
7021         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."),
7022         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."),
7023         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."),
7024         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"),
7025         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
7026         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."),
7027         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."),
7028         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."),
7029         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."),
7030         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."),
7031         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."),
7032         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."),
7033         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."),
7034         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."),
7035         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."),
7036         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."),
7037         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."),
7038         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."),
7039         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."),
7040         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'."),
7041         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."),
7042         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."),
7043         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
7044         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
7045         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."),
7046         _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}()'?"),
7047         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'."),
7048         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'."),
7049         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'."),
7050         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."),
7051         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."),
7052         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."),
7053         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."),
7054         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."),
7055         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."),
7056         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."),
7057         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}')'?"),
7058         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
7059         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'."),
7060         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
7061         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"),
7062         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."),
7063         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."),
7064         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
7065         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
7066         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."),
7067         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."),
7068         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."),
7069         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."),
7070         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."),
7071         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."),
7072         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'?"),
7073         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 '}'."),
7074         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."),
7075         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."),
7076         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?"),
7077         _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'."),
7078         _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'."),
7079         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."),
7080         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
7081         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"),
7082         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
7083         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
7084         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"),
7085         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
7086         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'."),
7087         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'."),
7088         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
7089         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"),
7090         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."),
7091         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
7092         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
7093         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."),
7094         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'."),
7095         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'."),
7096         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;`?"),
7097         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;`?"),
7098         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'."),
7099         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."),
7100         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."),
7101         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."),
7102         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),
7103         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),
7104         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),
7105         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),
7106         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
7107         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."),
7108         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."),
7109         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
7110         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
7111         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}'."),
7112         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
7113         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."),
7114         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."),
7115         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."),
7116         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."),
7117         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."),
7118         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."),
7119         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."),
7120         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)."),
7121         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
7122         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."),
7123         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)."),
7124         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
7125         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."),
7126         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}'."),
7127         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}'."),
7128         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}'."),
7129         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
7130         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}'."),
7131         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}'."),
7132         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
7133         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}'."),
7134         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."),
7135         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}'."),
7136         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
7137         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."),
7138         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."),
7139         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."),
7140         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."),
7141         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."),
7142         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."),
7143         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."),
7144         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."),
7145         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}'."),
7146         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."),
7147         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}'."),
7148         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'."),
7149         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}'."),
7150         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}'."),
7151         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}'."),
7152         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."),
7153         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."),
7154         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'?"),
7155         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7156         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."),
7157         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7158         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."),
7159         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}'."),
7160         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."),
7161         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."),
7162         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."),
7163         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."),
7164         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."),
7165         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."),
7166         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'."),
7167         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."),
7168         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."),
7169         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."),
7170         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."),
7171         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}'."),
7172         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'."),
7173         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."),
7174         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7175         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."),
7176         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."),
7177         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."),
7178         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7179         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."),
7180         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7181         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7182         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."),
7183         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."),
7184         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."),
7185         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."),
7186         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."),
7187         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."),
7188         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."),
7189         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."),
7190         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."),
7191         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."),
7192         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."),
7193         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7194         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7195         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7196         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7197         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."),
7198         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7199         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7200         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."),
7201         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."),
7202         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."),
7203         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}'."),
7204         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."),
7205         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."),
7206         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."),
7207         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."),
7208         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."),
7209         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}'."),
7210         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."),
7211         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'."),
7212         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."),
7213         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}'."),
7214         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7215         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."),
7216         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'."),
7217         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}'."),
7218         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}'."),
7219         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}'."),
7220         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7221         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}'."),
7222         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}'."),
7223         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}'."),
7224         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}'."),
7225         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7226         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."),
7227         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."),
7228         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."),
7229         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."),
7230         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7231         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."),
7232         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7233         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7234         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."),
7235         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."),
7236         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."),
7237         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."),
7238         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."),
7239         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."),
7240         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7241         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."),
7242         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}'."),
7243         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."),
7244         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}'."),
7245         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}'."),
7246         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}'."),
7247         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."),
7248         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}'."),
7249         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."),
7250         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."),
7251         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7252         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7253         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7254         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."),
7255         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."),
7256         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."),
7257         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}'."),
7258         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7259         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7260         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."),
7261         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."),
7262         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}'."),
7263         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."),
7264         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."),
7265         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."),
7266         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'."),
7267         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."),
7268         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."),
7269         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."),
7270         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7271         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'."),
7272         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."),
7273         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'."),
7274         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."),
7275         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."),
7276         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."),
7277         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."),
7278         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."),
7279         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."),
7280         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'."),
7281         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}'."),
7282         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."),
7283         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}'."),
7284         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."),
7285         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}'."),
7286         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."),
7287         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."),
7288         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."),
7289         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."),
7290         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."),
7291         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."),
7292         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}'."),
7293         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."),
7294         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."),
7295         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."),
7296         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."),
7297         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 *'."),
7298         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."),
7299         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."),
7300         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."),
7301         _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."),
7302         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7303         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."),
7304         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."),
7305         _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."),
7306         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."),
7307         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."),
7308         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."),
7309         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."),
7310         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."),
7311         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."),
7312         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."),
7313         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."),
7314         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}'."),
7315         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."),
7316         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."),
7317         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."),
7318         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."),
7319         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."),
7320         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."),
7321         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."),
7322         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."),
7323         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."),
7324         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."),
7325         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."),
7326         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."),
7327         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."),
7328         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."),
7329         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."),
7330         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
7331         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
7332         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
7333         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."),
7334         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."),
7335         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}'."),
7336         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}'."),
7337         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."),
7338         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."),
7339         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."),
7340         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."),
7341         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."),
7342         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."),
7343         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."),
7344         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[]'."),
7345         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."),
7346         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."),
7347         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."),
7348         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}'?"),
7349         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}'?"),
7350         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."),
7351         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
7352         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}."),
7353         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."),
7354         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."),
7355         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}."),
7356         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}'."),
7357         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?"),
7358         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}'?"),
7359         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."),
7360         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."),
7361         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."),
7362         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."),
7363         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."),
7364         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."),
7365         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."),
7366         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
7367         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
7368         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."),
7369         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."),
7370         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."),
7371         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}'"),
7372         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
7373         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
7374         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`."),
7375         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`."),
7376         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`."),
7377         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."),
7378         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'."),
7379         _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."),
7380         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
7381         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
7382         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."),
7383         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."),
7384         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."),
7385         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."),
7386         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."),
7387         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."),
7388         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."),
7389         _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."),
7390         _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."),
7391         _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."),
7392         _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."),
7393         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."),
7394         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."),
7395         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."),
7396         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}'."),
7397         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."),
7398         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."),
7399         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."),
7400         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."),
7401         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."),
7402         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."),
7403         _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."),
7404         _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."),
7405         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."),
7406         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?"),
7407         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?"),
7408         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}'."),
7409         _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."),
7410         _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."),
7411         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."),
7412         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."),
7413         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."),
7414         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}'."),
7415         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."),
7416         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."),
7417         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."),
7418         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}'."),
7419         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."),
7420         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."),
7421         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."),
7422         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}'?"),
7423         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}'?"),
7424         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."),
7425         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."),
7426         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."),
7427         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."),
7428         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."),
7429         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."),
7430         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."),
7431         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."),
7432         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."),
7433         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."),
7434         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."),
7435         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."),
7436         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."),
7437         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."),
7438         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}'."),
7439         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'."),
7440         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."),
7441         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."),
7442         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."),
7443         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."),
7444         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}'."),
7445         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."),
7446         _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."),
7447         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."),
7448         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}'."),
7449         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'?"),
7450         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."),
7451         _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."),
7452         _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."),
7453         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}'."),
7454         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),
7455         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?"),
7456         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."),
7457         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."),
7458         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}'."),
7459         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."),
7460         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."),
7461         _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."),
7462         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."),
7463         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."),
7464         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."),
7465         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."),
7466         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."),
7467         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."),
7468         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."),
7469         _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."),
7470         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."),
7471         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."),
7472         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}\"]'?"),
7473         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."),
7474         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."),
7475         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."),
7476         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}'."),
7477         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
7478         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."),
7479         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?"),
7480         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'."),
7481         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'."),
7482         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'."),
7483         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}'?"),
7484         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}."),
7485         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
7486         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}'?"),
7487         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
7488         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."),
7489         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."),
7490         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(...)'."),
7491         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"),
7492         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
7493         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
7494         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}'?"),
7495         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}'."),
7496         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."),
7497         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."),
7498         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}"),
7499         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."),
7500         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}'."),
7501         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."),
7502         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."),
7503         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."),
7504         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."),
7505         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."),
7506         _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}'."),
7507         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."),
7508         _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}'?"),
7509         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
7510         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."),
7511         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
7512         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
7513         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
7514         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."),
7515         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."),
7516         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
7517         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."),
7518         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."),
7519         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."),
7520         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
7521         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."),
7522         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}'."),
7523         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}'."),
7524         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}'."),
7525         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}'."),
7526         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."),
7527         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."),
7528         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
7529         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."),
7530         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
7531         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."),
7532         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
7533         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?"),
7534         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."),
7535         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."),
7536         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."),
7537         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."),
7538         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."),
7539         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."),
7540         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."),
7541         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
7542         _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."),
7543         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."),
7544         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
7545         _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."),
7546         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."),
7547         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."),
7548         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."),
7549         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}'."),
7550         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}'."),
7551         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}'."),
7552         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}'."),
7553         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}'."),
7554         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}'."),
7555         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}'."),
7556         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}'."),
7557         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}'."),
7558         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}'."),
7559         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}'."),
7560         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}'."),
7561         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."),
7562         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}'."),
7563         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}'."),
7564         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."),
7565         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}'."),
7566         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}'."),
7567         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."),
7568         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}'."),
7569         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}'."),
7570         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}'."),
7571         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}'."),
7572         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}'."),
7573         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}'."),
7574         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}'."),
7575         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}'."),
7576         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."),
7577         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}'."),
7578         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}'."),
7579         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."),
7580         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}'."),
7581         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}'."),
7582         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}'."),
7583         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}'."),
7584         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}'."),
7585         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}'."),
7586         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}'."),
7587         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}'."),
7588         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."),
7589         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}'."),
7590         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}'."),
7591         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."),
7592         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}'."),
7593         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}'."),
7594         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}'."),
7595         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}'."),
7596         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."),
7597         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}'."),
7598         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}'."),
7599         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."),
7600         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}'."),
7601         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}'."),
7602         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}'."),
7603         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}'."),
7604         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}'."),
7605         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}'."),
7606         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."),
7607         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}'."),
7608         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}'."),
7609         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."),
7610         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}'."),
7611         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}'."),
7612         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}'."),
7613         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}'."),
7614         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."),
7615         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}'."),
7616         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}'."),
7617         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}'."),
7618         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}'."),
7619         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}'."),
7620         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."),
7621         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}'."),
7622         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}'."),
7623         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."),
7624         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."),
7625         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}'."),
7626         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}'."),
7627         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."),
7628         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}'."),
7629         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}'."),
7630         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}'."),
7631         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}'."),
7632         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}'."),
7633         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}'."),
7634         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."),
7635         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}'."),
7636         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}'."),
7637         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."),
7638         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."),
7639         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
7640         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."),
7641         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."),
7642         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}'."),
7643         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
7644         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}."),
7645         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
7646         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}."),
7647         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}'?"),
7648         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}."),
7649         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."),
7650         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."),
7651         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'."),
7652         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."),
7653         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}'."),
7654         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}'."),
7655         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}'."),
7656         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."),
7657         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."),
7658         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}'."),
7659         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}'."),
7660         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."),
7661         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."),
7662         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."),
7663         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."),
7664         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."),
7665         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}'."),
7666         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}'."),
7667         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."),
7668         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."),
7669         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."),
7670         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}'."),
7671         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."),
7672         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'."),
7673         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
7674         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}."),
7675         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."),
7676         _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}'."),
7677         _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."),
7678         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}'?"),
7679         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
7680         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}'?"),
7681         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}."),
7682         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}."),
7683         _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}'."),
7684         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
7685         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."),
7686         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."),
7687         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."),
7688         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7689         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."),
7690         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."),
7691         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7692         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7693         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."),
7694         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."),
7695         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7696         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7697         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."),
7698         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7699         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."),
7700         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7701         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'."),
7702         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'."),
7703         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7704         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7705         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'."),
7706         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7707         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7708         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7709         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7710         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7711         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7712         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."),
7713         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7714         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7715         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7716         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7717         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7718         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7719         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7720         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7721         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7722         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7723         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7724         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}'."),
7725         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}."),
7726         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}'."),
7727         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7728         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7729         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7730         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."),
7731         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7732         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}."),
7733         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."),
7734         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."),
7735         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."),
7736         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."),
7737         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)."),
7738         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7739         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."),
7740         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7741         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."),
7742         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."),
7743         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)."),
7744         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."),
7745         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7746         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."),
7747         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)."),
7748         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."),
7749         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."),
7750         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."),
7751         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."),
7752         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."),
7753         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."),
7754         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'."),
7755         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."),
7756         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}."),
7757         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."),
7758         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"),
7759         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."),
7760         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7761         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}'."),
7762         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}'."),
7763         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}'. ========"),
7764         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7765         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}'."),
7766         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7767         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}'."),
7768         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}'."),
7769         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}'."),
7770         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7771         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."),
7772         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}'."),
7773         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7774         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."),
7775         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}'."),
7776         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7777         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."),
7778         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}'."),
7779         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}'."),
7780         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}'."),
7781         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}'."),
7782         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}'."),
7783         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}'."),
7784         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7785         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7786         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."),
7787         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7788         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'?"),
7789         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."),
7790         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}'. ========"),
7791         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7792         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7793         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}. ========"),
7794         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. ========"),
7795         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7796         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."),
7797         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. ========"),
7798         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."),
7799         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}'."),
7800         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."),
7801         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}'. ========"),
7802         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. ========"),
7803         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}'."),
7804         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'."),
7805         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."),
7806         _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),
7807         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7808         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7809         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."),
7810         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}'."),
7811         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),
7812         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7813         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}'."),
7814         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."),
7815         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."),
7816         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}'."),
7817         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."),
7818         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'."),
7819         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}'."),
7820         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."),
7821         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7822         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7823         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."),
7824         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."),
7825         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')."),
7826         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."),
7827         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."),
7828         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')"),
7829         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."),
7830         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)."),
7831         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."),
7832         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."),
7833         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."),
7834         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7835         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."),
7836         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."),
7837         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7838         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7839         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'."),
7840         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."),
7841         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7842         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"),
7843         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7844         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7845         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7846         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7847         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7848         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7849         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7850         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7851         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'."),
7852         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7853         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7854         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7855         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."),
7856         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."),
7857         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."),
7858         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
7859         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."),
7860         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
7861         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."),
7862         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."),
7863         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),
7864         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."),
7865         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."),
7866         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)."),
7867         _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),
7868         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
7869         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
7870         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
7871         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}"),
7872         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
7873         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}"),
7874         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
7875         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
7876         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
7877         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."),
7878         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}'."),
7879         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}'."),
7880         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."),
7881         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."),
7882         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."),
7883         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?"),
7884         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?"),
7885         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."),
7886         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}'."),
7887         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
7888         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
7889         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}'. ========"),
7890         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}. ========"),
7891         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."),
7892         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."),
7893         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."),
7894         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
7895         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
7896         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'."),
7897         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'."),
7898         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'."),
7899         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."),
7900         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}'."),
7901         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."),
7902         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}."),
7903         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."),
7904         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."),
7905         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
7906         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
7907         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."),
7908         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}'."),
7909         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."),
7910         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."),
7911         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"),
7912         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"),
7913         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}'"),
7914         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}'"),
7915         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"),
7916         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"),
7917         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"),
7918         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
7919         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}"),
7920         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}'"),
7921         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
7922         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
7923         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"),
7924         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
7925         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"),
7926         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"),
7927         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"),
7928         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
7929         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
7930         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')"),
7931         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"),
7932         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."),
7933         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."),
7934         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}'..."),
7935         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"),
7936         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
7937         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}'"),
7938         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}'"),
7939         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}'"),
7940         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}'"),
7941         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
7942         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."),
7943         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"),
7944         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}'"),
7945         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"),
7946         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"),
7947         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."),
7948         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}'"),
7949         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."),
7950         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."),
7951         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."),
7952         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?"),
7953         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."),
7954         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."),
7955         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."),
7956         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."),
7957         _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."),
7958         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."),
7959         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."),
7960         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."),
7961         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'."),
7962         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."),
7963         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."),
7964         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."),
7965         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."),
7966         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."),
7967         _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."),
7968         _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."),
7969         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."),
7970         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."),
7971         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."),
7972         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
7973         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
7974         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
7975         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."),
7976         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."),
7977         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."),
7978         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."),
7979         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."),
7980         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}';`"),
7981         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}'."),
7982         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'."),
7983         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."),
7984         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."),
7985         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}`"),
7986         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'."),
7987         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."),
7988         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."),
7989         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."),
7990         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."),
7991         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."),
7992         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."),
7993         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."),
7994         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."),
7995         _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."),
7996         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}'?"),
7997         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}'?"),
7998         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}'."),
7999         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}'."),
8000         _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."),
8001         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
8002         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."),
8003         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."),
8004         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."),
8005         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."),
8006         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."),
8007         _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."),
8008         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."),
8009         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."),
8010         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."),
8011         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."),
8012         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."),
8013         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."),
8014         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."),
8015         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}'."),
8016         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}'."),
8017         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
8018         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."),
8019         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."),
8020         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."),
8021         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."),
8022         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."),
8023         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."),
8024         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."),
8025         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."),
8026         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."),
8027         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."),
8028         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."),
8029         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."),
8030         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}'."),
8031         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."),
8032         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
8033         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
8034         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."),
8035         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."),
8036         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'."),
8037         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."),
8038         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}'."),
8039         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
8040         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."),
8041         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'."),
8042         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."),
8043         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."),
8044         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."),
8045         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."),
8046         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
8047         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."),
8048         _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}'?"),
8049         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."),
8050         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."),
8051         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."),
8052         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"),
8053         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"),
8054         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}'?"),
8055         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}"),
8056         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."),
8057         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."),
8058         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}'."),
8059         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."),
8060         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."),
8061         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."),
8062         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."),
8063         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."),
8064         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."),
8065         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."),
8066         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."),
8067         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
8068         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"),
8069         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
8070         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
8071         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
8072         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
8073         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
8074         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
8075         Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
8076         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
8077         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
8078         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
8079         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
8080         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
8081         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}\""),
8082         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
8083         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
8084         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
8085         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
8086         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
8087         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
8088         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
8089         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
8090         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
8091         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
8092         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}'"),
8093         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
8094         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
8095         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
8096         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
8097         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
8098         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
8099         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}\""),
8100         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
8101         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
8102         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
8103         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
8104         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
8105         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
8106         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
8107         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
8108         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
8109         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
8110         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
8111         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
8112         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
8113         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
8114         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
8115         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
8116         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
8117         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
8118         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
8119         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
8120         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
8121         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}'"),
8122         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
8123         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
8124         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
8125         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"),
8126         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
8127         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
8128         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"),
8129         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"),
8130         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"),
8131         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)"),
8132         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
8133         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
8134         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
8135         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
8136         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"),
8137         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"),
8138         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
8139         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
8140         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
8141         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
8142         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"),
8143         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
8144         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
8145         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
8146         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
8147         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
8148         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
8149         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
8150         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
8151         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
8152         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
8153         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
8154         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
8155         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
8156         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
8157         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
8158         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"),
8159         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8160         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8161         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8162         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8163         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8164         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8165         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8166         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8167         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8168         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8169         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"),
8170         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"),
8171         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8172         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"),
8173         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"),
8174         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"),
8175         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8176         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8177         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8178         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8179         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8180         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"),
8181         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8182         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8183         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8184         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8185         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8186         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8187         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8188         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"),
8189         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8190         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8191         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8192         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8193         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8194         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8195         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'"),
8196         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8197         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"),
8198         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}'"),
8199         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}'"),
8200         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"),
8201         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"),
8202         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8203         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8204         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8205         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"),
8206         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"),
8207         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8208         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"),
8209         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"),
8210         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"),
8211         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8212         Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
8213         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"),
8214         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8215         Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
8216         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8217         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."),
8218         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'."),
8219         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?"),
8220         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"),
8221         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."),
8222         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."),
8223         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8224         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."),
8225         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."),
8226         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}'."),
8227         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."),
8228         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"),
8229         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"),
8230         _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"),
8231         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."),
8232         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."),
8233         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."),
8234         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."),
8235         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."),
8236         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."),
8237         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."),
8238         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."),
8239         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."),
8240         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."),
8241         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."),
8242     };
8243 })(ts || (ts = {}));
8244 var ts;
8245 (function (ts) {
8246     var _a;
8247     /* @internal */
8248     function tokenIsIdentifierOrKeyword(token) {
8249         return token >= 75 /* Identifier */;
8250     }
8251     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8252     /* @internal */
8253     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8254         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8255     }
8256     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8257     var textToKeywordObj = (_a = {
8258             abstract: 122 /* AbstractKeyword */,
8259             any: 125 /* AnyKeyword */,
8260             as: 123 /* AsKeyword */,
8261             asserts: 124 /* AssertsKeyword */,
8262             bigint: 151 /* BigIntKeyword */,
8263             boolean: 128 /* BooleanKeyword */,
8264             break: 77 /* BreakKeyword */,
8265             case: 78 /* CaseKeyword */,
8266             catch: 79 /* CatchKeyword */,
8267             class: 80 /* ClassKeyword */,
8268             continue: 82 /* ContinueKeyword */,
8269             const: 81 /* ConstKeyword */
8270         },
8271         _a["" + "constructor"] = 129 /* ConstructorKeyword */,
8272         _a.debugger = 83 /* DebuggerKeyword */,
8273         _a.declare = 130 /* DeclareKeyword */,
8274         _a.default = 84 /* DefaultKeyword */,
8275         _a.delete = 85 /* DeleteKeyword */,
8276         _a.do = 86 /* DoKeyword */,
8277         _a.else = 87 /* ElseKeyword */,
8278         _a.enum = 88 /* EnumKeyword */,
8279         _a.export = 89 /* ExportKeyword */,
8280         _a.extends = 90 /* ExtendsKeyword */,
8281         _a.false = 91 /* FalseKeyword */,
8282         _a.finally = 92 /* FinallyKeyword */,
8283         _a.for = 93 /* ForKeyword */,
8284         _a.from = 149 /* FromKeyword */,
8285         _a.function = 94 /* FunctionKeyword */,
8286         _a.get = 131 /* GetKeyword */,
8287         _a.if = 95 /* IfKeyword */,
8288         _a.implements = 113 /* ImplementsKeyword */,
8289         _a.import = 96 /* ImportKeyword */,
8290         _a.in = 97 /* InKeyword */,
8291         _a.infer = 132 /* InferKeyword */,
8292         _a.instanceof = 98 /* InstanceOfKeyword */,
8293         _a.interface = 114 /* InterfaceKeyword */,
8294         _a.is = 133 /* IsKeyword */,
8295         _a.keyof = 134 /* KeyOfKeyword */,
8296         _a.let = 115 /* LetKeyword */,
8297         _a.module = 135 /* ModuleKeyword */,
8298         _a.namespace = 136 /* NamespaceKeyword */,
8299         _a.never = 137 /* NeverKeyword */,
8300         _a.new = 99 /* NewKeyword */,
8301         _a.null = 100 /* NullKeyword */,
8302         _a.number = 140 /* NumberKeyword */,
8303         _a.object = 141 /* ObjectKeyword */,
8304         _a.package = 116 /* PackageKeyword */,
8305         _a.private = 117 /* PrivateKeyword */,
8306         _a.protected = 118 /* ProtectedKeyword */,
8307         _a.public = 119 /* PublicKeyword */,
8308         _a.readonly = 138 /* ReadonlyKeyword */,
8309         _a.require = 139 /* RequireKeyword */,
8310         _a.global = 150 /* GlobalKeyword */,
8311         _a.return = 101 /* ReturnKeyword */,
8312         _a.set = 142 /* SetKeyword */,
8313         _a.static = 120 /* StaticKeyword */,
8314         _a.string = 143 /* StringKeyword */,
8315         _a.super = 102 /* SuperKeyword */,
8316         _a.switch = 103 /* SwitchKeyword */,
8317         _a.symbol = 144 /* SymbolKeyword */,
8318         _a.this = 104 /* ThisKeyword */,
8319         _a.throw = 105 /* ThrowKeyword */,
8320         _a.true = 106 /* TrueKeyword */,
8321         _a.try = 107 /* TryKeyword */,
8322         _a.type = 145 /* TypeKeyword */,
8323         _a.typeof = 108 /* TypeOfKeyword */,
8324         _a.undefined = 146 /* UndefinedKeyword */,
8325         _a.unique = 147 /* UniqueKeyword */,
8326         _a.unknown = 148 /* UnknownKeyword */,
8327         _a.var = 109 /* VarKeyword */,
8328         _a.void = 110 /* VoidKeyword */,
8329         _a.while = 111 /* WhileKeyword */,
8330         _a.with = 112 /* WithKeyword */,
8331         _a.yield = 121 /* YieldKeyword */,
8332         _a.async = 126 /* AsyncKeyword */,
8333         _a.await = 127 /* AwaitKeyword */,
8334         _a.of = 152 /* OfKeyword */,
8335         _a);
8336     var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
8337     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 */ }));
8338     /*
8339         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8340         IdentifierStart ::
8341             Can contain Unicode 3.0.0 categories:
8342             Uppercase letter (Lu),
8343             Lowercase letter (Ll),
8344             Titlecase letter (Lt),
8345             Modifier letter (Lm),
8346             Other letter (Lo), or
8347             Letter number (Nl).
8348         IdentifierPart :: =
8349             Can contain IdentifierStart + Unicode 3.0.0 categories:
8350             Non-spacing mark (Mn),
8351             Combining spacing mark (Mc),
8352             Decimal number (Nd), or
8353             Connector punctuation (Pc).
8354
8355         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8356         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8357     */
8358     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,];
8359     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,];
8360     /*
8361         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8362         IdentifierStart ::
8363             Can contain Unicode 6.2 categories:
8364             Uppercase letter (Lu),
8365             Lowercase letter (Ll),
8366             Titlecase letter (Lt),
8367             Modifier letter (Lm),
8368             Other letter (Lo), or
8369             Letter number (Nl).
8370         IdentifierPart ::
8371             Can contain IdentifierStart + Unicode 6.2 categories:
8372             Non-spacing mark (Mn),
8373             Combining spacing mark (Mc),
8374             Decimal number (Nd),
8375             Connector punctuation (Pc),
8376             <ZWNJ>, or
8377             <ZWJ>.
8378
8379         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8380         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8381     */
8382     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,];
8383     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,];
8384     /**
8385      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8386      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8387      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8388      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8389      */
8390     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];
8391     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];
8392     /**
8393      * Test for whether a single line comment's text contains a directive.
8394      */
8395     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8396     /**
8397      * Test for whether a multi-line comment's last line contains a directive.
8398      */
8399     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8400     function lookupInUnicodeMap(code, map) {
8401         // Bail out quickly if it couldn't possibly be in the map.
8402         if (code < map[0]) {
8403             return false;
8404         }
8405         // Perform binary search in one of the Unicode range maps
8406         var lo = 0;
8407         var hi = map.length;
8408         var mid;
8409         while (lo + 1 < hi) {
8410             mid = lo + (hi - lo) / 2;
8411             // mid has to be even to catch a range's beginning
8412             mid -= mid % 2;
8413             if (map[mid] <= code && code <= map[mid + 1]) {
8414                 return true;
8415             }
8416             if (code < map[mid]) {
8417                 hi = mid;
8418             }
8419             else {
8420                 lo = mid + 2;
8421             }
8422         }
8423         return false;
8424     }
8425     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8426         return languageVersion >= 2 /* ES2015 */ ?
8427             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8428             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8429                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8430     }
8431     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8432     function isUnicodeIdentifierPart(code, languageVersion) {
8433         return languageVersion >= 2 /* ES2015 */ ?
8434             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8435             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8436                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8437     }
8438     function makeReverseMap(source) {
8439         var result = [];
8440         source.forEach(function (value, name) {
8441             result[value] = name;
8442         });
8443         return result;
8444     }
8445     var tokenStrings = makeReverseMap(textToToken);
8446     function tokenToString(t) {
8447         return tokenStrings[t];
8448     }
8449     ts.tokenToString = tokenToString;
8450     /* @internal */
8451     function stringToToken(s) {
8452         return textToToken.get(s);
8453     }
8454     ts.stringToToken = stringToToken;
8455     /* @internal */
8456     function computeLineStarts(text) {
8457         var result = new Array();
8458         var pos = 0;
8459         var lineStart = 0;
8460         while (pos < text.length) {
8461             var ch = text.charCodeAt(pos);
8462             pos++;
8463             switch (ch) {
8464                 case 13 /* carriageReturn */:
8465                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8466                         pos++;
8467                     }
8468                 // falls through
8469                 case 10 /* lineFeed */:
8470                     result.push(lineStart);
8471                     lineStart = pos;
8472                     break;
8473                 default:
8474                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8475                         result.push(lineStart);
8476                         lineStart = pos;
8477                     }
8478                     break;
8479             }
8480         }
8481         result.push(lineStart);
8482         return result;
8483     }
8484     ts.computeLineStarts = computeLineStarts;
8485     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8486         return sourceFile.getPositionOfLineAndCharacter ?
8487             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8488             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8489     }
8490     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8491     /* @internal */
8492     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8493         if (line < 0 || line >= lineStarts.length) {
8494             if (allowEdits) {
8495                 // Clamp line to nearest allowable value
8496                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8497             }
8498             else {
8499                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8500             }
8501         }
8502         var res = lineStarts[line] + character;
8503         if (allowEdits) {
8504             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8505             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8506             // apply them to the computed position to improve accuracy
8507             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8508         }
8509         if (line < lineStarts.length - 1) {
8510             ts.Debug.assert(res < lineStarts[line + 1]);
8511         }
8512         else if (debugText !== undefined) {
8513             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8514         }
8515         return res;
8516     }
8517     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8518     /* @internal */
8519     function getLineStarts(sourceFile) {
8520         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8521     }
8522     ts.getLineStarts = getLineStarts;
8523     /* @internal */
8524     function computeLineAndCharacterOfPosition(lineStarts, position) {
8525         var lineNumber = computeLineOfPosition(lineStarts, position);
8526         return {
8527             line: lineNumber,
8528             character: position - lineStarts[lineNumber]
8529         };
8530     }
8531     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8532     /**
8533      * @internal
8534      * We assume the first line starts at position 0 and 'position' is non-negative.
8535      */
8536     function computeLineOfPosition(lineStarts, position, lowerBound) {
8537         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8538         if (lineNumber < 0) {
8539             // If the actual position was not found,
8540             // the binary search returns the 2's-complement of the next line start
8541             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8542             // then the search will return -2.
8543             //
8544             // We want the index of the previous line start, so we subtract 1.
8545             // Review 2's-complement if this is confusing.
8546             lineNumber = ~lineNumber - 1;
8547             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8548         }
8549         return lineNumber;
8550     }
8551     ts.computeLineOfPosition = computeLineOfPosition;
8552     /** @internal */
8553     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8554         if (pos1 === pos2)
8555             return 0;
8556         var lineStarts = getLineStarts(sourceFile);
8557         var lower = Math.min(pos1, pos2);
8558         var isNegative = lower === pos2;
8559         var upper = isNegative ? pos1 : pos2;
8560         var lowerLine = computeLineOfPosition(lineStarts, lower);
8561         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8562         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8563     }
8564     ts.getLinesBetweenPositions = getLinesBetweenPositions;
8565     function getLineAndCharacterOfPosition(sourceFile, position) {
8566         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8567     }
8568     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8569     function isWhiteSpaceLike(ch) {
8570         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8571     }
8572     ts.isWhiteSpaceLike = isWhiteSpaceLike;
8573     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8574     function isWhiteSpaceSingleLine(ch) {
8575         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8576         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8577         return ch === 32 /* space */ ||
8578             ch === 9 /* tab */ ||
8579             ch === 11 /* verticalTab */ ||
8580             ch === 12 /* formFeed */ ||
8581             ch === 160 /* nonBreakingSpace */ ||
8582             ch === 133 /* nextLine */ ||
8583             ch === 5760 /* ogham */ ||
8584             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8585             ch === 8239 /* narrowNoBreakSpace */ ||
8586             ch === 8287 /* mathematicalSpace */ ||
8587             ch === 12288 /* ideographicSpace */ ||
8588             ch === 65279 /* byteOrderMark */;
8589     }
8590     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8591     function isLineBreak(ch) {
8592         // ES5 7.3:
8593         // The ECMAScript line terminator characters are listed in Table 3.
8594         //     Table 3: Line Terminator Characters
8595         //     Code Unit Value     Name                    Formal Name
8596         //     \u000A              Line Feed               <LF>
8597         //     \u000D              Carriage Return         <CR>
8598         //     \u2028              Line separator          <LS>
8599         //     \u2029              Paragraph separator     <PS>
8600         // Only the characters in Table 3 are treated as line terminators. Other new line or line
8601         // breaking characters are treated as white space but not as line terminators.
8602         return ch === 10 /* lineFeed */ ||
8603             ch === 13 /* carriageReturn */ ||
8604             ch === 8232 /* lineSeparator */ ||
8605             ch === 8233 /* paragraphSeparator */;
8606     }
8607     ts.isLineBreak = isLineBreak;
8608     function isDigit(ch) {
8609         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8610     }
8611     function isHexDigit(ch) {
8612         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8613     }
8614     function isCodePoint(code) {
8615         return code <= 0x10FFFF;
8616     }
8617     /* @internal */
8618     function isOctalDigit(ch) {
8619         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8620     }
8621     ts.isOctalDigit = isOctalDigit;
8622     function couldStartTrivia(text, pos) {
8623         // Keep in sync with skipTrivia
8624         var ch = text.charCodeAt(pos);
8625         switch (ch) {
8626             case 13 /* carriageReturn */:
8627             case 10 /* lineFeed */:
8628             case 9 /* tab */:
8629             case 11 /* verticalTab */:
8630             case 12 /* formFeed */:
8631             case 32 /* space */:
8632             case 47 /* slash */:
8633             // starts of normal trivia
8634             // falls through
8635             case 60 /* lessThan */:
8636             case 124 /* bar */:
8637             case 61 /* equals */:
8638             case 62 /* greaterThan */:
8639                 // Starts of conflict marker trivia
8640                 return true;
8641             case 35 /* hash */:
8642                 // Only if its the beginning can we have #! trivia
8643                 return pos === 0;
8644             default:
8645                 return ch > 127 /* maxAsciiCharacter */;
8646         }
8647     }
8648     ts.couldStartTrivia = couldStartTrivia;
8649     /* @internal */
8650     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8651         if (stopAtComments === void 0) { stopAtComments = false; }
8652         if (ts.positionIsSynthesized(pos)) {
8653             return pos;
8654         }
8655         // Keep in sync with couldStartTrivia
8656         while (true) {
8657             var ch = text.charCodeAt(pos);
8658             switch (ch) {
8659                 case 13 /* carriageReturn */:
8660                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8661                         pos++;
8662                     }
8663                 // falls through
8664                 case 10 /* lineFeed */:
8665                     pos++;
8666                     if (stopAfterLineBreak) {
8667                         return pos;
8668                     }
8669                     continue;
8670                 case 9 /* tab */:
8671                 case 11 /* verticalTab */:
8672                 case 12 /* formFeed */:
8673                 case 32 /* space */:
8674                     pos++;
8675                     continue;
8676                 case 47 /* slash */:
8677                     if (stopAtComments) {
8678                         break;
8679                     }
8680                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8681                         pos += 2;
8682                         while (pos < text.length) {
8683                             if (isLineBreak(text.charCodeAt(pos))) {
8684                                 break;
8685                             }
8686                             pos++;
8687                         }
8688                         continue;
8689                     }
8690                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8691                         pos += 2;
8692                         while (pos < text.length) {
8693                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8694                                 pos += 2;
8695                                 break;
8696                             }
8697                             pos++;
8698                         }
8699                         continue;
8700                     }
8701                     break;
8702                 case 60 /* lessThan */:
8703                 case 124 /* bar */:
8704                 case 61 /* equals */:
8705                 case 62 /* greaterThan */:
8706                     if (isConflictMarkerTrivia(text, pos)) {
8707                         pos = scanConflictMarkerTrivia(text, pos);
8708                         continue;
8709                     }
8710                     break;
8711                 case 35 /* hash */:
8712                     if (pos === 0 && isShebangTrivia(text, pos)) {
8713                         pos = scanShebangTrivia(text, pos);
8714                         continue;
8715                     }
8716                     break;
8717                 default:
8718                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8719                         pos++;
8720                         continue;
8721                     }
8722                     break;
8723             }
8724             return pos;
8725         }
8726     }
8727     ts.skipTrivia = skipTrivia;
8728     // All conflict markers consist of the same character repeated seven times.  If it is
8729     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8730     var mergeConflictMarkerLength = "<<<<<<<".length;
8731     function isConflictMarkerTrivia(text, pos) {
8732         ts.Debug.assert(pos >= 0);
8733         // Conflict markers must be at the start of a line.
8734         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8735             var ch = text.charCodeAt(pos);
8736             if ((pos + mergeConflictMarkerLength) < text.length) {
8737                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8738                     if (text.charCodeAt(pos + i) !== ch) {
8739                         return false;
8740                     }
8741                 }
8742                 return ch === 61 /* equals */ ||
8743                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8744             }
8745         }
8746         return false;
8747     }
8748     function scanConflictMarkerTrivia(text, pos, error) {
8749         if (error) {
8750             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8751         }
8752         var ch = text.charCodeAt(pos);
8753         var len = text.length;
8754         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8755             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8756                 pos++;
8757             }
8758         }
8759         else {
8760             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8761             // Consume everything from the start of a ||||||| or ======= marker to the start
8762             // of the next ======= or >>>>>>> marker.
8763             while (pos < len) {
8764                 var currentChar = text.charCodeAt(pos);
8765                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8766                     break;
8767                 }
8768                 pos++;
8769             }
8770         }
8771         return pos;
8772     }
8773     var shebangTriviaRegex = /^#!.*/;
8774     /*@internal*/
8775     function isShebangTrivia(text, pos) {
8776         // Shebangs check must only be done at the start of the file
8777         ts.Debug.assert(pos === 0);
8778         return shebangTriviaRegex.test(text);
8779     }
8780     ts.isShebangTrivia = isShebangTrivia;
8781     /*@internal*/
8782     function scanShebangTrivia(text, pos) {
8783         var shebang = shebangTriviaRegex.exec(text)[0];
8784         pos = pos + shebang.length;
8785         return pos;
8786     }
8787     ts.scanShebangTrivia = scanShebangTrivia;
8788     /**
8789      * Invokes a callback for each comment range following the provided position.
8790      *
8791      * Single-line comment ranges include the leading double-slash characters but not the ending
8792      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8793      * asterisk-slash characters.
8794      *
8795      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8796      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8797      * @param text The source text to scan.
8798      * @param pos The position at which to start scanning.
8799      * @param trailing If false, whitespace is skipped until the first line break and comments
8800      *      between that location and the next token are returned. If true, comments occurring
8801      *      between the given position and the next line break are returned.
8802      * @param cb The callback to execute as each comment range is encountered.
8803      * @param state A state value to pass to each iteration of the callback.
8804      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8805      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8806      *      return value of the callback.
8807      */
8808     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8809         var pendingPos;
8810         var pendingEnd;
8811         var pendingKind;
8812         var pendingHasTrailingNewLine;
8813         var hasPendingCommentRange = false;
8814         var collecting = trailing;
8815         var accumulator = initial;
8816         if (pos === 0) {
8817             collecting = true;
8818             var shebang = getShebang(text);
8819             if (shebang) {
8820                 pos = shebang.length;
8821             }
8822         }
8823         scan: while (pos >= 0 && pos < text.length) {
8824             var ch = text.charCodeAt(pos);
8825             switch (ch) {
8826                 case 13 /* carriageReturn */:
8827                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8828                         pos++;
8829                     }
8830                 // falls through
8831                 case 10 /* lineFeed */:
8832                     pos++;
8833                     if (trailing) {
8834                         break scan;
8835                     }
8836                     collecting = true;
8837                     if (hasPendingCommentRange) {
8838                         pendingHasTrailingNewLine = true;
8839                     }
8840                     continue;
8841                 case 9 /* tab */:
8842                 case 11 /* verticalTab */:
8843                 case 12 /* formFeed */:
8844                 case 32 /* space */:
8845                     pos++;
8846                     continue;
8847                 case 47 /* slash */:
8848                     var nextChar = text.charCodeAt(pos + 1);
8849                     var hasTrailingNewLine = false;
8850                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
8851                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
8852                         var startPos = pos;
8853                         pos += 2;
8854                         if (nextChar === 47 /* slash */) {
8855                             while (pos < text.length) {
8856                                 if (isLineBreak(text.charCodeAt(pos))) {
8857                                     hasTrailingNewLine = true;
8858                                     break;
8859                                 }
8860                                 pos++;
8861                             }
8862                         }
8863                         else {
8864                             while (pos < text.length) {
8865                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8866                                     pos += 2;
8867                                     break;
8868                                 }
8869                                 pos++;
8870                             }
8871                         }
8872                         if (collecting) {
8873                             if (hasPendingCommentRange) {
8874                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8875                                 if (!reduce && accumulator) {
8876                                     // If we are not reducing and we have a truthy result, return it.
8877                                     return accumulator;
8878                                 }
8879                             }
8880                             pendingPos = startPos;
8881                             pendingEnd = pos;
8882                             pendingKind = kind;
8883                             pendingHasTrailingNewLine = hasTrailingNewLine;
8884                             hasPendingCommentRange = true;
8885                         }
8886                         continue;
8887                     }
8888                     break scan;
8889                 default:
8890                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8891                         if (hasPendingCommentRange && isLineBreak(ch)) {
8892                             pendingHasTrailingNewLine = true;
8893                         }
8894                         pos++;
8895                         continue;
8896                     }
8897                     break scan;
8898             }
8899         }
8900         if (hasPendingCommentRange) {
8901             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8902         }
8903         return accumulator;
8904     }
8905     function forEachLeadingCommentRange(text, pos, cb, state) {
8906         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
8907     }
8908     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
8909     function forEachTrailingCommentRange(text, pos, cb, state) {
8910         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
8911     }
8912     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
8913     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
8914         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
8915     }
8916     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
8917     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
8918         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
8919     }
8920     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
8921     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
8922         if (!comments) {
8923             comments = [];
8924         }
8925         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
8926         return comments;
8927     }
8928     function getLeadingCommentRanges(text, pos) {
8929         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8930     }
8931     ts.getLeadingCommentRanges = getLeadingCommentRanges;
8932     function getTrailingCommentRanges(text, pos) {
8933         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8934     }
8935     ts.getTrailingCommentRanges = getTrailingCommentRanges;
8936     /** Optionally, get the shebang */
8937     function getShebang(text) {
8938         var match = shebangTriviaRegex.exec(text);
8939         if (match) {
8940             return match[0];
8941         }
8942     }
8943     ts.getShebang = getShebang;
8944     function isIdentifierStart(ch, languageVersion) {
8945         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8946             ch === 36 /* $ */ || ch === 95 /* _ */ ||
8947             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
8948     }
8949     ts.isIdentifierStart = isIdentifierStart;
8950     function isIdentifierPart(ch, languageVersion, identifierVariant) {
8951         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8952             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
8953             // "-" and ":" are valid in JSX Identifiers
8954             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
8955             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
8956     }
8957     ts.isIdentifierPart = isIdentifierPart;
8958     /* @internal */
8959     function isIdentifierText(name, languageVersion, identifierVariant) {
8960         var ch = codePointAt(name, 0);
8961         if (!isIdentifierStart(ch, languageVersion)) {
8962             return false;
8963         }
8964         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
8965             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
8966                 return false;
8967             }
8968         }
8969         return true;
8970     }
8971     ts.isIdentifierText = isIdentifierText;
8972     // Creates a scanner over a (possibly unspecified) range of a piece of text.
8973     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
8974         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
8975         var text = textInitial;
8976         // Current position (end position of text of current token)
8977         var pos;
8978         // end of text
8979         var end;
8980         // Start position of whitespace before current token
8981         var startPos;
8982         // Start position of text of current token
8983         var tokenPos;
8984         var token;
8985         var tokenValue;
8986         var tokenFlags;
8987         var commentDirectives;
8988         var inJSDocType = 0;
8989         setText(text, start, length);
8990         var scanner = {
8991             getStartPos: function () { return startPos; },
8992             getTextPos: function () { return pos; },
8993             getToken: function () { return token; },
8994             getTokenPos: function () { return tokenPos; },
8995             getTokenText: function () { return text.substring(tokenPos, pos); },
8996             getTokenValue: function () { return tokenValue; },
8997             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
8998             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
8999             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
9000             isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
9001             isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
9002             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
9003             getCommentDirectives: function () { return commentDirectives; },
9004             getTokenFlags: function () { return tokenFlags; },
9005             reScanGreaterToken: reScanGreaterToken,
9006             reScanSlashToken: reScanSlashToken,
9007             reScanTemplateToken: reScanTemplateToken,
9008             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
9009             scanJsxIdentifier: scanJsxIdentifier,
9010             scanJsxAttributeValue: scanJsxAttributeValue,
9011             reScanJsxAttributeValue: reScanJsxAttributeValue,
9012             reScanJsxToken: reScanJsxToken,
9013             reScanLessThanToken: reScanLessThanToken,
9014             reScanQuestionToken: reScanQuestionToken,
9015             scanJsxToken: scanJsxToken,
9016             scanJsDocToken: scanJsDocToken,
9017             scan: scan,
9018             getText: getText,
9019             clearCommentDirectives: clearCommentDirectives,
9020             setText: setText,
9021             setScriptTarget: setScriptTarget,
9022             setLanguageVariant: setLanguageVariant,
9023             setOnError: setOnError,
9024             setTextPos: setTextPos,
9025             setInJSDocType: setInJSDocType,
9026             tryScan: tryScan,
9027             lookAhead: lookAhead,
9028             scanRange: scanRange,
9029         };
9030         if (ts.Debug.isDebugging) {
9031             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
9032                 get: function () {
9033                     var text = scanner.getText();
9034                     return text.slice(0, scanner.getStartPos()) + "║" + text.slice(scanner.getStartPos());
9035                 },
9036             });
9037         }
9038         return scanner;
9039         function error(message, errPos, length) {
9040             if (errPos === void 0) { errPos = pos; }
9041             if (onError) {
9042                 var oldPos = pos;
9043                 pos = errPos;
9044                 onError(message, length || 0);
9045                 pos = oldPos;
9046             }
9047         }
9048         function scanNumberFragment() {
9049             var start = pos;
9050             var allowSeparator = false;
9051             var isPreviousTokenSeparator = false;
9052             var result = "";
9053             while (true) {
9054                 var ch = text.charCodeAt(pos);
9055                 if (ch === 95 /* _ */) {
9056                     tokenFlags |= 512 /* ContainsSeparator */;
9057                     if (allowSeparator) {
9058                         allowSeparator = false;
9059                         isPreviousTokenSeparator = true;
9060                         result += text.substring(start, pos);
9061                     }
9062                     else if (isPreviousTokenSeparator) {
9063                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9064                     }
9065                     else {
9066                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9067                     }
9068                     pos++;
9069                     start = pos;
9070                     continue;
9071                 }
9072                 if (isDigit(ch)) {
9073                     allowSeparator = true;
9074                     isPreviousTokenSeparator = false;
9075                     pos++;
9076                     continue;
9077                 }
9078                 break;
9079             }
9080             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9081                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9082             }
9083             return result + text.substring(start, pos);
9084         }
9085         function scanNumber() {
9086             var start = pos;
9087             var mainFragment = scanNumberFragment();
9088             var decimalFragment;
9089             var scientificFragment;
9090             if (text.charCodeAt(pos) === 46 /* dot */) {
9091                 pos++;
9092                 decimalFragment = scanNumberFragment();
9093             }
9094             var end = pos;
9095             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
9096                 pos++;
9097                 tokenFlags |= 16 /* Scientific */;
9098                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
9099                     pos++;
9100                 var preNumericPart = pos;
9101                 var finalFragment = scanNumberFragment();
9102                 if (!finalFragment) {
9103                     error(ts.Diagnostics.Digit_expected);
9104                 }
9105                 else {
9106                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
9107                     end = pos;
9108                 }
9109             }
9110             var result;
9111             if (tokenFlags & 512 /* ContainsSeparator */) {
9112                 result = mainFragment;
9113                 if (decimalFragment) {
9114                     result += "." + decimalFragment;
9115                 }
9116                 if (scientificFragment) {
9117                     result += scientificFragment;
9118                 }
9119             }
9120             else {
9121                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
9122             }
9123             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
9124                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
9125                 return {
9126                     type: 8 /* NumericLiteral */,
9127                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
9128                 };
9129             }
9130             else {
9131                 tokenValue = result;
9132                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
9133                 checkForIdentifierStartAfterNumericLiteral(start);
9134                 return { type: type, value: tokenValue };
9135             }
9136         }
9137         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
9138             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
9139                 return;
9140             }
9141             var identifierStart = pos;
9142             var length = scanIdentifierParts().length;
9143             if (length === 1 && text[identifierStart] === "n") {
9144                 if (isScientific) {
9145                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
9146                 }
9147                 else {
9148                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
9149                 }
9150             }
9151             else {
9152                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
9153                 pos = identifierStart;
9154             }
9155         }
9156         function scanOctalDigits() {
9157             var start = pos;
9158             while (isOctalDigit(text.charCodeAt(pos))) {
9159                 pos++;
9160             }
9161             return +(text.substring(start, pos));
9162         }
9163         /**
9164          * Scans the given number of hexadecimal digits in the text,
9165          * returning -1 if the given number is unavailable.
9166          */
9167         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9168             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9169             return valueString ? parseInt(valueString, 16) : -1;
9170         }
9171         /**
9172          * Scans as many hexadecimal digits as are available in the text,
9173          * returning "" if the given number of digits was unavailable.
9174          */
9175         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9176             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9177         }
9178         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9179             var valueChars = [];
9180             var allowSeparator = false;
9181             var isPreviousTokenSeparator = false;
9182             while (valueChars.length < minCount || scanAsManyAsPossible) {
9183                 var ch = text.charCodeAt(pos);
9184                 if (canHaveSeparators && ch === 95 /* _ */) {
9185                     tokenFlags |= 512 /* ContainsSeparator */;
9186                     if (allowSeparator) {
9187                         allowSeparator = false;
9188                         isPreviousTokenSeparator = true;
9189                     }
9190                     else if (isPreviousTokenSeparator) {
9191                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9192                     }
9193                     else {
9194                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9195                     }
9196                     pos++;
9197                     continue;
9198                 }
9199                 allowSeparator = canHaveSeparators;
9200                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9201                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9202                 }
9203                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9204                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9205                     break;
9206                 }
9207                 valueChars.push(ch);
9208                 pos++;
9209                 isPreviousTokenSeparator = false;
9210             }
9211             if (valueChars.length < minCount) {
9212                 valueChars = [];
9213             }
9214             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9215                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9216             }
9217             return String.fromCharCode.apply(String, valueChars);
9218         }
9219         function scanString(jsxAttributeString) {
9220             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9221             var quote = text.charCodeAt(pos);
9222             pos++;
9223             var result = "";
9224             var start = pos;
9225             while (true) {
9226                 if (pos >= end) {
9227                     result += text.substring(start, pos);
9228                     tokenFlags |= 4 /* Unterminated */;
9229                     error(ts.Diagnostics.Unterminated_string_literal);
9230                     break;
9231                 }
9232                 var ch = text.charCodeAt(pos);
9233                 if (ch === quote) {
9234                     result += text.substring(start, pos);
9235                     pos++;
9236                     break;
9237                 }
9238                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9239                     result += text.substring(start, pos);
9240                     result += scanEscapeSequence();
9241                     start = pos;
9242                     continue;
9243                 }
9244                 if (isLineBreak(ch) && !jsxAttributeString) {
9245                     result += text.substring(start, pos);
9246                     tokenFlags |= 4 /* Unterminated */;
9247                     error(ts.Diagnostics.Unterminated_string_literal);
9248                     break;
9249                 }
9250                 pos++;
9251             }
9252             return result;
9253         }
9254         /**
9255          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9256          * a literal component of a TemplateExpression.
9257          */
9258         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9259             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9260             pos++;
9261             var start = pos;
9262             var contents = "";
9263             var resultingToken;
9264             while (true) {
9265                 if (pos >= end) {
9266                     contents += text.substring(start, pos);
9267                     tokenFlags |= 4 /* Unterminated */;
9268                     error(ts.Diagnostics.Unterminated_template_literal);
9269                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9270                     break;
9271                 }
9272                 var currChar = text.charCodeAt(pos);
9273                 // '`'
9274                 if (currChar === 96 /* backtick */) {
9275                     contents += text.substring(start, pos);
9276                     pos++;
9277                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9278                     break;
9279                 }
9280                 // '${'
9281                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9282                     contents += text.substring(start, pos);
9283                     pos += 2;
9284                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9285                     break;
9286                 }
9287                 // Escape character
9288                 if (currChar === 92 /* backslash */) {
9289                     contents += text.substring(start, pos);
9290                     contents += scanEscapeSequence(isTaggedTemplate);
9291                     start = pos;
9292                     continue;
9293                 }
9294                 // Speculated ECMAScript 6 Spec 11.8.6.1:
9295                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9296                 if (currChar === 13 /* carriageReturn */) {
9297                     contents += text.substring(start, pos);
9298                     pos++;
9299                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9300                         pos++;
9301                     }
9302                     contents += "\n";
9303                     start = pos;
9304                     continue;
9305                 }
9306                 pos++;
9307             }
9308             ts.Debug.assert(resultingToken !== undefined);
9309             tokenValue = contents;
9310             return resultingToken;
9311         }
9312         function scanEscapeSequence(isTaggedTemplate) {
9313             var start = pos;
9314             pos++;
9315             if (pos >= end) {
9316                 error(ts.Diagnostics.Unexpected_end_of_text);
9317                 return "";
9318             }
9319             var ch = text.charCodeAt(pos);
9320             pos++;
9321             switch (ch) {
9322                 case 48 /* _0 */:
9323                     // '\01'
9324                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9325                         pos++;
9326                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
9327                         return text.substring(start, pos);
9328                     }
9329                     return "\0";
9330                 case 98 /* b */:
9331                     return "\b";
9332                 case 116 /* t */:
9333                     return "\t";
9334                 case 110 /* n */:
9335                     return "\n";
9336                 case 118 /* v */:
9337                     return "\v";
9338                 case 102 /* f */:
9339                     return "\f";
9340                 case 114 /* r */:
9341                     return "\r";
9342                 case 39 /* singleQuote */:
9343                     return "\'";
9344                 case 34 /* doubleQuote */:
9345                     return "\"";
9346                 case 117 /* u */:
9347                     if (isTaggedTemplate) {
9348                         // '\u' or '\u0' or '\u00' or '\u000'
9349                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9350                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9351                                 pos = escapePos;
9352                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9353                                 return text.substring(start, pos);
9354                             }
9355                         }
9356                     }
9357                     // '\u{DDDDDDDD}'
9358                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9359                         pos++;
9360                         // '\u{'
9361                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9362                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9363                             return text.substring(start, pos);
9364                         }
9365                         if (isTaggedTemplate) {
9366                             var savePos = pos;
9367                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9368                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9369                             // '\u{Not Code Point' or '\u{CodePoint'
9370                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9371                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9372                                 return text.substring(start, pos);
9373                             }
9374                             else {
9375                                 pos = savePos;
9376                             }
9377                         }
9378                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9379                         return scanExtendedUnicodeEscape();
9380                     }
9381                     tokenFlags |= 1024 /* UnicodeEscape */;
9382                     // '\uDDDD'
9383                     return scanHexadecimalEscape(/*numDigits*/ 4);
9384                 case 120 /* x */:
9385                     if (isTaggedTemplate) {
9386                         if (!isHexDigit(text.charCodeAt(pos))) {
9387                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9388                             return text.substring(start, pos);
9389                         }
9390                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9391                             pos++;
9392                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9393                             return text.substring(start, pos);
9394                         }
9395                     }
9396                     // '\xDD'
9397                     return scanHexadecimalEscape(/*numDigits*/ 2);
9398                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9399                 // the line terminator is interpreted to be "the empty code unit sequence".
9400                 case 13 /* carriageReturn */:
9401                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9402                         pos++;
9403                     }
9404                 // falls through
9405                 case 10 /* lineFeed */:
9406                 case 8232 /* lineSeparator */:
9407                 case 8233 /* paragraphSeparator */:
9408                     return "";
9409                 default:
9410                     return String.fromCharCode(ch);
9411             }
9412         }
9413         function scanHexadecimalEscape(numDigits) {
9414             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9415             if (escapedValue >= 0) {
9416                 return String.fromCharCode(escapedValue);
9417             }
9418             else {
9419                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9420                 return "";
9421             }
9422         }
9423         function scanExtendedUnicodeEscape() {
9424             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9425             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9426             var isInvalidExtendedEscape = false;
9427             // Validate the value of the digit
9428             if (escapedValue < 0) {
9429                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9430                 isInvalidExtendedEscape = true;
9431             }
9432             else if (escapedValue > 0x10FFFF) {
9433                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9434                 isInvalidExtendedEscape = true;
9435             }
9436             if (pos >= end) {
9437                 error(ts.Diagnostics.Unexpected_end_of_text);
9438                 isInvalidExtendedEscape = true;
9439             }
9440             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9441                 // Only swallow the following character up if it's a '}'.
9442                 pos++;
9443             }
9444             else {
9445                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9446                 isInvalidExtendedEscape = true;
9447             }
9448             if (isInvalidExtendedEscape) {
9449                 return "";
9450             }
9451             return utf16EncodeAsString(escapedValue);
9452         }
9453         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9454         // and return code point value if valid Unicode escape is found. Otherwise return -1.
9455         function peekUnicodeEscape() {
9456             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9457                 var start_1 = pos;
9458                 pos += 2;
9459                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9460                 pos = start_1;
9461                 return value;
9462             }
9463             return -1;
9464         }
9465         function peekExtendedUnicodeEscape() {
9466             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9467                 var start_2 = pos;
9468                 pos += 3;
9469                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9470                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9471                 pos = start_2;
9472                 return escapedValue;
9473             }
9474             return -1;
9475         }
9476         function scanIdentifierParts() {
9477             var result = "";
9478             var start = pos;
9479             while (pos < end) {
9480                 var ch = codePointAt(text, pos);
9481                 if (isIdentifierPart(ch, languageVersion)) {
9482                     pos += charSize(ch);
9483                 }
9484                 else if (ch === 92 /* backslash */) {
9485                     ch = peekExtendedUnicodeEscape();
9486                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9487                         pos += 3;
9488                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9489                         result += scanExtendedUnicodeEscape();
9490                         start = pos;
9491                         continue;
9492                     }
9493                     ch = peekUnicodeEscape();
9494                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9495                         break;
9496                     }
9497                     tokenFlags |= 1024 /* UnicodeEscape */;
9498                     result += text.substring(start, pos);
9499                     result += utf16EncodeAsString(ch);
9500                     // Valid Unicode escape is always six characters
9501                     pos += 6;
9502                     start = pos;
9503                 }
9504                 else {
9505                     break;
9506                 }
9507             }
9508             result += text.substring(start, pos);
9509             return result;
9510         }
9511         function getIdentifierToken() {
9512             // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9513             var len = tokenValue.length;
9514             if (len >= 2 && len <= 11) {
9515                 var ch = tokenValue.charCodeAt(0);
9516                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9517                     var keyword = textToKeyword.get(tokenValue);
9518                     if (keyword !== undefined) {
9519                         return token = keyword;
9520                     }
9521                 }
9522             }
9523             return token = 75 /* Identifier */;
9524         }
9525         function scanBinaryOrOctalDigits(base) {
9526             var value = "";
9527             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9528             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9529             var separatorAllowed = false;
9530             var isPreviousTokenSeparator = false;
9531             while (true) {
9532                 var ch = text.charCodeAt(pos);
9533                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9534                 if (ch === 95 /* _ */) {
9535                     tokenFlags |= 512 /* ContainsSeparator */;
9536                     if (separatorAllowed) {
9537                         separatorAllowed = false;
9538                         isPreviousTokenSeparator = true;
9539                     }
9540                     else if (isPreviousTokenSeparator) {
9541                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9542                     }
9543                     else {
9544                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9545                     }
9546                     pos++;
9547                     continue;
9548                 }
9549                 separatorAllowed = true;
9550                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9551                     break;
9552                 }
9553                 value += text[pos];
9554                 pos++;
9555                 isPreviousTokenSeparator = false;
9556             }
9557             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9558                 // Literal ends with underscore - not allowed
9559                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9560             }
9561             return value;
9562         }
9563         function checkBigIntSuffix() {
9564             if (text.charCodeAt(pos) === 110 /* n */) {
9565                 tokenValue += "n";
9566                 // Use base 10 instead of base 2 or base 8 for shorter literals
9567                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9568                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9569                 }
9570                 pos++;
9571                 return 9 /* BigIntLiteral */;
9572             }
9573             else { // not a bigint, so can convert to number in simplified form
9574                 // Number() may not support 0b or 0o, so use parseInt() instead
9575                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9576                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9577                     : tokenFlags & 256 /* OctalSpecifier */
9578                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9579                         : +tokenValue;
9580                 tokenValue = "" + numericValue;
9581                 return 8 /* NumericLiteral */;
9582             }
9583         }
9584         function scan() {
9585             var _a;
9586             startPos = pos;
9587             tokenFlags = 0 /* None */;
9588             var asteriskSeen = false;
9589             while (true) {
9590                 tokenPos = pos;
9591                 if (pos >= end) {
9592                     return token = 1 /* EndOfFileToken */;
9593                 }
9594                 var ch = codePointAt(text, pos);
9595                 // Special handling for shebang
9596                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9597                     pos = scanShebangTrivia(text, pos);
9598                     if (skipTrivia) {
9599                         continue;
9600                     }
9601                     else {
9602                         return token = 6 /* ShebangTrivia */;
9603                     }
9604                 }
9605                 switch (ch) {
9606                     case 10 /* lineFeed */:
9607                     case 13 /* carriageReturn */:
9608                         tokenFlags |= 1 /* PrecedingLineBreak */;
9609                         if (skipTrivia) {
9610                             pos++;
9611                             continue;
9612                         }
9613                         else {
9614                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9615                                 // consume both CR and LF
9616                                 pos += 2;
9617                             }
9618                             else {
9619                                 pos++;
9620                             }
9621                             return token = 4 /* NewLineTrivia */;
9622                         }
9623                     case 9 /* tab */:
9624                     case 11 /* verticalTab */:
9625                     case 12 /* formFeed */:
9626                     case 32 /* space */:
9627                     case 160 /* nonBreakingSpace */:
9628                     case 5760 /* ogham */:
9629                     case 8192 /* enQuad */:
9630                     case 8193 /* emQuad */:
9631                     case 8194 /* enSpace */:
9632                     case 8195 /* emSpace */:
9633                     case 8196 /* threePerEmSpace */:
9634                     case 8197 /* fourPerEmSpace */:
9635                     case 8198 /* sixPerEmSpace */:
9636                     case 8199 /* figureSpace */:
9637                     case 8200 /* punctuationSpace */:
9638                     case 8201 /* thinSpace */:
9639                     case 8202 /* hairSpace */:
9640                     case 8203 /* zeroWidthSpace */:
9641                     case 8239 /* narrowNoBreakSpace */:
9642                     case 8287 /* mathematicalSpace */:
9643                     case 12288 /* ideographicSpace */:
9644                     case 65279 /* byteOrderMark */:
9645                         if (skipTrivia) {
9646                             pos++;
9647                             continue;
9648                         }
9649                         else {
9650                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9651                                 pos++;
9652                             }
9653                             return token = 5 /* WhitespaceTrivia */;
9654                         }
9655                     case 33 /* exclamation */:
9656                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9657                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9658                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9659                             }
9660                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
9661                         }
9662                         pos++;
9663                         return token = 53 /* ExclamationToken */;
9664                     case 34 /* doubleQuote */:
9665                     case 39 /* singleQuote */:
9666                         tokenValue = scanString();
9667                         return token = 10 /* StringLiteral */;
9668                     case 96 /* backtick */:
9669                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9670                     case 37 /* percent */:
9671                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9672                             return pos += 2, token = 68 /* PercentEqualsToken */;
9673                         }
9674                         pos++;
9675                         return token = 44 /* PercentToken */;
9676                     case 38 /* ampersand */:
9677                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9678                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9679                         }
9680                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9681                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
9682                         }
9683                         pos++;
9684                         return token = 50 /* AmpersandToken */;
9685                     case 40 /* openParen */:
9686                         pos++;
9687                         return token = 20 /* OpenParenToken */;
9688                     case 41 /* closeParen */:
9689                         pos++;
9690                         return token = 21 /* CloseParenToken */;
9691                     case 42 /* asterisk */:
9692                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9693                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
9694                         }
9695                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9696                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9697                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9698                             }
9699                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9700                         }
9701                         pos++;
9702                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9703                             // decoration at the start of a JSDoc comment line
9704                             asteriskSeen = true;
9705                             continue;
9706                         }
9707                         return token = 41 /* AsteriskToken */;
9708                     case 43 /* plus */:
9709                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9710                             return pos += 2, token = 45 /* PlusPlusToken */;
9711                         }
9712                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9713                             return pos += 2, token = 63 /* PlusEqualsToken */;
9714                         }
9715                         pos++;
9716                         return token = 39 /* PlusToken */;
9717                     case 44 /* comma */:
9718                         pos++;
9719                         return token = 27 /* CommaToken */;
9720                     case 45 /* minus */:
9721                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9722                             return pos += 2, token = 46 /* MinusMinusToken */;
9723                         }
9724                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9725                             return pos += 2, token = 64 /* MinusEqualsToken */;
9726                         }
9727                         pos++;
9728                         return token = 40 /* MinusToken */;
9729                     case 46 /* dot */:
9730                         if (isDigit(text.charCodeAt(pos + 1))) {
9731                             tokenValue = scanNumber().value;
9732                             return token = 8 /* NumericLiteral */;
9733                         }
9734                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9735                             return pos += 3, token = 25 /* DotDotDotToken */;
9736                         }
9737                         pos++;
9738                         return token = 24 /* DotToken */;
9739                     case 47 /* slash */:
9740                         // Single-line comment
9741                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9742                             pos += 2;
9743                             while (pos < end) {
9744                                 if (isLineBreak(text.charCodeAt(pos))) {
9745                                     break;
9746                                 }
9747                                 pos++;
9748                             }
9749                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9750                             if (skipTrivia) {
9751                                 continue;
9752                             }
9753                             else {
9754                                 return token = 2 /* SingleLineCommentTrivia */;
9755                             }
9756                         }
9757                         // Multi-line comment
9758                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9759                             pos += 2;
9760                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9761                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
9762                             }
9763                             var commentClosed = false;
9764                             var lastLineStart = tokenPos;
9765                             while (pos < end) {
9766                                 var ch_1 = text.charCodeAt(pos);
9767                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9768                                     pos += 2;
9769                                     commentClosed = true;
9770                                     break;
9771                                 }
9772                                 pos++;
9773                                 if (isLineBreak(ch_1)) {
9774                                     lastLineStart = pos;
9775                                     tokenFlags |= 1 /* PrecedingLineBreak */;
9776                                 }
9777                             }
9778                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9779                             if (!commentClosed) {
9780                                 error(ts.Diagnostics.Asterisk_Slash_expected);
9781                             }
9782                             if (skipTrivia) {
9783                                 continue;
9784                             }
9785                             else {
9786                                 if (!commentClosed) {
9787                                     tokenFlags |= 4 /* Unterminated */;
9788                                 }
9789                                 return token = 3 /* MultiLineCommentTrivia */;
9790                             }
9791                         }
9792                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9793                             return pos += 2, token = 67 /* SlashEqualsToken */;
9794                         }
9795                         pos++;
9796                         return token = 43 /* SlashToken */;
9797                     case 48 /* _0 */:
9798                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9799                             pos += 2;
9800                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9801                             if (!tokenValue) {
9802                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9803                                 tokenValue = "0";
9804                             }
9805                             tokenValue = "0x" + tokenValue;
9806                             tokenFlags |= 64 /* HexSpecifier */;
9807                             return token = checkBigIntSuffix();
9808                         }
9809                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9810                             pos += 2;
9811                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
9812                             if (!tokenValue) {
9813                                 error(ts.Diagnostics.Binary_digit_expected);
9814                                 tokenValue = "0";
9815                             }
9816                             tokenValue = "0b" + tokenValue;
9817                             tokenFlags |= 128 /* BinarySpecifier */;
9818                             return token = checkBigIntSuffix();
9819                         }
9820                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
9821                             pos += 2;
9822                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
9823                             if (!tokenValue) {
9824                                 error(ts.Diagnostics.Octal_digit_expected);
9825                                 tokenValue = "0";
9826                             }
9827                             tokenValue = "0o" + tokenValue;
9828                             tokenFlags |= 256 /* OctalSpecifier */;
9829                             return token = checkBigIntSuffix();
9830                         }
9831                         // Try to parse as an octal
9832                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
9833                             tokenValue = "" + scanOctalDigits();
9834                             tokenFlags |= 32 /* Octal */;
9835                             return token = 8 /* NumericLiteral */;
9836                         }
9837                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
9838                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
9839                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
9840                     // falls through
9841                     case 49 /* _1 */:
9842                     case 50 /* _2 */:
9843                     case 51 /* _3 */:
9844                     case 52 /* _4 */:
9845                     case 53 /* _5 */:
9846                     case 54 /* _6 */:
9847                     case 55 /* _7 */:
9848                     case 56 /* _8 */:
9849                     case 57 /* _9 */:
9850                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
9851                         return token;
9852                     case 58 /* colon */:
9853                         pos++;
9854                         return token = 58 /* ColonToken */;
9855                     case 59 /* semicolon */:
9856                         pos++;
9857                         return token = 26 /* SemicolonToken */;
9858                     case 60 /* lessThan */:
9859                         if (isConflictMarkerTrivia(text, pos)) {
9860                             pos = scanConflictMarkerTrivia(text, pos, error);
9861                             if (skipTrivia) {
9862                                 continue;
9863                             }
9864                             else {
9865                                 return token = 7 /* ConflictMarkerTrivia */;
9866                             }
9867                         }
9868                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
9869                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9870                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
9871                             }
9872                             return pos += 2, token = 47 /* LessThanLessThanToken */;
9873                         }
9874                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9875                             return pos += 2, token = 32 /* LessThanEqualsToken */;
9876                         }
9877                         if (languageVariant === 1 /* JSX */ &&
9878                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
9879                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
9880                             return pos += 2, token = 30 /* LessThanSlashToken */;
9881                         }
9882                         pos++;
9883                         return token = 29 /* LessThanToken */;
9884                     case 61 /* equals */:
9885                         if (isConflictMarkerTrivia(text, pos)) {
9886                             pos = scanConflictMarkerTrivia(text, pos, error);
9887                             if (skipTrivia) {
9888                                 continue;
9889                             }
9890                             else {
9891                                 return token = 7 /* ConflictMarkerTrivia */;
9892                             }
9893                         }
9894                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9895                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9896                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
9897                             }
9898                             return pos += 2, token = 34 /* EqualsEqualsToken */;
9899                         }
9900                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9901                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
9902                         }
9903                         pos++;
9904                         return token = 62 /* EqualsToken */;
9905                     case 62 /* greaterThan */:
9906                         if (isConflictMarkerTrivia(text, pos)) {
9907                             pos = scanConflictMarkerTrivia(text, pos, error);
9908                             if (skipTrivia) {
9909                                 continue;
9910                             }
9911                             else {
9912                                 return token = 7 /* ConflictMarkerTrivia */;
9913                             }
9914                         }
9915                         pos++;
9916                         return token = 31 /* GreaterThanToken */;
9917                     case 63 /* question */:
9918                         pos++;
9919                         if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
9920                             pos++;
9921                             return token = 28 /* QuestionDotToken */;
9922                         }
9923                         if (text.charCodeAt(pos) === 63 /* question */) {
9924                             pos++;
9925                             return token = 60 /* QuestionQuestionToken */;
9926                         }
9927                         return token = 57 /* QuestionToken */;
9928                     case 91 /* openBracket */:
9929                         pos++;
9930                         return token = 22 /* OpenBracketToken */;
9931                     case 93 /* closeBracket */:
9932                         pos++;
9933                         return token = 23 /* CloseBracketToken */;
9934                     case 94 /* caret */:
9935                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9936                             return pos += 2, token = 74 /* CaretEqualsToken */;
9937                         }
9938                         pos++;
9939                         return token = 52 /* CaretToken */;
9940                     case 123 /* openBrace */:
9941                         pos++;
9942                         return token = 18 /* OpenBraceToken */;
9943                     case 124 /* bar */:
9944                         if (isConflictMarkerTrivia(text, pos)) {
9945                             pos = scanConflictMarkerTrivia(text, pos, error);
9946                             if (skipTrivia) {
9947                                 continue;
9948                             }
9949                             else {
9950                                 return token = 7 /* ConflictMarkerTrivia */;
9951                             }
9952                         }
9953                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
9954                             return pos += 2, token = 56 /* BarBarToken */;
9955                         }
9956                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9957                             return pos += 2, token = 73 /* BarEqualsToken */;
9958                         }
9959                         pos++;
9960                         return token = 51 /* BarToken */;
9961                     case 125 /* closeBrace */:
9962                         pos++;
9963                         return token = 19 /* CloseBraceToken */;
9964                     case 126 /* tilde */:
9965                         pos++;
9966                         return token = 54 /* TildeToken */;
9967                     case 64 /* at */:
9968                         pos++;
9969                         return token = 59 /* AtToken */;
9970                     case 92 /* backslash */:
9971                         var extendedCookedChar = peekExtendedUnicodeEscape();
9972                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
9973                             pos += 3;
9974                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9975                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
9976                             return token = getIdentifierToken();
9977                         }
9978                         var cookedChar = peekUnicodeEscape();
9979                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
9980                             pos += 6;
9981                             tokenFlags |= 1024 /* UnicodeEscape */;
9982                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
9983                             return token = getIdentifierToken();
9984                         }
9985                         error(ts.Diagnostics.Invalid_character);
9986                         pos++;
9987                         return token = 0 /* Unknown */;
9988                     case 35 /* hash */:
9989                         if (pos !== 0 && text[pos + 1] === "!") {
9990                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
9991                             pos++;
9992                             return token = 0 /* Unknown */;
9993                         }
9994                         pos++;
9995                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
9996                             pos++;
9997                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
9998                                 pos++;
9999                             tokenValue = text.substring(tokenPos, pos);
10000                             if (ch === 92 /* backslash */) {
10001                                 tokenValue += scanIdentifierParts();
10002                             }
10003                         }
10004                         else {
10005                             tokenValue = "#";
10006                             error(ts.Diagnostics.Invalid_character);
10007                         }
10008                         return token = 76 /* PrivateIdentifier */;
10009                     default:
10010                         if (isIdentifierStart(ch, languageVersion)) {
10011                             pos += charSize(ch);
10012                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
10013                                 pos += charSize(ch);
10014                             tokenValue = text.substring(tokenPos, pos);
10015                             if (ch === 92 /* backslash */) {
10016                                 tokenValue += scanIdentifierParts();
10017                             }
10018                             return token = getIdentifierToken();
10019                         }
10020                         else if (isWhiteSpaceSingleLine(ch)) {
10021                             pos += charSize(ch);
10022                             continue;
10023                         }
10024                         else if (isLineBreak(ch)) {
10025                             tokenFlags |= 1 /* PrecedingLineBreak */;
10026                             pos += charSize(ch);
10027                             continue;
10028                         }
10029                         error(ts.Diagnostics.Invalid_character);
10030                         pos += charSize(ch);
10031                         return token = 0 /* Unknown */;
10032                 }
10033             }
10034         }
10035         function reScanGreaterToken() {
10036             if (token === 31 /* GreaterThanToken */) {
10037                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
10038                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10039                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10040                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
10041                         }
10042                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
10043                     }
10044                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10045                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
10046                     }
10047                     pos++;
10048                     return token = 48 /* GreaterThanGreaterThanToken */;
10049                 }
10050                 if (text.charCodeAt(pos) === 61 /* equals */) {
10051                     pos++;
10052                     return token = 33 /* GreaterThanEqualsToken */;
10053                 }
10054             }
10055             return token;
10056         }
10057         function reScanSlashToken() {
10058             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
10059                 var p = tokenPos + 1;
10060                 var inEscape = false;
10061                 var inCharacterClass = false;
10062                 while (true) {
10063                     // If we reach the end of a file, or hit a newline, then this is an unterminated
10064                     // regex.  Report error and return what we have so far.
10065                     if (p >= end) {
10066                         tokenFlags |= 4 /* Unterminated */;
10067                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
10068                         break;
10069                     }
10070                     var ch = text.charCodeAt(p);
10071                     if (isLineBreak(ch)) {
10072                         tokenFlags |= 4 /* Unterminated */;
10073                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
10074                         break;
10075                     }
10076                     if (inEscape) {
10077                         // Parsing an escape character;
10078                         // reset the flag and just advance to the next char.
10079                         inEscape = false;
10080                     }
10081                     else if (ch === 47 /* slash */ && !inCharacterClass) {
10082                         // A slash within a character class is permissible,
10083                         // but in general it signals the end of the regexp literal.
10084                         p++;
10085                         break;
10086                     }
10087                     else if (ch === 91 /* openBracket */) {
10088                         inCharacterClass = true;
10089                     }
10090                     else if (ch === 92 /* backslash */) {
10091                         inEscape = true;
10092                     }
10093                     else if (ch === 93 /* closeBracket */) {
10094                         inCharacterClass = false;
10095                     }
10096                     p++;
10097                 }
10098                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
10099                     p++;
10100                 }
10101                 pos = p;
10102                 tokenValue = text.substring(tokenPos, pos);
10103                 token = 13 /* RegularExpressionLiteral */;
10104             }
10105             return token;
10106         }
10107         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
10108             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
10109             if (type === undefined) {
10110                 return commentDirectives;
10111             }
10112             return ts.append(commentDirectives, {
10113                 range: { pos: lineStart, end: pos },
10114                 type: type,
10115             });
10116         }
10117         function getDirectiveFromComment(text, commentDirectiveRegEx) {
10118             var match = commentDirectiveRegEx.exec(text);
10119             if (!match) {
10120                 return undefined;
10121             }
10122             switch (match[1]) {
10123                 case "ts-expect-error":
10124                     return 0 /* ExpectError */;
10125                 case "ts-ignore":
10126                     return 1 /* Ignore */;
10127             }
10128             return undefined;
10129         }
10130         /**
10131          * Unconditionally back up and scan a template expression portion.
10132          */
10133         function reScanTemplateToken(isTaggedTemplate) {
10134             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
10135             pos = tokenPos;
10136             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
10137         }
10138         function reScanTemplateHeadOrNoSubstitutionTemplate() {
10139             pos = tokenPos;
10140             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
10141         }
10142         function reScanJsxToken() {
10143             pos = tokenPos = startPos;
10144             return token = scanJsxToken();
10145         }
10146         function reScanLessThanToken() {
10147             if (token === 47 /* LessThanLessThanToken */) {
10148                 pos = tokenPos + 1;
10149                 return token = 29 /* LessThanToken */;
10150             }
10151             return token;
10152         }
10153         function reScanQuestionToken() {
10154             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
10155             pos = tokenPos + 1;
10156             return token = 57 /* QuestionToken */;
10157         }
10158         function scanJsxToken() {
10159             startPos = tokenPos = pos;
10160             if (pos >= end) {
10161                 return token = 1 /* EndOfFileToken */;
10162             }
10163             var char = text.charCodeAt(pos);
10164             if (char === 60 /* lessThan */) {
10165                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10166                     pos += 2;
10167                     return token = 30 /* LessThanSlashToken */;
10168                 }
10169                 pos++;
10170                 return token = 29 /* LessThanToken */;
10171             }
10172             if (char === 123 /* openBrace */) {
10173                 pos++;
10174                 return token = 18 /* OpenBraceToken */;
10175             }
10176             // First non-whitespace character on this line.
10177             var firstNonWhitespace = 0;
10178             var lastNonWhitespace = -1;
10179             // These initial values are special because the first line is:
10180             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10181             while (pos < end) {
10182                 // We want to keep track of the last non-whitespace (but including
10183                 // newlines character for hitting the end of the JSX Text region)
10184                 if (!isWhiteSpaceSingleLine(char)) {
10185                     lastNonWhitespace = pos;
10186                 }
10187                 char = text.charCodeAt(pos);
10188                 if (char === 123 /* openBrace */) {
10189                     break;
10190                 }
10191                 if (char === 60 /* lessThan */) {
10192                     if (isConflictMarkerTrivia(text, pos)) {
10193                         pos = scanConflictMarkerTrivia(text, pos, error);
10194                         return token = 7 /* ConflictMarkerTrivia */;
10195                     }
10196                     break;
10197                 }
10198                 if (char === 62 /* greaterThan */) {
10199                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10200                 }
10201                 if (char === 125 /* closeBrace */) {
10202                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10203                 }
10204                 if (lastNonWhitespace > 0)
10205                     lastNonWhitespace++;
10206                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10207                 // i.e (- : whitespace)
10208                 //      <div>----
10209                 //      </div> becomes <div></div>
10210                 //
10211                 //      <div>----</div> becomes <div>----</div>
10212                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10213                     firstNonWhitespace = -1;
10214                 }
10215                 else if (!isWhiteSpaceLike(char)) {
10216                     firstNonWhitespace = pos;
10217                 }
10218                 pos++;
10219             }
10220             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10221             tokenValue = text.substring(startPos, endPosition);
10222             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10223         }
10224         // Scans a JSX identifier; these differ from normal identifiers in that
10225         // they allow dashes
10226         function scanJsxIdentifier() {
10227             if (tokenIsIdentifierOrKeyword(token)) {
10228                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10229                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10230                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10231                 while (pos < end) {
10232                     var ch = text.charCodeAt(pos);
10233                     if (ch === 45 /* minus */) {
10234                         tokenValue += "-";
10235                         pos++;
10236                         continue;
10237                     }
10238                     var oldPos = pos;
10239                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10240                     if (pos === oldPos) {
10241                         break;
10242                     }
10243                 }
10244             }
10245             return token;
10246         }
10247         function scanJsxAttributeValue() {
10248             startPos = pos;
10249             switch (text.charCodeAt(pos)) {
10250                 case 34 /* doubleQuote */:
10251                 case 39 /* singleQuote */:
10252                     tokenValue = scanString(/*jsxAttributeString*/ true);
10253                     return token = 10 /* StringLiteral */;
10254                 default:
10255                     // If this scans anything other than `{`, it's a parse error.
10256                     return scan();
10257             }
10258         }
10259         function reScanJsxAttributeValue() {
10260             pos = tokenPos = startPos;
10261             return scanJsxAttributeValue();
10262         }
10263         function scanJsDocToken() {
10264             startPos = tokenPos = pos;
10265             tokenFlags = 0 /* None */;
10266             if (pos >= end) {
10267                 return token = 1 /* EndOfFileToken */;
10268             }
10269             var ch = codePointAt(text, pos);
10270             pos += charSize(ch);
10271             switch (ch) {
10272                 case 9 /* tab */:
10273                 case 11 /* verticalTab */:
10274                 case 12 /* formFeed */:
10275                 case 32 /* space */:
10276                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10277                         pos++;
10278                     }
10279                     return token = 5 /* WhitespaceTrivia */;
10280                 case 64 /* at */:
10281                     return token = 59 /* AtToken */;
10282                 case 10 /* lineFeed */:
10283                 case 13 /* carriageReturn */:
10284                     tokenFlags |= 1 /* PrecedingLineBreak */;
10285                     return token = 4 /* NewLineTrivia */;
10286                 case 42 /* asterisk */:
10287                     return token = 41 /* AsteriskToken */;
10288                 case 123 /* openBrace */:
10289                     return token = 18 /* OpenBraceToken */;
10290                 case 125 /* closeBrace */:
10291                     return token = 19 /* CloseBraceToken */;
10292                 case 91 /* openBracket */:
10293                     return token = 22 /* OpenBracketToken */;
10294                 case 93 /* closeBracket */:
10295                     return token = 23 /* CloseBracketToken */;
10296                 case 60 /* lessThan */:
10297                     return token = 29 /* LessThanToken */;
10298                 case 62 /* greaterThan */:
10299                     return token = 31 /* GreaterThanToken */;
10300                 case 61 /* equals */:
10301                     return token = 62 /* EqualsToken */;
10302                 case 44 /* comma */:
10303                     return token = 27 /* CommaToken */;
10304                 case 46 /* dot */:
10305                     return token = 24 /* DotToken */;
10306                 case 96 /* backtick */:
10307                     return token = 61 /* BacktickToken */;
10308                 case 92 /* backslash */:
10309                     pos--;
10310                     var extendedCookedChar = peekExtendedUnicodeEscape();
10311                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10312                         pos += 3;
10313                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10314                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10315                         return token = getIdentifierToken();
10316                     }
10317                     var cookedChar = peekUnicodeEscape();
10318                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10319                         pos += 6;
10320                         tokenFlags |= 1024 /* UnicodeEscape */;
10321                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10322                         return token = getIdentifierToken();
10323                     }
10324                     pos++;
10325                     return token = 0 /* Unknown */;
10326             }
10327             if (isIdentifierStart(ch, languageVersion)) {
10328                 var char = ch;
10329                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10330                     pos += charSize(char);
10331                 tokenValue = text.substring(tokenPos, pos);
10332                 if (char === 92 /* backslash */) {
10333                     tokenValue += scanIdentifierParts();
10334                 }
10335                 return token = getIdentifierToken();
10336             }
10337             else {
10338                 return token = 0 /* Unknown */;
10339             }
10340         }
10341         function speculationHelper(callback, isLookahead) {
10342             var savePos = pos;
10343             var saveStartPos = startPos;
10344             var saveTokenPos = tokenPos;
10345             var saveToken = token;
10346             var saveTokenValue = tokenValue;
10347             var saveTokenFlags = tokenFlags;
10348             var result = callback();
10349             // If our callback returned something 'falsy' or we're just looking ahead,
10350             // then unconditionally restore us to where we were.
10351             if (!result || isLookahead) {
10352                 pos = savePos;
10353                 startPos = saveStartPos;
10354                 tokenPos = saveTokenPos;
10355                 token = saveToken;
10356                 tokenValue = saveTokenValue;
10357                 tokenFlags = saveTokenFlags;
10358             }
10359             return result;
10360         }
10361         function scanRange(start, length, callback) {
10362             var saveEnd = end;
10363             var savePos = pos;
10364             var saveStartPos = startPos;
10365             var saveTokenPos = tokenPos;
10366             var saveToken = token;
10367             var saveTokenValue = tokenValue;
10368             var saveTokenFlags = tokenFlags;
10369             var saveErrorExpectations = commentDirectives;
10370             setText(text, start, length);
10371             var result = callback();
10372             end = saveEnd;
10373             pos = savePos;
10374             startPos = saveStartPos;
10375             tokenPos = saveTokenPos;
10376             token = saveToken;
10377             tokenValue = saveTokenValue;
10378             tokenFlags = saveTokenFlags;
10379             commentDirectives = saveErrorExpectations;
10380             return result;
10381         }
10382         function lookAhead(callback) {
10383             return speculationHelper(callback, /*isLookahead*/ true);
10384         }
10385         function tryScan(callback) {
10386             return speculationHelper(callback, /*isLookahead*/ false);
10387         }
10388         function getText() {
10389             return text;
10390         }
10391         function clearCommentDirectives() {
10392             commentDirectives = undefined;
10393         }
10394         function setText(newText, start, length) {
10395             text = newText || "";
10396             end = length === undefined ? text.length : start + length;
10397             setTextPos(start || 0);
10398         }
10399         function setOnError(errorCallback) {
10400             onError = errorCallback;
10401         }
10402         function setScriptTarget(scriptTarget) {
10403             languageVersion = scriptTarget;
10404         }
10405         function setLanguageVariant(variant) {
10406             languageVariant = variant;
10407         }
10408         function setTextPos(textPos) {
10409             ts.Debug.assert(textPos >= 0);
10410             pos = textPos;
10411             startPos = textPos;
10412             tokenPos = textPos;
10413             token = 0 /* Unknown */;
10414             tokenValue = undefined;
10415             tokenFlags = 0 /* None */;
10416         }
10417         function setInJSDocType(inType) {
10418             inJSDocType += inType ? 1 : -1;
10419         }
10420     }
10421     ts.createScanner = createScanner;
10422     /* @internal */
10423     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10424         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10425         var size = str.length;
10426         // Account for out-of-bounds indices:
10427         if (i < 0 || i >= size) {
10428             return undefined; // String.codePointAt returns `undefined` for OOB indexes
10429         }
10430         // Get the first code unit
10431         var first = str.charCodeAt(i);
10432         // check if it’s the start of a surrogate pair
10433         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10434             var second = str.charCodeAt(i + 1);
10435             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10436                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10437                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10438             }
10439         }
10440         return first;
10441     };
10442     /* @internal */
10443     function charSize(ch) {
10444         if (ch >= 0x10000) {
10445             return 2;
10446         }
10447         return 1;
10448     }
10449     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10450     function utf16EncodeAsStringFallback(codePoint) {
10451         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10452         if (codePoint <= 65535) {
10453             return String.fromCharCode(codePoint);
10454         }
10455         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10456         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10457         return String.fromCharCode(codeUnit1, codeUnit2);
10458     }
10459     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10460     /* @internal */
10461     function utf16EncodeAsString(codePoint) {
10462         return utf16EncodeAsStringWorker(codePoint);
10463     }
10464     ts.utf16EncodeAsString = utf16EncodeAsString;
10465 })(ts || (ts = {}));
10466 var ts;
10467 (function (ts) {
10468     function isExternalModuleNameRelative(moduleName) {
10469         // TypeScript 1.0 spec (April 2014): 11.2.1
10470         // An external module name is "relative" if the first term is "." or "..".
10471         // 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.
10472         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10473     }
10474     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10475     function sortAndDeduplicateDiagnostics(diagnostics) {
10476         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10477     }
10478     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10479     function getDefaultLibFileName(options) {
10480         switch (options.target) {
10481             case 99 /* ESNext */:
10482                 return "lib.esnext.full.d.ts";
10483             case 7 /* ES2020 */:
10484                 return "lib.es2020.full.d.ts";
10485             case 6 /* ES2019 */:
10486                 return "lib.es2019.full.d.ts";
10487             case 5 /* ES2018 */:
10488                 return "lib.es2018.full.d.ts";
10489             case 4 /* ES2017 */:
10490                 return "lib.es2017.full.d.ts";
10491             case 3 /* ES2016 */:
10492                 return "lib.es2016.full.d.ts";
10493             case 2 /* ES2015 */:
10494                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10495             default:
10496                 return "lib.d.ts";
10497         }
10498     }
10499     ts.getDefaultLibFileName = getDefaultLibFileName;
10500     function textSpanEnd(span) {
10501         return span.start + span.length;
10502     }
10503     ts.textSpanEnd = textSpanEnd;
10504     function textSpanIsEmpty(span) {
10505         return span.length === 0;
10506     }
10507     ts.textSpanIsEmpty = textSpanIsEmpty;
10508     function textSpanContainsPosition(span, position) {
10509         return position >= span.start && position < textSpanEnd(span);
10510     }
10511     ts.textSpanContainsPosition = textSpanContainsPosition;
10512     /* @internal */
10513     function textRangeContainsPositionInclusive(span, position) {
10514         return position >= span.pos && position <= span.end;
10515     }
10516     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10517     // Returns true if 'span' contains 'other'.
10518     function textSpanContainsTextSpan(span, other) {
10519         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10520     }
10521     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10522     function textSpanOverlapsWith(span, other) {
10523         return textSpanOverlap(span, other) !== undefined;
10524     }
10525     ts.textSpanOverlapsWith = textSpanOverlapsWith;
10526     function textSpanOverlap(span1, span2) {
10527         var overlap = textSpanIntersection(span1, span2);
10528         return overlap && overlap.length === 0 ? undefined : overlap;
10529     }
10530     ts.textSpanOverlap = textSpanOverlap;
10531     function textSpanIntersectsWithTextSpan(span, other) {
10532         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10533     }
10534     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10535     function textSpanIntersectsWith(span, start, length) {
10536         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10537     }
10538     ts.textSpanIntersectsWith = textSpanIntersectsWith;
10539     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10540         var end1 = start1 + length1;
10541         var end2 = start2 + length2;
10542         return start2 <= end1 && end2 >= start1;
10543     }
10544     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10545     function textSpanIntersectsWithPosition(span, position) {
10546         return position <= textSpanEnd(span) && position >= span.start;
10547     }
10548     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10549     function textSpanIntersection(span1, span2) {
10550         var start = Math.max(span1.start, span2.start);
10551         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10552         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10553     }
10554     ts.textSpanIntersection = textSpanIntersection;
10555     function createTextSpan(start, length) {
10556         if (start < 0) {
10557             throw new Error("start < 0");
10558         }
10559         if (length < 0) {
10560             throw new Error("length < 0");
10561         }
10562         return { start: start, length: length };
10563     }
10564     ts.createTextSpan = createTextSpan;
10565     function createTextSpanFromBounds(start, end) {
10566         return createTextSpan(start, end - start);
10567     }
10568     ts.createTextSpanFromBounds = createTextSpanFromBounds;
10569     function textChangeRangeNewSpan(range) {
10570         return createTextSpan(range.span.start, range.newLength);
10571     }
10572     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10573     function textChangeRangeIsUnchanged(range) {
10574         return textSpanIsEmpty(range.span) && range.newLength === 0;
10575     }
10576     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10577     function createTextChangeRange(span, newLength) {
10578         if (newLength < 0) {
10579             throw new Error("newLength < 0");
10580         }
10581         return { span: span, newLength: newLength };
10582     }
10583     ts.createTextChangeRange = createTextChangeRange;
10584     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10585     /**
10586      * Called to merge all the changes that occurred across several versions of a script snapshot
10587      * into a single change.  i.e. if a user keeps making successive edits to a script we will
10588      * have a text change from V1 to V2, V2 to V3, ..., Vn.
10589      *
10590      * This function will then merge those changes into a single change range valid between V1 and
10591      * Vn.
10592      */
10593     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10594         if (changes.length === 0) {
10595             return ts.unchangedTextChangeRange;
10596         }
10597         if (changes.length === 1) {
10598             return changes[0];
10599         }
10600         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10601         // as it makes things much easier to reason about.
10602         var change0 = changes[0];
10603         var oldStartN = change0.span.start;
10604         var oldEndN = textSpanEnd(change0.span);
10605         var newEndN = oldStartN + change0.newLength;
10606         for (var i = 1; i < changes.length; i++) {
10607             var nextChange = changes[i];
10608             // Consider the following case:
10609             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
10610             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
10611             // i.e. the span starting at 30 with length 30 is increased to length 40.
10612             //
10613             //      0         10        20        30        40        50        60        70        80        90        100
10614             //      -------------------------------------------------------------------------------------------------------
10615             //                |                                                 /
10616             //                |                                            /----
10617             //  T1            |                                       /----
10618             //                |                                  /----
10619             //                |                             /----
10620             //      -------------------------------------------------------------------------------------------------------
10621             //                                     |                            \
10622             //                                     |                               \
10623             //   T2                                |                                 \
10624             //                                     |                                   \
10625             //                                     |                                      \
10626             //      -------------------------------------------------------------------------------------------------------
10627             //
10628             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
10629             // it's just the min of the old and new starts.  i.e.:
10630             //
10631             //      0         10        20        30        40        50        60        70        80        90        100
10632             //      ------------------------------------------------------------*------------------------------------------
10633             //                |                                                 /
10634             //                |                                            /----
10635             //  T1            |                                       /----
10636             //                |                                  /----
10637             //                |                             /----
10638             //      ----------------------------------------$-------------------$------------------------------------------
10639             //                .                    |                            \
10640             //                .                    |                               \
10641             //   T2           .                    |                                 \
10642             //                .                    |                                   \
10643             //                .                    |                                      \
10644             //      ----------------------------------------------------------------------*--------------------------------
10645             //
10646             // (Note the dots represent the newly inferred start.
10647             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
10648             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10649             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
10650             // means:
10651             //
10652             //      0         10        20        30        40        50        60        70        80        90        100
10653             //      --------------------------------------------------------------------------------*----------------------
10654             //                |                                                                     /
10655             //                |                                                                /----
10656             //  T1            |                                                           /----
10657             //                |                                                      /----
10658             //                |                                                 /----
10659             //      ------------------------------------------------------------$------------------------------------------
10660             //                .                    |                            \
10661             //                .                    |                               \
10662             //   T2           .                    |                                 \
10663             //                .                    |                                   \
10664             //                .                    |                                      \
10665             //      ----------------------------------------------------------------------*--------------------------------
10666             //
10667             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10668             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
10669             // that's the same as if we started at char 80 instead of 60.
10670             //
10671             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
10672             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10673             // first.
10674             //
10675             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10676             // semantics: { { start: 10, length: 70 }, newLength: 60 }
10677             //
10678             // The math then works out as follows.
10679             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10680             // final result like so:
10681             //
10682             // {
10683             //      oldStart3: Min(oldStart1, oldStart2),
10684             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10685             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10686             // }
10687             var oldStart1 = oldStartN;
10688             var oldEnd1 = oldEndN;
10689             var newEnd1 = newEndN;
10690             var oldStart2 = nextChange.span.start;
10691             var oldEnd2 = textSpanEnd(nextChange.span);
10692             var newEnd2 = oldStart2 + nextChange.newLength;
10693             oldStartN = Math.min(oldStart1, oldStart2);
10694             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10695             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10696         }
10697         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10698     }
10699     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10700     function getTypeParameterOwner(d) {
10701         if (d && d.kind === 155 /* TypeParameter */) {
10702             for (var current = d; current; current = current.parent) {
10703                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
10704                     return current;
10705                 }
10706             }
10707         }
10708     }
10709     ts.getTypeParameterOwner = getTypeParameterOwner;
10710     function isParameterPropertyDeclaration(node, parent) {
10711         return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
10712     }
10713     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10714     function isEmptyBindingPattern(node) {
10715         if (isBindingPattern(node)) {
10716             return ts.every(node.elements, isEmptyBindingElement);
10717         }
10718         return false;
10719     }
10720     ts.isEmptyBindingPattern = isEmptyBindingPattern;
10721     function isEmptyBindingElement(node) {
10722         if (isOmittedExpression(node)) {
10723             return true;
10724         }
10725         return isEmptyBindingPattern(node.name);
10726     }
10727     ts.isEmptyBindingElement = isEmptyBindingElement;
10728     function walkUpBindingElementsAndPatterns(binding) {
10729         var node = binding.parent;
10730         while (isBindingElement(node.parent)) {
10731             node = node.parent.parent;
10732         }
10733         return node.parent;
10734     }
10735     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10736     function getCombinedFlags(node, getFlags) {
10737         if (isBindingElement(node)) {
10738             node = walkUpBindingElementsAndPatterns(node);
10739         }
10740         var flags = getFlags(node);
10741         if (node.kind === 242 /* VariableDeclaration */) {
10742             node = node.parent;
10743         }
10744         if (node && node.kind === 243 /* VariableDeclarationList */) {
10745             flags |= getFlags(node);
10746             node = node.parent;
10747         }
10748         if (node && node.kind === 225 /* VariableStatement */) {
10749             flags |= getFlags(node);
10750         }
10751         return flags;
10752     }
10753     function getCombinedModifierFlags(node) {
10754         return getCombinedFlags(node, ts.getModifierFlags);
10755     }
10756     ts.getCombinedModifierFlags = getCombinedModifierFlags;
10757     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
10758     // nodes like variable declarations and binding elements can returned a view of their flags
10759     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
10760     // stored on the variable declaration directly, but on the containing variable statement
10761     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
10762     // list.  By calling this function, all those flags are combined so that the client can treat
10763     // the node as if it actually had those flags.
10764     function getCombinedNodeFlags(node) {
10765         return getCombinedFlags(node, function (n) { return n.flags; });
10766     }
10767     ts.getCombinedNodeFlags = getCombinedNodeFlags;
10768     /**
10769      * Checks to see if the locale is in the appropriate format,
10770      * and if it is, attempts to set the appropriate language.
10771      */
10772     function validateLocaleAndSetLanguage(locale, sys, errors) {
10773         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10774         if (!matchResult) {
10775             if (errors) {
10776                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10777             }
10778             return;
10779         }
10780         var language = matchResult[1];
10781         var territory = matchResult[3];
10782         // First try the entire locale, then fall back to just language if that's all we have.
10783         // Either ways do not fail, and fallback to the English diagnostic strings.
10784         if (!trySetLanguageAndTerritory(language, territory, errors)) {
10785             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10786         }
10787         // Set the UI locale for string collation
10788         ts.setUILocale(locale);
10789         function trySetLanguageAndTerritory(language, territory, errors) {
10790             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10791             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10792             var filePath = ts.combinePaths(containingDirectoryPath, language);
10793             if (territory) {
10794                 filePath = filePath + "-" + territory;
10795             }
10796             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
10797             if (!sys.fileExists(filePath)) {
10798                 return false;
10799             }
10800             // TODO: Add codePage support for readFile?
10801             var fileContents = "";
10802             try {
10803                 fileContents = sys.readFile(filePath);
10804             }
10805             catch (e) {
10806                 if (errors) {
10807                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
10808                 }
10809                 return false;
10810             }
10811             try {
10812                 // this is a global mutation (or live binding update)!
10813                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
10814             }
10815             catch (_a) {
10816                 if (errors) {
10817                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
10818                 }
10819                 return false;
10820             }
10821             return true;
10822         }
10823     }
10824     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
10825     function getOriginalNode(node, nodeTest) {
10826         if (node) {
10827             while (node.original !== undefined) {
10828                 node = node.original;
10829             }
10830         }
10831         return !nodeTest || nodeTest(node) ? node : undefined;
10832     }
10833     ts.getOriginalNode = getOriginalNode;
10834     /**
10835      * Gets a value indicating whether a node originated in the parse tree.
10836      *
10837      * @param node The node to test.
10838      */
10839     function isParseTreeNode(node) {
10840         return (node.flags & 8 /* Synthesized */) === 0;
10841     }
10842     ts.isParseTreeNode = isParseTreeNode;
10843     function getParseTreeNode(node, nodeTest) {
10844         if (node === undefined || isParseTreeNode(node)) {
10845             return node;
10846         }
10847         node = getOriginalNode(node);
10848         if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
10849             return node;
10850         }
10851         return undefined;
10852     }
10853     ts.getParseTreeNode = getParseTreeNode;
10854     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
10855     function escapeLeadingUnderscores(identifier) {
10856         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
10857     }
10858     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
10859     /**
10860      * Remove extra underscore from escaped identifier text content.
10861      *
10862      * @param identifier The escaped identifier text.
10863      * @returns The unescaped identifier text.
10864      */
10865     function unescapeLeadingUnderscores(identifier) {
10866         var id = identifier;
10867         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
10868     }
10869     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
10870     function idText(identifierOrPrivateName) {
10871         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
10872     }
10873     ts.idText = idText;
10874     function symbolName(symbol) {
10875         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
10876             return idText(symbol.valueDeclaration.name);
10877         }
10878         return unescapeLeadingUnderscores(symbol.escapedName);
10879     }
10880     ts.symbolName = symbolName;
10881     /**
10882      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
10883      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
10884      * will be merged with)
10885      */
10886     function nameForNamelessJSDocTypedef(declaration) {
10887         var hostNode = declaration.parent.parent;
10888         if (!hostNode) {
10889             return undefined;
10890         }
10891         // Covers classes, functions - any named declaration host node
10892         if (isDeclaration(hostNode)) {
10893             return getDeclarationIdentifier(hostNode);
10894         }
10895         // Covers remaining cases (returning undefined if none match).
10896         switch (hostNode.kind) {
10897             case 225 /* VariableStatement */:
10898                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
10899                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
10900                 }
10901                 break;
10902             case 226 /* ExpressionStatement */:
10903                 var expr = hostNode.expression;
10904                 if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
10905                     expr = expr.left;
10906                 }
10907                 switch (expr.kind) {
10908                     case 194 /* PropertyAccessExpression */:
10909                         return expr.name;
10910                     case 195 /* ElementAccessExpression */:
10911                         var arg = expr.argumentExpression;
10912                         if (isIdentifier(arg)) {
10913                             return arg;
10914                         }
10915                 }
10916                 break;
10917             case 200 /* ParenthesizedExpression */: {
10918                 return getDeclarationIdentifier(hostNode.expression);
10919             }
10920             case 238 /* LabeledStatement */: {
10921                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
10922                     return getDeclarationIdentifier(hostNode.statement);
10923                 }
10924                 break;
10925             }
10926         }
10927     }
10928     function getDeclarationIdentifier(node) {
10929         var name = getNameOfDeclaration(node);
10930         return name && isIdentifier(name) ? name : undefined;
10931     }
10932     /** @internal */
10933     function nodeHasName(statement, name) {
10934         if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
10935             return true;
10936         }
10937         if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
10938             return true;
10939         }
10940         return false;
10941     }
10942     ts.nodeHasName = nodeHasName;
10943     function getNameOfJSDocTypedef(declaration) {
10944         return declaration.name || nameForNamelessJSDocTypedef(declaration);
10945     }
10946     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
10947     /** @internal */
10948     function isNamedDeclaration(node) {
10949         return !!node.name; // A 'name' property should always be a DeclarationName.
10950     }
10951     ts.isNamedDeclaration = isNamedDeclaration;
10952     /** @internal */
10953     function getNonAssignedNameOfDeclaration(declaration) {
10954         switch (declaration.kind) {
10955             case 75 /* Identifier */:
10956                 return declaration;
10957             case 323 /* JSDocPropertyTag */:
10958             case 317 /* JSDocParameterTag */: {
10959                 var name = declaration.name;
10960                 if (name.kind === 153 /* QualifiedName */) {
10961                     return name.right;
10962                 }
10963                 break;
10964             }
10965             case 196 /* CallExpression */:
10966             case 209 /* BinaryExpression */: {
10967                 var expr_1 = declaration;
10968                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
10969                     case 1 /* ExportsProperty */:
10970                     case 4 /* ThisProperty */:
10971                     case 5 /* Property */:
10972                     case 3 /* PrototypeProperty */:
10973                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
10974                     case 7 /* ObjectDefinePropertyValue */:
10975                     case 8 /* ObjectDefinePropertyExports */:
10976                     case 9 /* ObjectDefinePrototypeProperty */:
10977                         return expr_1.arguments[1];
10978                     default:
10979                         return undefined;
10980                 }
10981             }
10982             case 322 /* JSDocTypedefTag */:
10983                 return getNameOfJSDocTypedef(declaration);
10984             case 316 /* JSDocEnumTag */:
10985                 return nameForNamelessJSDocTypedef(declaration);
10986             case 259 /* ExportAssignment */: {
10987                 var expression = declaration.expression;
10988                 return isIdentifier(expression) ? expression : undefined;
10989             }
10990             case 195 /* ElementAccessExpression */:
10991                 var expr = declaration;
10992                 if (ts.isBindableStaticElementAccessExpression(expr)) {
10993                     return expr.argumentExpression;
10994                 }
10995         }
10996         return declaration.name;
10997     }
10998     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
10999     function getNameOfDeclaration(declaration) {
11000         if (declaration === undefined)
11001             return undefined;
11002         return getNonAssignedNameOfDeclaration(declaration) ||
11003             (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
11004     }
11005     ts.getNameOfDeclaration = getNameOfDeclaration;
11006     function getAssignedName(node) {
11007         if (!node.parent) {
11008             return undefined;
11009         }
11010         else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
11011             return node.parent.name;
11012         }
11013         else if (isBinaryExpression(node.parent) && node === node.parent.right) {
11014             if (isIdentifier(node.parent.left)) {
11015                 return node.parent.left;
11016             }
11017             else if (ts.isAccessExpression(node.parent.left)) {
11018                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
11019             }
11020         }
11021         else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
11022             return node.parent.name;
11023         }
11024     }
11025     /**
11026      * Gets the JSDoc parameter tags for the node if present.
11027      *
11028      * @remarks Returns any JSDoc param tag whose name matches the provided
11029      * parameter, whether a param tag on a containing function
11030      * expression, or a param tag on a variable declaration whose
11031      * initializer is the containing function. The tags closest to the
11032      * node are returned first, so in the previous example, the param
11033      * tag on the containing function expression would be first.
11034      *
11035      * For binding patterns, parameter tags are matched by position.
11036      */
11037     function getJSDocParameterTags(param) {
11038         if (param.name) {
11039             if (isIdentifier(param.name)) {
11040                 var name_1 = param.name.escapedText;
11041                 return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
11042             }
11043             else {
11044                 var i = param.parent.parameters.indexOf(param);
11045                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
11046                 var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
11047                 if (i < paramTags.length) {
11048                     return [paramTags[i]];
11049                 }
11050             }
11051         }
11052         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
11053         return ts.emptyArray;
11054     }
11055     ts.getJSDocParameterTags = getJSDocParameterTags;
11056     /**
11057      * Gets the JSDoc type parameter tags for the node if present.
11058      *
11059      * @remarks Returns any JSDoc template tag whose names match the provided
11060      * parameter, whether a template tag on a containing function
11061      * expression, or a template tag on a variable declaration whose
11062      * initializer is the containing function. The tags closest to the
11063      * node are returned first, so in the previous example, the template
11064      * tag on the containing function expression would be first.
11065      */
11066     function getJSDocTypeParameterTags(param) {
11067         var name = param.name.escapedText;
11068         return getJSDocTags(param.parent).filter(function (tag) {
11069             return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
11070         });
11071     }
11072     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
11073     /**
11074      * Return true if the node has JSDoc parameter tags.
11075      *
11076      * @remarks Includes parameter tags that are not directly on the node,
11077      * for example on a variable declaration whose initializer is a function expression.
11078      */
11079     function hasJSDocParameterTags(node) {
11080         return !!getFirstJSDocTag(node, isJSDocParameterTag);
11081     }
11082     ts.hasJSDocParameterTags = hasJSDocParameterTags;
11083     /** Gets the JSDoc augments tag for the node if present */
11084     function getJSDocAugmentsTag(node) {
11085         return getFirstJSDocTag(node, isJSDocAugmentsTag);
11086     }
11087     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
11088     /** Gets the JSDoc implements tags for the node if present */
11089     function getJSDocImplementsTags(node) {
11090         return getAllJSDocTags(node, isJSDocImplementsTag);
11091     }
11092     ts.getJSDocImplementsTags = getJSDocImplementsTags;
11093     /** Gets the JSDoc class tag for the node if present */
11094     function getJSDocClassTag(node) {
11095         return getFirstJSDocTag(node, isJSDocClassTag);
11096     }
11097     ts.getJSDocClassTag = getJSDocClassTag;
11098     /** Gets the JSDoc public tag for the node if present */
11099     function getJSDocPublicTag(node) {
11100         return getFirstJSDocTag(node, isJSDocPublicTag);
11101     }
11102     ts.getJSDocPublicTag = getJSDocPublicTag;
11103     /** Gets the JSDoc private tag for the node if present */
11104     function getJSDocPrivateTag(node) {
11105         return getFirstJSDocTag(node, isJSDocPrivateTag);
11106     }
11107     ts.getJSDocPrivateTag = getJSDocPrivateTag;
11108     /** Gets the JSDoc protected tag for the node if present */
11109     function getJSDocProtectedTag(node) {
11110         return getFirstJSDocTag(node, isJSDocProtectedTag);
11111     }
11112     ts.getJSDocProtectedTag = getJSDocProtectedTag;
11113     /** Gets the JSDoc protected tag for the node if present */
11114     function getJSDocReadonlyTag(node) {
11115         return getFirstJSDocTag(node, isJSDocReadonlyTag);
11116     }
11117     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
11118     /** Gets the JSDoc enum tag for the node if present */
11119     function getJSDocEnumTag(node) {
11120         return getFirstJSDocTag(node, isJSDocEnumTag);
11121     }
11122     ts.getJSDocEnumTag = getJSDocEnumTag;
11123     /** Gets the JSDoc this tag for the node if present */
11124     function getJSDocThisTag(node) {
11125         return getFirstJSDocTag(node, isJSDocThisTag);
11126     }
11127     ts.getJSDocThisTag = getJSDocThisTag;
11128     /** Gets the JSDoc return tag for the node if present */
11129     function getJSDocReturnTag(node) {
11130         return getFirstJSDocTag(node, isJSDocReturnTag);
11131     }
11132     ts.getJSDocReturnTag = getJSDocReturnTag;
11133     /** Gets the JSDoc template tag for the node if present */
11134     function getJSDocTemplateTag(node) {
11135         return getFirstJSDocTag(node, isJSDocTemplateTag);
11136     }
11137     ts.getJSDocTemplateTag = getJSDocTemplateTag;
11138     /** Gets the JSDoc type tag for the node if present and valid */
11139     function getJSDocTypeTag(node) {
11140         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
11141         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11142         if (tag && tag.typeExpression && tag.typeExpression.type) {
11143             return tag;
11144         }
11145         return undefined;
11146     }
11147     ts.getJSDocTypeTag = getJSDocTypeTag;
11148     /**
11149      * Gets the type node for the node if provided via JSDoc.
11150      *
11151      * @remarks The search includes any JSDoc param tag that relates
11152      * to the provided parameter, for example a type tag on the
11153      * parameter itself, or a param tag on a containing function
11154      * expression, or a param tag on a variable declaration whose
11155      * initializer is the containing function. The tags closest to the
11156      * node are examined first, so in the previous example, the type
11157      * tag directly on the node would be returned.
11158      */
11159     function getJSDocType(node) {
11160         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11161         if (!tag && isParameter(node)) {
11162             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11163         }
11164         return tag && tag.typeExpression && tag.typeExpression.type;
11165     }
11166     ts.getJSDocType = getJSDocType;
11167     /**
11168      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11169      *
11170      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11171      * gets the type from inside the braces, after the fat arrow, etc.
11172      */
11173     function getJSDocReturnType(node) {
11174         var returnTag = getJSDocReturnTag(node);
11175         if (returnTag && returnTag.typeExpression) {
11176             return returnTag.typeExpression.type;
11177         }
11178         var typeTag = getJSDocTypeTag(node);
11179         if (typeTag && typeTag.typeExpression) {
11180             var type = typeTag.typeExpression.type;
11181             if (isTypeLiteralNode(type)) {
11182                 var sig = ts.find(type.members, isCallSignatureDeclaration);
11183                 return sig && sig.type;
11184             }
11185             if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
11186                 return type.type;
11187             }
11188         }
11189     }
11190     ts.getJSDocReturnType = getJSDocReturnType;
11191     /** Get all JSDoc tags related to a node, including those on parent nodes. */
11192     function getJSDocTags(node) {
11193         var tags = node.jsDocCache;
11194         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11195         if (tags === undefined) {
11196             var comments = ts.getJSDocCommentsAndTags(node);
11197             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11198             node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
11199         }
11200         return tags;
11201     }
11202     ts.getJSDocTags = getJSDocTags;
11203     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11204     function getFirstJSDocTag(node, predicate) {
11205         return ts.find(getJSDocTags(node), predicate);
11206     }
11207     /** Gets all JSDoc tags that match a specified predicate */
11208     function getAllJSDocTags(node, predicate) {
11209         return getJSDocTags(node).filter(predicate);
11210     }
11211     ts.getAllJSDocTags = getAllJSDocTags;
11212     /** Gets all JSDoc tags of a specified kind */
11213     function getAllJSDocTagsOfKind(node, kind) {
11214         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11215     }
11216     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11217     /**
11218      * Gets the effective type parameters. If the node was parsed in a
11219      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11220      */
11221     function getEffectiveTypeParameterDeclarations(node) {
11222         if (isJSDocSignature(node)) {
11223             return ts.emptyArray;
11224         }
11225         if (ts.isJSDocTypeAlias(node)) {
11226             ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
11227             return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11228         }
11229         if (node.typeParameters) {
11230             return node.typeParameters;
11231         }
11232         if (ts.isInJSFile(node)) {
11233             var decls = ts.getJSDocTypeParameterDeclarations(node);
11234             if (decls.length) {
11235                 return decls;
11236             }
11237             var typeTag = getJSDocType(node);
11238             if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11239                 return typeTag.typeParameters;
11240             }
11241         }
11242         return ts.emptyArray;
11243     }
11244     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11245     function getEffectiveConstraintOfTypeParameter(node) {
11246         return node.constraint ? node.constraint :
11247             isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11248                 undefined;
11249     }
11250     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11251     // #region
11252     // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
11253     // Literals
11254     function isNumericLiteral(node) {
11255         return node.kind === 8 /* NumericLiteral */;
11256     }
11257     ts.isNumericLiteral = isNumericLiteral;
11258     function isBigIntLiteral(node) {
11259         return node.kind === 9 /* BigIntLiteral */;
11260     }
11261     ts.isBigIntLiteral = isBigIntLiteral;
11262     function isStringLiteral(node) {
11263         return node.kind === 10 /* StringLiteral */;
11264     }
11265     ts.isStringLiteral = isStringLiteral;
11266     function isJsxText(node) {
11267         return node.kind === 11 /* JsxText */;
11268     }
11269     ts.isJsxText = isJsxText;
11270     function isRegularExpressionLiteral(node) {
11271         return node.kind === 13 /* RegularExpressionLiteral */;
11272     }
11273     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
11274     function isNoSubstitutionTemplateLiteral(node) {
11275         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
11276     }
11277     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
11278     // Pseudo-literals
11279     function isTemplateHead(node) {
11280         return node.kind === 15 /* TemplateHead */;
11281     }
11282     ts.isTemplateHead = isTemplateHead;
11283     function isTemplateMiddle(node) {
11284         return node.kind === 16 /* TemplateMiddle */;
11285     }
11286     ts.isTemplateMiddle = isTemplateMiddle;
11287     function isTemplateTail(node) {
11288         return node.kind === 17 /* TemplateTail */;
11289     }
11290     ts.isTemplateTail = isTemplateTail;
11291     function isIdentifier(node) {
11292         return node.kind === 75 /* Identifier */;
11293     }
11294     ts.isIdentifier = isIdentifier;
11295     // Names
11296     function isQualifiedName(node) {
11297         return node.kind === 153 /* QualifiedName */;
11298     }
11299     ts.isQualifiedName = isQualifiedName;
11300     function isComputedPropertyName(node) {
11301         return node.kind === 154 /* ComputedPropertyName */;
11302     }
11303     ts.isComputedPropertyName = isComputedPropertyName;
11304     function isPrivateIdentifier(node) {
11305         return node.kind === 76 /* PrivateIdentifier */;
11306     }
11307     ts.isPrivateIdentifier = isPrivateIdentifier;
11308     function isIdentifierOrPrivateIdentifier(node) {
11309         return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
11310     }
11311     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11312     // Signature elements
11313     function isTypeParameterDeclaration(node) {
11314         return node.kind === 155 /* TypeParameter */;
11315     }
11316     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
11317     function isParameter(node) {
11318         return node.kind === 156 /* Parameter */;
11319     }
11320     ts.isParameter = isParameter;
11321     function isDecorator(node) {
11322         return node.kind === 157 /* Decorator */;
11323     }
11324     ts.isDecorator = isDecorator;
11325     // TypeMember
11326     function isPropertySignature(node) {
11327         return node.kind === 158 /* PropertySignature */;
11328     }
11329     ts.isPropertySignature = isPropertySignature;
11330     function isPropertyDeclaration(node) {
11331         return node.kind === 159 /* PropertyDeclaration */;
11332     }
11333     ts.isPropertyDeclaration = isPropertyDeclaration;
11334     function isMethodSignature(node) {
11335         return node.kind === 160 /* MethodSignature */;
11336     }
11337     ts.isMethodSignature = isMethodSignature;
11338     function isMethodDeclaration(node) {
11339         return node.kind === 161 /* MethodDeclaration */;
11340     }
11341     ts.isMethodDeclaration = isMethodDeclaration;
11342     function isConstructorDeclaration(node) {
11343         return node.kind === 162 /* Constructor */;
11344     }
11345     ts.isConstructorDeclaration = isConstructorDeclaration;
11346     function isGetAccessorDeclaration(node) {
11347         return node.kind === 163 /* GetAccessor */;
11348     }
11349     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
11350     function isSetAccessorDeclaration(node) {
11351         return node.kind === 164 /* SetAccessor */;
11352     }
11353     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
11354     function isCallSignatureDeclaration(node) {
11355         return node.kind === 165 /* CallSignature */;
11356     }
11357     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
11358     function isConstructSignatureDeclaration(node) {
11359         return node.kind === 166 /* ConstructSignature */;
11360     }
11361     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
11362     function isIndexSignatureDeclaration(node) {
11363         return node.kind === 167 /* IndexSignature */;
11364     }
11365     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
11366     /* @internal */
11367     function isGetOrSetAccessorDeclaration(node) {
11368         return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
11369     }
11370     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11371     // Type
11372     function isTypePredicateNode(node) {
11373         return node.kind === 168 /* TypePredicate */;
11374     }
11375     ts.isTypePredicateNode = isTypePredicateNode;
11376     function isTypeReferenceNode(node) {
11377         return node.kind === 169 /* TypeReference */;
11378     }
11379     ts.isTypeReferenceNode = isTypeReferenceNode;
11380     function isFunctionTypeNode(node) {
11381         return node.kind === 170 /* FunctionType */;
11382     }
11383     ts.isFunctionTypeNode = isFunctionTypeNode;
11384     function isConstructorTypeNode(node) {
11385         return node.kind === 171 /* ConstructorType */;
11386     }
11387     ts.isConstructorTypeNode = isConstructorTypeNode;
11388     function isTypeQueryNode(node) {
11389         return node.kind === 172 /* TypeQuery */;
11390     }
11391     ts.isTypeQueryNode = isTypeQueryNode;
11392     function isTypeLiteralNode(node) {
11393         return node.kind === 173 /* TypeLiteral */;
11394     }
11395     ts.isTypeLiteralNode = isTypeLiteralNode;
11396     function isArrayTypeNode(node) {
11397         return node.kind === 174 /* ArrayType */;
11398     }
11399     ts.isArrayTypeNode = isArrayTypeNode;
11400     function isTupleTypeNode(node) {
11401         return node.kind === 175 /* TupleType */;
11402     }
11403     ts.isTupleTypeNode = isTupleTypeNode;
11404     function isUnionTypeNode(node) {
11405         return node.kind === 178 /* UnionType */;
11406     }
11407     ts.isUnionTypeNode = isUnionTypeNode;
11408     function isIntersectionTypeNode(node) {
11409         return node.kind === 179 /* IntersectionType */;
11410     }
11411     ts.isIntersectionTypeNode = isIntersectionTypeNode;
11412     function isConditionalTypeNode(node) {
11413         return node.kind === 180 /* ConditionalType */;
11414     }
11415     ts.isConditionalTypeNode = isConditionalTypeNode;
11416     function isInferTypeNode(node) {
11417         return node.kind === 181 /* InferType */;
11418     }
11419     ts.isInferTypeNode = isInferTypeNode;
11420     function isParenthesizedTypeNode(node) {
11421         return node.kind === 182 /* ParenthesizedType */;
11422     }
11423     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
11424     function isThisTypeNode(node) {
11425         return node.kind === 183 /* ThisType */;
11426     }
11427     ts.isThisTypeNode = isThisTypeNode;
11428     function isTypeOperatorNode(node) {
11429         return node.kind === 184 /* TypeOperator */;
11430     }
11431     ts.isTypeOperatorNode = isTypeOperatorNode;
11432     function isIndexedAccessTypeNode(node) {
11433         return node.kind === 185 /* IndexedAccessType */;
11434     }
11435     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
11436     function isMappedTypeNode(node) {
11437         return node.kind === 186 /* MappedType */;
11438     }
11439     ts.isMappedTypeNode = isMappedTypeNode;
11440     function isLiteralTypeNode(node) {
11441         return node.kind === 187 /* LiteralType */;
11442     }
11443     ts.isLiteralTypeNode = isLiteralTypeNode;
11444     function isImportTypeNode(node) {
11445         return node.kind === 188 /* ImportType */;
11446     }
11447     ts.isImportTypeNode = isImportTypeNode;
11448     // Binding patterns
11449     function isObjectBindingPattern(node) {
11450         return node.kind === 189 /* ObjectBindingPattern */;
11451     }
11452     ts.isObjectBindingPattern = isObjectBindingPattern;
11453     function isArrayBindingPattern(node) {
11454         return node.kind === 190 /* ArrayBindingPattern */;
11455     }
11456     ts.isArrayBindingPattern = isArrayBindingPattern;
11457     function isBindingElement(node) {
11458         return node.kind === 191 /* BindingElement */;
11459     }
11460     ts.isBindingElement = isBindingElement;
11461     // Expression
11462     function isArrayLiteralExpression(node) {
11463         return node.kind === 192 /* ArrayLiteralExpression */;
11464     }
11465     ts.isArrayLiteralExpression = isArrayLiteralExpression;
11466     function isObjectLiteralExpression(node) {
11467         return node.kind === 193 /* ObjectLiteralExpression */;
11468     }
11469     ts.isObjectLiteralExpression = isObjectLiteralExpression;
11470     function isPropertyAccessExpression(node) {
11471         return node.kind === 194 /* PropertyAccessExpression */;
11472     }
11473     ts.isPropertyAccessExpression = isPropertyAccessExpression;
11474     function isPropertyAccessChain(node) {
11475         return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11476     }
11477     ts.isPropertyAccessChain = isPropertyAccessChain;
11478     function isElementAccessExpression(node) {
11479         return node.kind === 195 /* ElementAccessExpression */;
11480     }
11481     ts.isElementAccessExpression = isElementAccessExpression;
11482     function isElementAccessChain(node) {
11483         return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11484     }
11485     ts.isElementAccessChain = isElementAccessChain;
11486     function isCallExpression(node) {
11487         return node.kind === 196 /* CallExpression */;
11488     }
11489     ts.isCallExpression = isCallExpression;
11490     function isCallChain(node) {
11491         return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11492     }
11493     ts.isCallChain = isCallChain;
11494     function isOptionalChain(node) {
11495         var kind = node.kind;
11496         return !!(node.flags & 32 /* OptionalChain */) &&
11497             (kind === 194 /* PropertyAccessExpression */
11498                 || kind === 195 /* ElementAccessExpression */
11499                 || kind === 196 /* CallExpression */
11500                 || kind === 218 /* NonNullExpression */);
11501     }
11502     ts.isOptionalChain = isOptionalChain;
11503     /* @internal */
11504     function isOptionalChainRoot(node) {
11505         return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
11506     }
11507     ts.isOptionalChainRoot = isOptionalChainRoot;
11508     /**
11509      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11510      */
11511     /* @internal */
11512     function isExpressionOfOptionalChainRoot(node) {
11513         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11514     }
11515     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11516     /**
11517      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11518      *
11519      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11520      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11521      * 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)
11522      * 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
11523      *   the end of the chain starting at `c?.`)
11524      * 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
11525      *   the end of the chain starting at `a?.`)
11526      */
11527     /* @internal */
11528     function isOutermostOptionalChain(node) {
11529         return !isOptionalChain(node.parent) // cases 1, 2, and 3
11530             || isOptionalChainRoot(node.parent) // case 4
11531             || node !== node.parent.expression; // case 5
11532     }
11533     ts.isOutermostOptionalChain = isOutermostOptionalChain;
11534     function isNullishCoalesce(node) {
11535         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11536     }
11537     ts.isNullishCoalesce = isNullishCoalesce;
11538     function isNewExpression(node) {
11539         return node.kind === 197 /* NewExpression */;
11540     }
11541     ts.isNewExpression = isNewExpression;
11542     function isTaggedTemplateExpression(node) {
11543         return node.kind === 198 /* TaggedTemplateExpression */;
11544     }
11545     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
11546     function isTypeAssertion(node) {
11547         return node.kind === 199 /* TypeAssertionExpression */;
11548     }
11549     ts.isTypeAssertion = isTypeAssertion;
11550     function isConstTypeReference(node) {
11551         return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
11552             node.typeName.escapedText === "const" && !node.typeArguments;
11553     }
11554     ts.isConstTypeReference = isConstTypeReference;
11555     function isParenthesizedExpression(node) {
11556         return node.kind === 200 /* ParenthesizedExpression */;
11557     }
11558     ts.isParenthesizedExpression = isParenthesizedExpression;
11559     function skipPartiallyEmittedExpressions(node) {
11560         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11561     }
11562     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11563     function isFunctionExpression(node) {
11564         return node.kind === 201 /* FunctionExpression */;
11565     }
11566     ts.isFunctionExpression = isFunctionExpression;
11567     function isArrowFunction(node) {
11568         return node.kind === 202 /* ArrowFunction */;
11569     }
11570     ts.isArrowFunction = isArrowFunction;
11571     function isDeleteExpression(node) {
11572         return node.kind === 203 /* DeleteExpression */;
11573     }
11574     ts.isDeleteExpression = isDeleteExpression;
11575     function isTypeOfExpression(node) {
11576         return node.kind === 204 /* TypeOfExpression */;
11577     }
11578     ts.isTypeOfExpression = isTypeOfExpression;
11579     function isVoidExpression(node) {
11580         return node.kind === 205 /* VoidExpression */;
11581     }
11582     ts.isVoidExpression = isVoidExpression;
11583     function isAwaitExpression(node) {
11584         return node.kind === 206 /* AwaitExpression */;
11585     }
11586     ts.isAwaitExpression = isAwaitExpression;
11587     function isPrefixUnaryExpression(node) {
11588         return node.kind === 207 /* PrefixUnaryExpression */;
11589     }
11590     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
11591     function isPostfixUnaryExpression(node) {
11592         return node.kind === 208 /* PostfixUnaryExpression */;
11593     }
11594     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
11595     function isBinaryExpression(node) {
11596         return node.kind === 209 /* BinaryExpression */;
11597     }
11598     ts.isBinaryExpression = isBinaryExpression;
11599     function isConditionalExpression(node) {
11600         return node.kind === 210 /* ConditionalExpression */;
11601     }
11602     ts.isConditionalExpression = isConditionalExpression;
11603     function isTemplateExpression(node) {
11604         return node.kind === 211 /* TemplateExpression */;
11605     }
11606     ts.isTemplateExpression = isTemplateExpression;
11607     function isYieldExpression(node) {
11608         return node.kind === 212 /* YieldExpression */;
11609     }
11610     ts.isYieldExpression = isYieldExpression;
11611     function isSpreadElement(node) {
11612         return node.kind === 213 /* SpreadElement */;
11613     }
11614     ts.isSpreadElement = isSpreadElement;
11615     function isClassExpression(node) {
11616         return node.kind === 214 /* ClassExpression */;
11617     }
11618     ts.isClassExpression = isClassExpression;
11619     function isOmittedExpression(node) {
11620         return node.kind === 215 /* OmittedExpression */;
11621     }
11622     ts.isOmittedExpression = isOmittedExpression;
11623     function isExpressionWithTypeArguments(node) {
11624         return node.kind === 216 /* ExpressionWithTypeArguments */;
11625     }
11626     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
11627     function isAsExpression(node) {
11628         return node.kind === 217 /* AsExpression */;
11629     }
11630     ts.isAsExpression = isAsExpression;
11631     function isNonNullExpression(node) {
11632         return node.kind === 218 /* NonNullExpression */;
11633     }
11634     ts.isNonNullExpression = isNonNullExpression;
11635     function isNonNullChain(node) {
11636         return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11637     }
11638     ts.isNonNullChain = isNonNullChain;
11639     function isMetaProperty(node) {
11640         return node.kind === 219 /* MetaProperty */;
11641     }
11642     ts.isMetaProperty = isMetaProperty;
11643     // Misc
11644     function isTemplateSpan(node) {
11645         return node.kind === 221 /* TemplateSpan */;
11646     }
11647     ts.isTemplateSpan = isTemplateSpan;
11648     function isSemicolonClassElement(node) {
11649         return node.kind === 222 /* SemicolonClassElement */;
11650     }
11651     ts.isSemicolonClassElement = isSemicolonClassElement;
11652     // Block
11653     function isBlock(node) {
11654         return node.kind === 223 /* Block */;
11655     }
11656     ts.isBlock = isBlock;
11657     function isVariableStatement(node) {
11658         return node.kind === 225 /* VariableStatement */;
11659     }
11660     ts.isVariableStatement = isVariableStatement;
11661     function isEmptyStatement(node) {
11662         return node.kind === 224 /* EmptyStatement */;
11663     }
11664     ts.isEmptyStatement = isEmptyStatement;
11665     function isExpressionStatement(node) {
11666         return node.kind === 226 /* ExpressionStatement */;
11667     }
11668     ts.isExpressionStatement = isExpressionStatement;
11669     function isIfStatement(node) {
11670         return node.kind === 227 /* IfStatement */;
11671     }
11672     ts.isIfStatement = isIfStatement;
11673     function isDoStatement(node) {
11674         return node.kind === 228 /* DoStatement */;
11675     }
11676     ts.isDoStatement = isDoStatement;
11677     function isWhileStatement(node) {
11678         return node.kind === 229 /* WhileStatement */;
11679     }
11680     ts.isWhileStatement = isWhileStatement;
11681     function isForStatement(node) {
11682         return node.kind === 230 /* ForStatement */;
11683     }
11684     ts.isForStatement = isForStatement;
11685     function isForInStatement(node) {
11686         return node.kind === 231 /* ForInStatement */;
11687     }
11688     ts.isForInStatement = isForInStatement;
11689     function isForOfStatement(node) {
11690         return node.kind === 232 /* ForOfStatement */;
11691     }
11692     ts.isForOfStatement = isForOfStatement;
11693     function isContinueStatement(node) {
11694         return node.kind === 233 /* ContinueStatement */;
11695     }
11696     ts.isContinueStatement = isContinueStatement;
11697     function isBreakStatement(node) {
11698         return node.kind === 234 /* BreakStatement */;
11699     }
11700     ts.isBreakStatement = isBreakStatement;
11701     function isBreakOrContinueStatement(node) {
11702         return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
11703     }
11704     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11705     function isReturnStatement(node) {
11706         return node.kind === 235 /* ReturnStatement */;
11707     }
11708     ts.isReturnStatement = isReturnStatement;
11709     function isWithStatement(node) {
11710         return node.kind === 236 /* WithStatement */;
11711     }
11712     ts.isWithStatement = isWithStatement;
11713     function isSwitchStatement(node) {
11714         return node.kind === 237 /* SwitchStatement */;
11715     }
11716     ts.isSwitchStatement = isSwitchStatement;
11717     function isLabeledStatement(node) {
11718         return node.kind === 238 /* LabeledStatement */;
11719     }
11720     ts.isLabeledStatement = isLabeledStatement;
11721     function isThrowStatement(node) {
11722         return node.kind === 239 /* ThrowStatement */;
11723     }
11724     ts.isThrowStatement = isThrowStatement;
11725     function isTryStatement(node) {
11726         return node.kind === 240 /* TryStatement */;
11727     }
11728     ts.isTryStatement = isTryStatement;
11729     function isDebuggerStatement(node) {
11730         return node.kind === 241 /* DebuggerStatement */;
11731     }
11732     ts.isDebuggerStatement = isDebuggerStatement;
11733     function isVariableDeclaration(node) {
11734         return node.kind === 242 /* VariableDeclaration */;
11735     }
11736     ts.isVariableDeclaration = isVariableDeclaration;
11737     function isVariableDeclarationList(node) {
11738         return node.kind === 243 /* VariableDeclarationList */;
11739     }
11740     ts.isVariableDeclarationList = isVariableDeclarationList;
11741     function isFunctionDeclaration(node) {
11742         return node.kind === 244 /* FunctionDeclaration */;
11743     }
11744     ts.isFunctionDeclaration = isFunctionDeclaration;
11745     function isClassDeclaration(node) {
11746         return node.kind === 245 /* ClassDeclaration */;
11747     }
11748     ts.isClassDeclaration = isClassDeclaration;
11749     function isInterfaceDeclaration(node) {
11750         return node.kind === 246 /* InterfaceDeclaration */;
11751     }
11752     ts.isInterfaceDeclaration = isInterfaceDeclaration;
11753     function isTypeAliasDeclaration(node) {
11754         return node.kind === 247 /* TypeAliasDeclaration */;
11755     }
11756     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
11757     function isEnumDeclaration(node) {
11758         return node.kind === 248 /* EnumDeclaration */;
11759     }
11760     ts.isEnumDeclaration = isEnumDeclaration;
11761     function isModuleDeclaration(node) {
11762         return node.kind === 249 /* ModuleDeclaration */;
11763     }
11764     ts.isModuleDeclaration = isModuleDeclaration;
11765     function isModuleBlock(node) {
11766         return node.kind === 250 /* ModuleBlock */;
11767     }
11768     ts.isModuleBlock = isModuleBlock;
11769     function isCaseBlock(node) {
11770         return node.kind === 251 /* CaseBlock */;
11771     }
11772     ts.isCaseBlock = isCaseBlock;
11773     function isNamespaceExportDeclaration(node) {
11774         return node.kind === 252 /* NamespaceExportDeclaration */;
11775     }
11776     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
11777     function isImportEqualsDeclaration(node) {
11778         return node.kind === 253 /* ImportEqualsDeclaration */;
11779     }
11780     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
11781     function isImportDeclaration(node) {
11782         return node.kind === 254 /* ImportDeclaration */;
11783     }
11784     ts.isImportDeclaration = isImportDeclaration;
11785     function isImportClause(node) {
11786         return node.kind === 255 /* ImportClause */;
11787     }
11788     ts.isImportClause = isImportClause;
11789     function isNamespaceImport(node) {
11790         return node.kind === 256 /* NamespaceImport */;
11791     }
11792     ts.isNamespaceImport = isNamespaceImport;
11793     function isNamespaceExport(node) {
11794         return node.kind === 262 /* NamespaceExport */;
11795     }
11796     ts.isNamespaceExport = isNamespaceExport;
11797     function isNamedExportBindings(node) {
11798         return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
11799     }
11800     ts.isNamedExportBindings = isNamedExportBindings;
11801     function isNamedImports(node) {
11802         return node.kind === 257 /* NamedImports */;
11803     }
11804     ts.isNamedImports = isNamedImports;
11805     function isImportSpecifier(node) {
11806         return node.kind === 258 /* ImportSpecifier */;
11807     }
11808     ts.isImportSpecifier = isImportSpecifier;
11809     function isExportAssignment(node) {
11810         return node.kind === 259 /* ExportAssignment */;
11811     }
11812     ts.isExportAssignment = isExportAssignment;
11813     function isExportDeclaration(node) {
11814         return node.kind === 260 /* ExportDeclaration */;
11815     }
11816     ts.isExportDeclaration = isExportDeclaration;
11817     function isNamedExports(node) {
11818         return node.kind === 261 /* NamedExports */;
11819     }
11820     ts.isNamedExports = isNamedExports;
11821     function isExportSpecifier(node) {
11822         return node.kind === 263 /* ExportSpecifier */;
11823     }
11824     ts.isExportSpecifier = isExportSpecifier;
11825     function isMissingDeclaration(node) {
11826         return node.kind === 264 /* MissingDeclaration */;
11827     }
11828     ts.isMissingDeclaration = isMissingDeclaration;
11829     // Module References
11830     function isExternalModuleReference(node) {
11831         return node.kind === 265 /* ExternalModuleReference */;
11832     }
11833     ts.isExternalModuleReference = isExternalModuleReference;
11834     // JSX
11835     function isJsxElement(node) {
11836         return node.kind === 266 /* JsxElement */;
11837     }
11838     ts.isJsxElement = isJsxElement;
11839     function isJsxSelfClosingElement(node) {
11840         return node.kind === 267 /* JsxSelfClosingElement */;
11841     }
11842     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
11843     function isJsxOpeningElement(node) {
11844         return node.kind === 268 /* JsxOpeningElement */;
11845     }
11846     ts.isJsxOpeningElement = isJsxOpeningElement;
11847     function isJsxClosingElement(node) {
11848         return node.kind === 269 /* JsxClosingElement */;
11849     }
11850     ts.isJsxClosingElement = isJsxClosingElement;
11851     function isJsxFragment(node) {
11852         return node.kind === 270 /* JsxFragment */;
11853     }
11854     ts.isJsxFragment = isJsxFragment;
11855     function isJsxOpeningFragment(node) {
11856         return node.kind === 271 /* JsxOpeningFragment */;
11857     }
11858     ts.isJsxOpeningFragment = isJsxOpeningFragment;
11859     function isJsxClosingFragment(node) {
11860         return node.kind === 272 /* JsxClosingFragment */;
11861     }
11862     ts.isJsxClosingFragment = isJsxClosingFragment;
11863     function isJsxAttribute(node) {
11864         return node.kind === 273 /* JsxAttribute */;
11865     }
11866     ts.isJsxAttribute = isJsxAttribute;
11867     function isJsxAttributes(node) {
11868         return node.kind === 274 /* JsxAttributes */;
11869     }
11870     ts.isJsxAttributes = isJsxAttributes;
11871     function isJsxSpreadAttribute(node) {
11872         return node.kind === 275 /* JsxSpreadAttribute */;
11873     }
11874     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
11875     function isJsxExpression(node) {
11876         return node.kind === 276 /* JsxExpression */;
11877     }
11878     ts.isJsxExpression = isJsxExpression;
11879     // Clauses
11880     function isCaseClause(node) {
11881         return node.kind === 277 /* CaseClause */;
11882     }
11883     ts.isCaseClause = isCaseClause;
11884     function isDefaultClause(node) {
11885         return node.kind === 278 /* DefaultClause */;
11886     }
11887     ts.isDefaultClause = isDefaultClause;
11888     function isHeritageClause(node) {
11889         return node.kind === 279 /* HeritageClause */;
11890     }
11891     ts.isHeritageClause = isHeritageClause;
11892     function isCatchClause(node) {
11893         return node.kind === 280 /* CatchClause */;
11894     }
11895     ts.isCatchClause = isCatchClause;
11896     // Property assignments
11897     function isPropertyAssignment(node) {
11898         return node.kind === 281 /* PropertyAssignment */;
11899     }
11900     ts.isPropertyAssignment = isPropertyAssignment;
11901     function isShorthandPropertyAssignment(node) {
11902         return node.kind === 282 /* ShorthandPropertyAssignment */;
11903     }
11904     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
11905     function isSpreadAssignment(node) {
11906         return node.kind === 283 /* SpreadAssignment */;
11907     }
11908     ts.isSpreadAssignment = isSpreadAssignment;
11909     // Enum
11910     function isEnumMember(node) {
11911         return node.kind === 284 /* EnumMember */;
11912     }
11913     ts.isEnumMember = isEnumMember;
11914     // Top-level nodes
11915     function isSourceFile(node) {
11916         return node.kind === 290 /* SourceFile */;
11917     }
11918     ts.isSourceFile = isSourceFile;
11919     function isBundle(node) {
11920         return node.kind === 291 /* Bundle */;
11921     }
11922     ts.isBundle = isBundle;
11923     function isUnparsedSource(node) {
11924         return node.kind === 292 /* UnparsedSource */;
11925     }
11926     ts.isUnparsedSource = isUnparsedSource;
11927     function isUnparsedPrepend(node) {
11928         return node.kind === 286 /* UnparsedPrepend */;
11929     }
11930     ts.isUnparsedPrepend = isUnparsedPrepend;
11931     function isUnparsedTextLike(node) {
11932         switch (node.kind) {
11933             case 287 /* UnparsedText */:
11934             case 288 /* UnparsedInternalText */:
11935                 return true;
11936             default:
11937                 return false;
11938         }
11939     }
11940     ts.isUnparsedTextLike = isUnparsedTextLike;
11941     function isUnparsedNode(node) {
11942         return isUnparsedTextLike(node) ||
11943             node.kind === 285 /* UnparsedPrologue */ ||
11944             node.kind === 289 /* UnparsedSyntheticReference */;
11945     }
11946     ts.isUnparsedNode = isUnparsedNode;
11947     // JSDoc
11948     function isJSDocTypeExpression(node) {
11949         return node.kind === 294 /* JSDocTypeExpression */;
11950     }
11951     ts.isJSDocTypeExpression = isJSDocTypeExpression;
11952     function isJSDocAllType(node) {
11953         return node.kind === 295 /* JSDocAllType */;
11954     }
11955     ts.isJSDocAllType = isJSDocAllType;
11956     function isJSDocUnknownType(node) {
11957         return node.kind === 296 /* JSDocUnknownType */;
11958     }
11959     ts.isJSDocUnknownType = isJSDocUnknownType;
11960     function isJSDocNullableType(node) {
11961         return node.kind === 297 /* JSDocNullableType */;
11962     }
11963     ts.isJSDocNullableType = isJSDocNullableType;
11964     function isJSDocNonNullableType(node) {
11965         return node.kind === 298 /* JSDocNonNullableType */;
11966     }
11967     ts.isJSDocNonNullableType = isJSDocNonNullableType;
11968     function isJSDocOptionalType(node) {
11969         return node.kind === 299 /* JSDocOptionalType */;
11970     }
11971     ts.isJSDocOptionalType = isJSDocOptionalType;
11972     function isJSDocFunctionType(node) {
11973         return node.kind === 300 /* JSDocFunctionType */;
11974     }
11975     ts.isJSDocFunctionType = isJSDocFunctionType;
11976     function isJSDocVariadicType(node) {
11977         return node.kind === 301 /* JSDocVariadicType */;
11978     }
11979     ts.isJSDocVariadicType = isJSDocVariadicType;
11980     function isJSDoc(node) {
11981         return node.kind === 303 /* JSDocComment */;
11982     }
11983     ts.isJSDoc = isJSDoc;
11984     function isJSDocAuthorTag(node) {
11985         return node.kind === 309 /* JSDocAuthorTag */;
11986     }
11987     ts.isJSDocAuthorTag = isJSDocAuthorTag;
11988     function isJSDocAugmentsTag(node) {
11989         return node.kind === 307 /* JSDocAugmentsTag */;
11990     }
11991     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
11992     function isJSDocImplementsTag(node) {
11993         return node.kind === 308 /* JSDocImplementsTag */;
11994     }
11995     ts.isJSDocImplementsTag = isJSDocImplementsTag;
11996     function isJSDocClassTag(node) {
11997         return node.kind === 310 /* JSDocClassTag */;
11998     }
11999     ts.isJSDocClassTag = isJSDocClassTag;
12000     function isJSDocPublicTag(node) {
12001         return node.kind === 311 /* JSDocPublicTag */;
12002     }
12003     ts.isJSDocPublicTag = isJSDocPublicTag;
12004     function isJSDocPrivateTag(node) {
12005         return node.kind === 312 /* JSDocPrivateTag */;
12006     }
12007     ts.isJSDocPrivateTag = isJSDocPrivateTag;
12008     function isJSDocProtectedTag(node) {
12009         return node.kind === 313 /* JSDocProtectedTag */;
12010     }
12011     ts.isJSDocProtectedTag = isJSDocProtectedTag;
12012     function isJSDocReadonlyTag(node) {
12013         return node.kind === 314 /* JSDocReadonlyTag */;
12014     }
12015     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
12016     function isJSDocEnumTag(node) {
12017         return node.kind === 316 /* JSDocEnumTag */;
12018     }
12019     ts.isJSDocEnumTag = isJSDocEnumTag;
12020     function isJSDocThisTag(node) {
12021         return node.kind === 319 /* JSDocThisTag */;
12022     }
12023     ts.isJSDocThisTag = isJSDocThisTag;
12024     function isJSDocParameterTag(node) {
12025         return node.kind === 317 /* JSDocParameterTag */;
12026     }
12027     ts.isJSDocParameterTag = isJSDocParameterTag;
12028     function isJSDocReturnTag(node) {
12029         return node.kind === 318 /* JSDocReturnTag */;
12030     }
12031     ts.isJSDocReturnTag = isJSDocReturnTag;
12032     function isJSDocTypeTag(node) {
12033         return node.kind === 320 /* JSDocTypeTag */;
12034     }
12035     ts.isJSDocTypeTag = isJSDocTypeTag;
12036     function isJSDocTemplateTag(node) {
12037         return node.kind === 321 /* JSDocTemplateTag */;
12038     }
12039     ts.isJSDocTemplateTag = isJSDocTemplateTag;
12040     function isJSDocTypedefTag(node) {
12041         return node.kind === 322 /* JSDocTypedefTag */;
12042     }
12043     ts.isJSDocTypedefTag = isJSDocTypedefTag;
12044     function isJSDocPropertyTag(node) {
12045         return node.kind === 323 /* JSDocPropertyTag */;
12046     }
12047     ts.isJSDocPropertyTag = isJSDocPropertyTag;
12048     function isJSDocPropertyLikeTag(node) {
12049         return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
12050     }
12051     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
12052     function isJSDocTypeLiteral(node) {
12053         return node.kind === 304 /* JSDocTypeLiteral */;
12054     }
12055     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
12056     function isJSDocCallbackTag(node) {
12057         return node.kind === 315 /* JSDocCallbackTag */;
12058     }
12059     ts.isJSDocCallbackTag = isJSDocCallbackTag;
12060     function isJSDocSignature(node) {
12061         return node.kind === 305 /* JSDocSignature */;
12062     }
12063     ts.isJSDocSignature = isJSDocSignature;
12064     // #endregion
12065     // #region
12066     // Node tests
12067     //
12068     // All node tests in the following list should *not* reference parent pointers so that
12069     // they may be used with transformations.
12070     /* @internal */
12071     function isSyntaxList(n) {
12072         return n.kind === 324 /* SyntaxList */;
12073     }
12074     ts.isSyntaxList = isSyntaxList;
12075     /* @internal */
12076     function isNode(node) {
12077         return isNodeKind(node.kind);
12078     }
12079     ts.isNode = isNode;
12080     /* @internal */
12081     function isNodeKind(kind) {
12082         return kind >= 153 /* FirstNode */;
12083     }
12084     ts.isNodeKind = isNodeKind;
12085     /**
12086      * True if node is of some token syntax kind.
12087      * For example, this is true for an IfKeyword but not for an IfStatement.
12088      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
12089      */
12090     function isToken(n) {
12091         return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
12092     }
12093     ts.isToken = isToken;
12094     // Node Arrays
12095     /* @internal */
12096     function isNodeArray(array) {
12097         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
12098     }
12099     ts.isNodeArray = isNodeArray;
12100     // Literals
12101     /* @internal */
12102     function isLiteralKind(kind) {
12103         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
12104     }
12105     ts.isLiteralKind = isLiteralKind;
12106     function isLiteralExpression(node) {
12107         return isLiteralKind(node.kind);
12108     }
12109     ts.isLiteralExpression = isLiteralExpression;
12110     // Pseudo-literals
12111     /* @internal */
12112     function isTemplateLiteralKind(kind) {
12113         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
12114     }
12115     ts.isTemplateLiteralKind = isTemplateLiteralKind;
12116     function isTemplateLiteralToken(node) {
12117         return isTemplateLiteralKind(node.kind);
12118     }
12119     ts.isTemplateLiteralToken = isTemplateLiteralToken;
12120     function isTemplateMiddleOrTemplateTail(node) {
12121         var kind = node.kind;
12122         return kind === 16 /* TemplateMiddle */
12123             || kind === 17 /* TemplateTail */;
12124     }
12125     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
12126     function isImportOrExportSpecifier(node) {
12127         return isImportSpecifier(node) || isExportSpecifier(node);
12128     }
12129     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
12130     function isTypeOnlyImportOrExportDeclaration(node) {
12131         switch (node.kind) {
12132             case 258 /* ImportSpecifier */:
12133             case 263 /* ExportSpecifier */:
12134                 return node.parent.parent.isTypeOnly;
12135             case 256 /* NamespaceImport */:
12136                 return node.parent.isTypeOnly;
12137             case 255 /* ImportClause */:
12138                 return node.isTypeOnly;
12139             default:
12140                 return false;
12141         }
12142     }
12143     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
12144     function isStringTextContainingNode(node) {
12145         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
12146     }
12147     ts.isStringTextContainingNode = isStringTextContainingNode;
12148     // Identifiers
12149     /* @internal */
12150     function isGeneratedIdentifier(node) {
12151         return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
12152     }
12153     ts.isGeneratedIdentifier = isGeneratedIdentifier;
12154     // Private Identifiers
12155     /*@internal*/
12156     function isPrivateIdentifierPropertyDeclaration(node) {
12157         return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
12158     }
12159     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12160     /*@internal*/
12161     function isPrivateIdentifierPropertyAccessExpression(node) {
12162         return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
12163     }
12164     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12165     // Keywords
12166     /* @internal */
12167     function isModifierKind(token) {
12168         switch (token) {
12169             case 122 /* AbstractKeyword */:
12170             case 126 /* AsyncKeyword */:
12171             case 81 /* ConstKeyword */:
12172             case 130 /* DeclareKeyword */:
12173             case 84 /* DefaultKeyword */:
12174             case 89 /* ExportKeyword */:
12175             case 119 /* PublicKeyword */:
12176             case 117 /* PrivateKeyword */:
12177             case 118 /* ProtectedKeyword */:
12178             case 138 /* ReadonlyKeyword */:
12179             case 120 /* StaticKeyword */:
12180                 return true;
12181         }
12182         return false;
12183     }
12184     ts.isModifierKind = isModifierKind;
12185     /* @internal */
12186     function isParameterPropertyModifier(kind) {
12187         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12188     }
12189     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12190     /* @internal */
12191     function isClassMemberModifier(idToken) {
12192         return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
12193     }
12194     ts.isClassMemberModifier = isClassMemberModifier;
12195     function isModifier(node) {
12196         return isModifierKind(node.kind);
12197     }
12198     ts.isModifier = isModifier;
12199     function isEntityName(node) {
12200         var kind = node.kind;
12201         return kind === 153 /* QualifiedName */
12202             || kind === 75 /* Identifier */;
12203     }
12204     ts.isEntityName = isEntityName;
12205     function isPropertyName(node) {
12206         var kind = node.kind;
12207         return kind === 75 /* Identifier */
12208             || kind === 76 /* PrivateIdentifier */
12209             || kind === 10 /* StringLiteral */
12210             || kind === 8 /* NumericLiteral */
12211             || kind === 154 /* ComputedPropertyName */;
12212     }
12213     ts.isPropertyName = isPropertyName;
12214     function isBindingName(node) {
12215         var kind = node.kind;
12216         return kind === 75 /* Identifier */
12217             || kind === 189 /* ObjectBindingPattern */
12218             || kind === 190 /* ArrayBindingPattern */;
12219     }
12220     ts.isBindingName = isBindingName;
12221     // Functions
12222     function isFunctionLike(node) {
12223         return node && isFunctionLikeKind(node.kind);
12224     }
12225     ts.isFunctionLike = isFunctionLike;
12226     /* @internal */
12227     function isFunctionLikeDeclaration(node) {
12228         return node && isFunctionLikeDeclarationKind(node.kind);
12229     }
12230     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12231     function isFunctionLikeDeclarationKind(kind) {
12232         switch (kind) {
12233             case 244 /* FunctionDeclaration */:
12234             case 161 /* MethodDeclaration */:
12235             case 162 /* Constructor */:
12236             case 163 /* GetAccessor */:
12237             case 164 /* SetAccessor */:
12238             case 201 /* FunctionExpression */:
12239             case 202 /* ArrowFunction */:
12240                 return true;
12241             default:
12242                 return false;
12243         }
12244     }
12245     /* @internal */
12246     function isFunctionLikeKind(kind) {
12247         switch (kind) {
12248             case 160 /* MethodSignature */:
12249             case 165 /* CallSignature */:
12250             case 305 /* JSDocSignature */:
12251             case 166 /* ConstructSignature */:
12252             case 167 /* IndexSignature */:
12253             case 170 /* FunctionType */:
12254             case 300 /* JSDocFunctionType */:
12255             case 171 /* ConstructorType */:
12256                 return true;
12257             default:
12258                 return isFunctionLikeDeclarationKind(kind);
12259         }
12260     }
12261     ts.isFunctionLikeKind = isFunctionLikeKind;
12262     /* @internal */
12263     function isFunctionOrModuleBlock(node) {
12264         return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
12265     }
12266     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12267     // Classes
12268     function isClassElement(node) {
12269         var kind = node.kind;
12270         return kind === 162 /* Constructor */
12271             || kind === 159 /* PropertyDeclaration */
12272             || kind === 161 /* MethodDeclaration */
12273             || kind === 163 /* GetAccessor */
12274             || kind === 164 /* SetAccessor */
12275             || kind === 167 /* IndexSignature */
12276             || kind === 222 /* SemicolonClassElement */;
12277     }
12278     ts.isClassElement = isClassElement;
12279     function isClassLike(node) {
12280         return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
12281     }
12282     ts.isClassLike = isClassLike;
12283     function isAccessor(node) {
12284         return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
12285     }
12286     ts.isAccessor = isAccessor;
12287     /* @internal */
12288     function isMethodOrAccessor(node) {
12289         switch (node.kind) {
12290             case 161 /* MethodDeclaration */:
12291             case 163 /* GetAccessor */:
12292             case 164 /* SetAccessor */:
12293                 return true;
12294             default:
12295                 return false;
12296         }
12297     }
12298     ts.isMethodOrAccessor = isMethodOrAccessor;
12299     // Type members
12300     function isTypeElement(node) {
12301         var kind = node.kind;
12302         return kind === 166 /* ConstructSignature */
12303             || kind === 165 /* CallSignature */
12304             || kind === 158 /* PropertySignature */
12305             || kind === 160 /* MethodSignature */
12306             || kind === 167 /* IndexSignature */;
12307     }
12308     ts.isTypeElement = isTypeElement;
12309     function isClassOrTypeElement(node) {
12310         return isTypeElement(node) || isClassElement(node);
12311     }
12312     ts.isClassOrTypeElement = isClassOrTypeElement;
12313     function isObjectLiteralElementLike(node) {
12314         var kind = node.kind;
12315         return kind === 281 /* PropertyAssignment */
12316             || kind === 282 /* ShorthandPropertyAssignment */
12317             || kind === 283 /* SpreadAssignment */
12318             || kind === 161 /* MethodDeclaration */
12319             || kind === 163 /* GetAccessor */
12320             || kind === 164 /* SetAccessor */;
12321     }
12322     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12323     // Type
12324     /**
12325      * Node test that determines whether a node is a valid type node.
12326      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12327      * of a TypeNode.
12328      */
12329     function isTypeNode(node) {
12330         return ts.isTypeNodeKind(node.kind);
12331     }
12332     ts.isTypeNode = isTypeNode;
12333     function isFunctionOrConstructorTypeNode(node) {
12334         switch (node.kind) {
12335             case 170 /* FunctionType */:
12336             case 171 /* ConstructorType */:
12337                 return true;
12338         }
12339         return false;
12340     }
12341     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12342     // Binding patterns
12343     /* @internal */
12344     function isBindingPattern(node) {
12345         if (node) {
12346             var kind = node.kind;
12347             return kind === 190 /* ArrayBindingPattern */
12348                 || kind === 189 /* ObjectBindingPattern */;
12349         }
12350         return false;
12351     }
12352     ts.isBindingPattern = isBindingPattern;
12353     /* @internal */
12354     function isAssignmentPattern(node) {
12355         var kind = node.kind;
12356         return kind === 192 /* ArrayLiteralExpression */
12357             || kind === 193 /* ObjectLiteralExpression */;
12358     }
12359     ts.isAssignmentPattern = isAssignmentPattern;
12360     /* @internal */
12361     function isArrayBindingElement(node) {
12362         var kind = node.kind;
12363         return kind === 191 /* BindingElement */
12364             || kind === 215 /* OmittedExpression */;
12365     }
12366     ts.isArrayBindingElement = isArrayBindingElement;
12367     /**
12368      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12369      */
12370     /* @internal */
12371     function isDeclarationBindingElement(bindingElement) {
12372         switch (bindingElement.kind) {
12373             case 242 /* VariableDeclaration */:
12374             case 156 /* Parameter */:
12375             case 191 /* BindingElement */:
12376                 return true;
12377         }
12378         return false;
12379     }
12380     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12381     /**
12382      * Determines whether a node is a BindingOrAssignmentPattern
12383      */
12384     /* @internal */
12385     function isBindingOrAssignmentPattern(node) {
12386         return isObjectBindingOrAssignmentPattern(node)
12387             || isArrayBindingOrAssignmentPattern(node);
12388     }
12389     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12390     /**
12391      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12392      */
12393     /* @internal */
12394     function isObjectBindingOrAssignmentPattern(node) {
12395         switch (node.kind) {
12396             case 189 /* ObjectBindingPattern */:
12397             case 193 /* ObjectLiteralExpression */:
12398                 return true;
12399         }
12400         return false;
12401     }
12402     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12403     /**
12404      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12405      */
12406     /* @internal */
12407     function isArrayBindingOrAssignmentPattern(node) {
12408         switch (node.kind) {
12409             case 190 /* ArrayBindingPattern */:
12410             case 192 /* ArrayLiteralExpression */:
12411                 return true;
12412         }
12413         return false;
12414     }
12415     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12416     /* @internal */
12417     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12418         var kind = node.kind;
12419         return kind === 194 /* PropertyAccessExpression */
12420             || kind === 153 /* QualifiedName */
12421             || kind === 188 /* ImportType */;
12422     }
12423     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12424     // Expression
12425     function isPropertyAccessOrQualifiedName(node) {
12426         var kind = node.kind;
12427         return kind === 194 /* PropertyAccessExpression */
12428             || kind === 153 /* QualifiedName */;
12429     }
12430     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12431     function isCallLikeExpression(node) {
12432         switch (node.kind) {
12433             case 268 /* JsxOpeningElement */:
12434             case 267 /* JsxSelfClosingElement */:
12435             case 196 /* CallExpression */:
12436             case 197 /* NewExpression */:
12437             case 198 /* TaggedTemplateExpression */:
12438             case 157 /* Decorator */:
12439                 return true;
12440             default:
12441                 return false;
12442         }
12443     }
12444     ts.isCallLikeExpression = isCallLikeExpression;
12445     function isCallOrNewExpression(node) {
12446         return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
12447     }
12448     ts.isCallOrNewExpression = isCallOrNewExpression;
12449     function isTemplateLiteral(node) {
12450         var kind = node.kind;
12451         return kind === 211 /* TemplateExpression */
12452             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12453     }
12454     ts.isTemplateLiteral = isTemplateLiteral;
12455     /* @internal */
12456     function isLeftHandSideExpression(node) {
12457         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12458     }
12459     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12460     function isLeftHandSideExpressionKind(kind) {
12461         switch (kind) {
12462             case 194 /* PropertyAccessExpression */:
12463             case 195 /* ElementAccessExpression */:
12464             case 197 /* NewExpression */:
12465             case 196 /* CallExpression */:
12466             case 266 /* JsxElement */:
12467             case 267 /* JsxSelfClosingElement */:
12468             case 270 /* JsxFragment */:
12469             case 198 /* TaggedTemplateExpression */:
12470             case 192 /* ArrayLiteralExpression */:
12471             case 200 /* ParenthesizedExpression */:
12472             case 193 /* ObjectLiteralExpression */:
12473             case 214 /* ClassExpression */:
12474             case 201 /* FunctionExpression */:
12475             case 75 /* Identifier */:
12476             case 13 /* RegularExpressionLiteral */:
12477             case 8 /* NumericLiteral */:
12478             case 9 /* BigIntLiteral */:
12479             case 10 /* StringLiteral */:
12480             case 14 /* NoSubstitutionTemplateLiteral */:
12481             case 211 /* TemplateExpression */:
12482             case 91 /* FalseKeyword */:
12483             case 100 /* NullKeyword */:
12484             case 104 /* ThisKeyword */:
12485             case 106 /* TrueKeyword */:
12486             case 102 /* SuperKeyword */:
12487             case 218 /* NonNullExpression */:
12488             case 219 /* MetaProperty */:
12489             case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12490                 return true;
12491             default:
12492                 return false;
12493         }
12494     }
12495     /* @internal */
12496     function isUnaryExpression(node) {
12497         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12498     }
12499     ts.isUnaryExpression = isUnaryExpression;
12500     function isUnaryExpressionKind(kind) {
12501         switch (kind) {
12502             case 207 /* PrefixUnaryExpression */:
12503             case 208 /* PostfixUnaryExpression */:
12504             case 203 /* DeleteExpression */:
12505             case 204 /* TypeOfExpression */:
12506             case 205 /* VoidExpression */:
12507             case 206 /* AwaitExpression */:
12508             case 199 /* TypeAssertionExpression */:
12509                 return true;
12510             default:
12511                 return isLeftHandSideExpressionKind(kind);
12512         }
12513     }
12514     /* @internal */
12515     function isUnaryExpressionWithWrite(expr) {
12516         switch (expr.kind) {
12517             case 208 /* PostfixUnaryExpression */:
12518                 return true;
12519             case 207 /* PrefixUnaryExpression */:
12520                 return expr.operator === 45 /* PlusPlusToken */ ||
12521                     expr.operator === 46 /* MinusMinusToken */;
12522             default:
12523                 return false;
12524         }
12525     }
12526     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12527     /* @internal */
12528     /**
12529      * Determines whether a node is an expression based only on its kind.
12530      * Use `isExpressionNode` if not in transforms.
12531      */
12532     function isExpression(node) {
12533         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12534     }
12535     ts.isExpression = isExpression;
12536     function isExpressionKind(kind) {
12537         switch (kind) {
12538             case 210 /* ConditionalExpression */:
12539             case 212 /* YieldExpression */:
12540             case 202 /* ArrowFunction */:
12541             case 209 /* BinaryExpression */:
12542             case 213 /* SpreadElement */:
12543             case 217 /* AsExpression */:
12544             case 215 /* OmittedExpression */:
12545             case 327 /* CommaListExpression */:
12546             case 326 /* PartiallyEmittedExpression */:
12547                 return true;
12548             default:
12549                 return isUnaryExpressionKind(kind);
12550         }
12551     }
12552     function isAssertionExpression(node) {
12553         var kind = node.kind;
12554         return kind === 199 /* TypeAssertionExpression */
12555             || kind === 217 /* AsExpression */;
12556     }
12557     ts.isAssertionExpression = isAssertionExpression;
12558     /* @internal */
12559     function isPartiallyEmittedExpression(node) {
12560         return node.kind === 326 /* PartiallyEmittedExpression */;
12561     }
12562     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
12563     /* @internal */
12564     function isNotEmittedStatement(node) {
12565         return node.kind === 325 /* NotEmittedStatement */;
12566     }
12567     ts.isNotEmittedStatement = isNotEmittedStatement;
12568     /* @internal */
12569     function isSyntheticReference(node) {
12570         return node.kind === 330 /* SyntheticReferenceExpression */;
12571     }
12572     ts.isSyntheticReference = isSyntheticReference;
12573     /* @internal */
12574     function isNotEmittedOrPartiallyEmittedNode(node) {
12575         return isNotEmittedStatement(node)
12576             || isPartiallyEmittedExpression(node);
12577     }
12578     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12579     function isIterationStatement(node, lookInLabeledStatements) {
12580         switch (node.kind) {
12581             case 230 /* ForStatement */:
12582             case 231 /* ForInStatement */:
12583             case 232 /* ForOfStatement */:
12584             case 228 /* DoStatement */:
12585             case 229 /* WhileStatement */:
12586                 return true;
12587             case 238 /* LabeledStatement */:
12588                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12589         }
12590         return false;
12591     }
12592     ts.isIterationStatement = isIterationStatement;
12593     /* @internal */
12594     function isScopeMarker(node) {
12595         return isExportAssignment(node) || isExportDeclaration(node);
12596     }
12597     ts.isScopeMarker = isScopeMarker;
12598     /* @internal */
12599     function hasScopeMarker(statements) {
12600         return ts.some(statements, isScopeMarker);
12601     }
12602     ts.hasScopeMarker = hasScopeMarker;
12603     /* @internal */
12604     function needsScopeMarker(result) {
12605         return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12606     }
12607     ts.needsScopeMarker = needsScopeMarker;
12608     /* @internal */
12609     function isExternalModuleIndicator(result) {
12610         // Exported top-level member indicates moduleness
12611         return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
12612     }
12613     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12614     /* @internal */
12615     function isForInOrOfStatement(node) {
12616         return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
12617     }
12618     ts.isForInOrOfStatement = isForInOrOfStatement;
12619     // Element
12620     /* @internal */
12621     function isConciseBody(node) {
12622         return isBlock(node)
12623             || isExpression(node);
12624     }
12625     ts.isConciseBody = isConciseBody;
12626     /* @internal */
12627     function isFunctionBody(node) {
12628         return isBlock(node);
12629     }
12630     ts.isFunctionBody = isFunctionBody;
12631     /* @internal */
12632     function isForInitializer(node) {
12633         return isVariableDeclarationList(node)
12634             || isExpression(node);
12635     }
12636     ts.isForInitializer = isForInitializer;
12637     /* @internal */
12638     function isModuleBody(node) {
12639         var kind = node.kind;
12640         return kind === 250 /* ModuleBlock */
12641             || kind === 249 /* ModuleDeclaration */
12642             || kind === 75 /* Identifier */;
12643     }
12644     ts.isModuleBody = isModuleBody;
12645     /* @internal */
12646     function isNamespaceBody(node) {
12647         var kind = node.kind;
12648         return kind === 250 /* ModuleBlock */
12649             || kind === 249 /* ModuleDeclaration */;
12650     }
12651     ts.isNamespaceBody = isNamespaceBody;
12652     /* @internal */
12653     function isJSDocNamespaceBody(node) {
12654         var kind = node.kind;
12655         return kind === 75 /* Identifier */
12656             || kind === 249 /* ModuleDeclaration */;
12657     }
12658     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12659     /* @internal */
12660     function isNamedImportBindings(node) {
12661         var kind = node.kind;
12662         return kind === 257 /* NamedImports */
12663             || kind === 256 /* NamespaceImport */;
12664     }
12665     ts.isNamedImportBindings = isNamedImportBindings;
12666     /* @internal */
12667     function isModuleOrEnumDeclaration(node) {
12668         return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
12669     }
12670     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12671     function isDeclarationKind(kind) {
12672         return kind === 202 /* ArrowFunction */
12673             || kind === 191 /* BindingElement */
12674             || kind === 245 /* ClassDeclaration */
12675             || kind === 214 /* ClassExpression */
12676             || kind === 162 /* Constructor */
12677             || kind === 248 /* EnumDeclaration */
12678             || kind === 284 /* EnumMember */
12679             || kind === 263 /* ExportSpecifier */
12680             || kind === 244 /* FunctionDeclaration */
12681             || kind === 201 /* FunctionExpression */
12682             || kind === 163 /* GetAccessor */
12683             || kind === 255 /* ImportClause */
12684             || kind === 253 /* ImportEqualsDeclaration */
12685             || kind === 258 /* ImportSpecifier */
12686             || kind === 246 /* InterfaceDeclaration */
12687             || kind === 273 /* JsxAttribute */
12688             || kind === 161 /* MethodDeclaration */
12689             || kind === 160 /* MethodSignature */
12690             || kind === 249 /* ModuleDeclaration */
12691             || kind === 252 /* NamespaceExportDeclaration */
12692             || kind === 256 /* NamespaceImport */
12693             || kind === 262 /* NamespaceExport */
12694             || kind === 156 /* Parameter */
12695             || kind === 281 /* PropertyAssignment */
12696             || kind === 159 /* PropertyDeclaration */
12697             || kind === 158 /* PropertySignature */
12698             || kind === 164 /* SetAccessor */
12699             || kind === 282 /* ShorthandPropertyAssignment */
12700             || kind === 247 /* TypeAliasDeclaration */
12701             || kind === 155 /* TypeParameter */
12702             || kind === 242 /* VariableDeclaration */
12703             || kind === 322 /* JSDocTypedefTag */
12704             || kind === 315 /* JSDocCallbackTag */
12705             || kind === 323 /* JSDocPropertyTag */;
12706     }
12707     function isDeclarationStatementKind(kind) {
12708         return kind === 244 /* FunctionDeclaration */
12709             || kind === 264 /* MissingDeclaration */
12710             || kind === 245 /* ClassDeclaration */
12711             || kind === 246 /* InterfaceDeclaration */
12712             || kind === 247 /* TypeAliasDeclaration */
12713             || kind === 248 /* EnumDeclaration */
12714             || kind === 249 /* ModuleDeclaration */
12715             || kind === 254 /* ImportDeclaration */
12716             || kind === 253 /* ImportEqualsDeclaration */
12717             || kind === 260 /* ExportDeclaration */
12718             || kind === 259 /* ExportAssignment */
12719             || kind === 252 /* NamespaceExportDeclaration */;
12720     }
12721     function isStatementKindButNotDeclarationKind(kind) {
12722         return kind === 234 /* BreakStatement */
12723             || kind === 233 /* ContinueStatement */
12724             || kind === 241 /* DebuggerStatement */
12725             || kind === 228 /* DoStatement */
12726             || kind === 226 /* ExpressionStatement */
12727             || kind === 224 /* EmptyStatement */
12728             || kind === 231 /* ForInStatement */
12729             || kind === 232 /* ForOfStatement */
12730             || kind === 230 /* ForStatement */
12731             || kind === 227 /* IfStatement */
12732             || kind === 238 /* LabeledStatement */
12733             || kind === 235 /* ReturnStatement */
12734             || kind === 237 /* SwitchStatement */
12735             || kind === 239 /* ThrowStatement */
12736             || kind === 240 /* TryStatement */
12737             || kind === 225 /* VariableStatement */
12738             || kind === 229 /* WhileStatement */
12739             || kind === 236 /* WithStatement */
12740             || kind === 325 /* NotEmittedStatement */
12741             || kind === 329 /* EndOfDeclarationMarker */
12742             || kind === 328 /* MergeDeclarationMarker */;
12743     }
12744     /* @internal */
12745     function isDeclaration(node) {
12746         if (node.kind === 155 /* TypeParameter */) {
12747             return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12748         }
12749         return isDeclarationKind(node.kind);
12750     }
12751     ts.isDeclaration = isDeclaration;
12752     /* @internal */
12753     function isDeclarationStatement(node) {
12754         return isDeclarationStatementKind(node.kind);
12755     }
12756     ts.isDeclarationStatement = isDeclarationStatement;
12757     /**
12758      * Determines whether the node is a statement that is not also a declaration
12759      */
12760     /* @internal */
12761     function isStatementButNotDeclaration(node) {
12762         return isStatementKindButNotDeclarationKind(node.kind);
12763     }
12764     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12765     /* @internal */
12766     function isStatement(node) {
12767         var kind = node.kind;
12768         return isStatementKindButNotDeclarationKind(kind)
12769             || isDeclarationStatementKind(kind)
12770             || isBlockStatement(node);
12771     }
12772     ts.isStatement = isStatement;
12773     function isBlockStatement(node) {
12774         if (node.kind !== 223 /* Block */)
12775             return false;
12776         if (node.parent !== undefined) {
12777             if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
12778                 return false;
12779             }
12780         }
12781         return !ts.isFunctionBlock(node);
12782     }
12783     // Module references
12784     /* @internal */
12785     function isModuleReference(node) {
12786         var kind = node.kind;
12787         return kind === 265 /* ExternalModuleReference */
12788             || kind === 153 /* QualifiedName */
12789             || kind === 75 /* Identifier */;
12790     }
12791     ts.isModuleReference = isModuleReference;
12792     // JSX
12793     /* @internal */
12794     function isJsxTagNameExpression(node) {
12795         var kind = node.kind;
12796         return kind === 104 /* ThisKeyword */
12797             || kind === 75 /* Identifier */
12798             || kind === 194 /* PropertyAccessExpression */;
12799     }
12800     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12801     /* @internal */
12802     function isJsxChild(node) {
12803         var kind = node.kind;
12804         return kind === 266 /* JsxElement */
12805             || kind === 276 /* JsxExpression */
12806             || kind === 267 /* JsxSelfClosingElement */
12807             || kind === 11 /* JsxText */
12808             || kind === 270 /* JsxFragment */;
12809     }
12810     ts.isJsxChild = isJsxChild;
12811     /* @internal */
12812     function isJsxAttributeLike(node) {
12813         var kind = node.kind;
12814         return kind === 273 /* JsxAttribute */
12815             || kind === 275 /* JsxSpreadAttribute */;
12816     }
12817     ts.isJsxAttributeLike = isJsxAttributeLike;
12818     /* @internal */
12819     function isStringLiteralOrJsxExpression(node) {
12820         var kind = node.kind;
12821         return kind === 10 /* StringLiteral */
12822             || kind === 276 /* JsxExpression */;
12823     }
12824     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12825     function isJsxOpeningLikeElement(node) {
12826         var kind = node.kind;
12827         return kind === 268 /* JsxOpeningElement */
12828             || kind === 267 /* JsxSelfClosingElement */;
12829     }
12830     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12831     // Clauses
12832     function isCaseOrDefaultClause(node) {
12833         var kind = node.kind;
12834         return kind === 277 /* CaseClause */
12835             || kind === 278 /* DefaultClause */;
12836     }
12837     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12838     // JSDoc
12839     /** True if node is of some JSDoc syntax kind. */
12840     /* @internal */
12841     function isJSDocNode(node) {
12842         return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
12843     }
12844     ts.isJSDocNode = isJSDocNode;
12845     /** True if node is of a kind that may contain comment text. */
12846     function isJSDocCommentContainingNode(node) {
12847         return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
12848     }
12849     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12850     // TODO: determine what this does before making it public.
12851     /* @internal */
12852     function isJSDocTag(node) {
12853         return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
12854     }
12855     ts.isJSDocTag = isJSDocTag;
12856     function isSetAccessor(node) {
12857         return node.kind === 164 /* SetAccessor */;
12858     }
12859     ts.isSetAccessor = isSetAccessor;
12860     function isGetAccessor(node) {
12861         return node.kind === 163 /* GetAccessor */;
12862     }
12863     ts.isGetAccessor = isGetAccessor;
12864     /** True if has jsdoc nodes attached to it. */
12865     /* @internal */
12866     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12867     function hasJSDocNodes(node) {
12868         var jsDoc = node.jsDoc;
12869         return !!jsDoc && jsDoc.length > 0;
12870     }
12871     ts.hasJSDocNodes = hasJSDocNodes;
12872     /** True if has type node attached to it. */
12873     /* @internal */
12874     function hasType(node) {
12875         return !!node.type;
12876     }
12877     ts.hasType = hasType;
12878     /** True if has initializer node attached to it. */
12879     /* @internal */
12880     function hasInitializer(node) {
12881         return !!node.initializer;
12882     }
12883     ts.hasInitializer = hasInitializer;
12884     /** True if has initializer node attached to it. */
12885     function hasOnlyExpressionInitializer(node) {
12886         switch (node.kind) {
12887             case 242 /* VariableDeclaration */:
12888             case 156 /* Parameter */:
12889             case 191 /* BindingElement */:
12890             case 158 /* PropertySignature */:
12891             case 159 /* PropertyDeclaration */:
12892             case 281 /* PropertyAssignment */:
12893             case 284 /* EnumMember */:
12894                 return true;
12895             default:
12896                 return false;
12897         }
12898     }
12899     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12900     function isObjectLiteralElement(node) {
12901         return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12902     }
12903     ts.isObjectLiteralElement = isObjectLiteralElement;
12904     /* @internal */
12905     function isTypeReferenceType(node) {
12906         return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
12907     }
12908     ts.isTypeReferenceType = isTypeReferenceType;
12909     var MAX_SMI_X86 = 1073741823;
12910     /* @internal */
12911     function guessIndentation(lines) {
12912         var indentation = MAX_SMI_X86;
12913         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12914             var line = lines_1[_i];
12915             if (!line.length) {
12916                 continue;
12917             }
12918             var i = 0;
12919             for (; i < line.length && i < indentation; i++) {
12920                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12921                     break;
12922                 }
12923             }
12924             if (i < indentation) {
12925                 indentation = i;
12926             }
12927             if (indentation === 0) {
12928                 return 0;
12929             }
12930         }
12931         return indentation === MAX_SMI_X86 ? undefined : indentation;
12932     }
12933     ts.guessIndentation = guessIndentation;
12934     function isStringLiteralLike(node) {
12935         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12936     }
12937     ts.isStringLiteralLike = isStringLiteralLike;
12938     // #endregion
12939 })(ts || (ts = {}));
12940 /* @internal */
12941 var ts;
12942 (function (ts) {
12943     ts.resolvingEmptyArray = [];
12944     ts.emptyMap = ts.createMap();
12945     ts.emptyUnderscoreEscapedMap = ts.emptyMap;
12946     ts.externalHelpersModuleNameText = "tslib";
12947     ts.defaultMaximumTruncationLength = 160;
12948     ts.noTruncationMaximumTruncationLength = 1000000;
12949     function getDeclarationOfKind(symbol, kind) {
12950         var declarations = symbol.declarations;
12951         if (declarations) {
12952             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12953                 var declaration = declarations_1[_i];
12954                 if (declaration.kind === kind) {
12955                     return declaration;
12956                 }
12957             }
12958         }
12959         return undefined;
12960     }
12961     ts.getDeclarationOfKind = getDeclarationOfKind;
12962     /** Create a new escaped identifier map. */
12963     function createUnderscoreEscapedMap() {
12964         return new ts.Map();
12965     }
12966     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12967     function hasEntries(map) {
12968         return !!map && !!map.size;
12969     }
12970     ts.hasEntries = hasEntries;
12971     function createSymbolTable(symbols) {
12972         var result = ts.createMap();
12973         if (symbols) {
12974             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12975                 var symbol = symbols_1[_i];
12976                 result.set(symbol.escapedName, symbol);
12977             }
12978         }
12979         return result;
12980     }
12981     ts.createSymbolTable = createSymbolTable;
12982     function isTransientSymbol(symbol) {
12983         return (symbol.flags & 33554432 /* Transient */) !== 0;
12984     }
12985     ts.isTransientSymbol = isTransientSymbol;
12986     var stringWriter = createSingleLineStringWriter();
12987     function createSingleLineStringWriter() {
12988         var str = "";
12989         var writeText = function (text) { return str += text; };
12990         return {
12991             getText: function () { return str; },
12992             write: writeText,
12993             rawWrite: writeText,
12994             writeKeyword: writeText,
12995             writeOperator: writeText,
12996             writePunctuation: writeText,
12997             writeSpace: writeText,
12998             writeStringLiteral: writeText,
12999             writeLiteral: writeText,
13000             writeParameter: writeText,
13001             writeProperty: writeText,
13002             writeSymbol: function (s, _) { return writeText(s); },
13003             writeTrailingSemicolon: writeText,
13004             writeComment: writeText,
13005             getTextPos: function () { return str.length; },
13006             getLine: function () { return 0; },
13007             getColumn: function () { return 0; },
13008             getIndent: function () { return 0; },
13009             isAtStartOfLine: function () { return false; },
13010             hasTrailingComment: function () { return false; },
13011             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
13012             // Completely ignore indentation for string writers.  And map newlines to
13013             // a single space.
13014             writeLine: function () { return str += " "; },
13015             increaseIndent: ts.noop,
13016             decreaseIndent: ts.noop,
13017             clear: function () { return str = ""; },
13018             trackSymbol: ts.noop,
13019             reportInaccessibleThisError: ts.noop,
13020             reportInaccessibleUniqueSymbolError: ts.noop,
13021             reportPrivateInBaseOfClassExpression: ts.noop,
13022         };
13023     }
13024     function changesAffectModuleResolution(oldOptions, newOptions) {
13025         return oldOptions.configFilePath !== newOptions.configFilePath ||
13026             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
13027     }
13028     ts.changesAffectModuleResolution = changesAffectModuleResolution;
13029     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
13030         return ts.moduleResolutionOptionDeclarations.some(function (o) {
13031             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
13032         });
13033     }
13034     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
13035     function findAncestor(node, callback) {
13036         while (node) {
13037             var result = callback(node);
13038             if (result === "quit") {
13039                 return undefined;
13040             }
13041             else if (result) {
13042                 return node;
13043             }
13044             node = node.parent;
13045         }
13046         return undefined;
13047     }
13048     ts.findAncestor = findAncestor;
13049     function forEachAncestor(node, callback) {
13050         while (true) {
13051             var res = callback(node);
13052             if (res === "quit")
13053                 return undefined;
13054             if (res !== undefined)
13055                 return res;
13056             if (ts.isSourceFile(node))
13057                 return undefined;
13058             node = node.parent;
13059         }
13060     }
13061     ts.forEachAncestor = forEachAncestor;
13062     function forEachEntry(map, callback) {
13063         var iterator = map.entries();
13064         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13065             var _a = iterResult.value, key = _a[0], value = _a[1];
13066             var result = callback(value, key);
13067             if (result) {
13068                 return result;
13069             }
13070         }
13071         return undefined;
13072     }
13073     ts.forEachEntry = forEachEntry;
13074     function forEachKey(map, callback) {
13075         var iterator = map.keys();
13076         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13077             var result = callback(iterResult.value);
13078             if (result) {
13079                 return result;
13080             }
13081         }
13082         return undefined;
13083     }
13084     ts.forEachKey = forEachKey;
13085     function copyEntries(source, target) {
13086         source.forEach(function (value, key) {
13087             target.set(key, value);
13088         });
13089     }
13090     ts.copyEntries = copyEntries;
13091     function arrayToSet(array, makeKey) {
13092         return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
13093     }
13094     ts.arrayToSet = arrayToSet;
13095     function cloneMap(map) {
13096         var clone = ts.createMap();
13097         copyEntries(map, clone);
13098         return clone;
13099     }
13100     ts.cloneMap = cloneMap;
13101     function usingSingleLineStringWriter(action) {
13102         var oldString = stringWriter.getText();
13103         try {
13104             action(stringWriter);
13105             return stringWriter.getText();
13106         }
13107         finally {
13108             stringWriter.clear();
13109             stringWriter.writeKeyword(oldString);
13110         }
13111     }
13112     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
13113     function getFullWidth(node) {
13114         return node.end - node.pos;
13115     }
13116     ts.getFullWidth = getFullWidth;
13117     function getResolvedModule(sourceFile, moduleNameText) {
13118         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
13119     }
13120     ts.getResolvedModule = getResolvedModule;
13121     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
13122         if (!sourceFile.resolvedModules) {
13123             sourceFile.resolvedModules = ts.createMap();
13124         }
13125         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
13126     }
13127     ts.setResolvedModule = setResolvedModule;
13128     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
13129         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
13130             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
13131         }
13132         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
13133     }
13134     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
13135     function projectReferenceIsEqualTo(oldRef, newRef) {
13136         return oldRef.path === newRef.path &&
13137             !oldRef.prepend === !newRef.prepend &&
13138             !oldRef.circular === !newRef.circular;
13139     }
13140     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
13141     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
13142         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
13143             oldResolution.extension === newResolution.extension &&
13144             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
13145             oldResolution.originalPath === newResolution.originalPath &&
13146             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
13147     }
13148     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
13149     function packageIdIsEqual(a, b) {
13150         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
13151     }
13152     function packageIdToString(_a) {
13153         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
13154         var fullName = subModuleName ? name + "/" + subModuleName : name;
13155         return fullName + "@" + version;
13156     }
13157     ts.packageIdToString = packageIdToString;
13158     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13159         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13160     }
13161     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13162     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13163         ts.Debug.assert(names.length === newResolutions.length);
13164         for (var i = 0; i < names.length; i++) {
13165             var newResolution = newResolutions[i];
13166             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13167             var changed = oldResolution
13168                 ? !newResolution || !comparer(oldResolution, newResolution)
13169                 : newResolution;
13170             if (changed) {
13171                 return true;
13172             }
13173         }
13174         return false;
13175     }
13176     ts.hasChangesInResolutions = hasChangesInResolutions;
13177     // Returns true if this node contains a parse error anywhere underneath it.
13178     function containsParseError(node) {
13179         aggregateChildData(node);
13180         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13181     }
13182     ts.containsParseError = containsParseError;
13183     function aggregateChildData(node) {
13184         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13185             // A node is considered to contain a parse error if:
13186             //  a) the parser explicitly marked that it had an error
13187             //  b) any of it's children reported that it had an error.
13188             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13189                 ts.forEachChild(node, containsParseError);
13190             // If so, mark ourselves accordingly.
13191             if (thisNodeOrAnySubNodesHasError) {
13192                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13193             }
13194             // Also mark that we've propagated the child information to this node.  This way we can
13195             // always consult the bit directly on this node without needing to check its children
13196             // again.
13197             node.flags |= 524288 /* HasAggregatedChildData */;
13198         }
13199     }
13200     function getSourceFileOfNode(node) {
13201         while (node && node.kind !== 290 /* SourceFile */) {
13202             node = node.parent;
13203         }
13204         return node;
13205     }
13206     ts.getSourceFileOfNode = getSourceFileOfNode;
13207     function isStatementWithLocals(node) {
13208         switch (node.kind) {
13209             case 223 /* Block */:
13210             case 251 /* CaseBlock */:
13211             case 230 /* ForStatement */:
13212             case 231 /* ForInStatement */:
13213             case 232 /* ForOfStatement */:
13214                 return true;
13215         }
13216         return false;
13217     }
13218     ts.isStatementWithLocals = isStatementWithLocals;
13219     function getStartPositionOfLine(line, sourceFile) {
13220         ts.Debug.assert(line >= 0);
13221         return ts.getLineStarts(sourceFile)[line];
13222     }
13223     ts.getStartPositionOfLine = getStartPositionOfLine;
13224     // This is a useful function for debugging purposes.
13225     function nodePosToString(node) {
13226         var file = getSourceFileOfNode(node);
13227         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13228         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13229     }
13230     ts.nodePosToString = nodePosToString;
13231     function getEndLinePosition(line, sourceFile) {
13232         ts.Debug.assert(line >= 0);
13233         var lineStarts = ts.getLineStarts(sourceFile);
13234         var lineIndex = line;
13235         var sourceText = sourceFile.text;
13236         if (lineIndex + 1 === lineStarts.length) {
13237             // last line - return EOF
13238             return sourceText.length - 1;
13239         }
13240         else {
13241             // current line start
13242             var start = lineStarts[lineIndex];
13243             // take the start position of the next line - 1 = it should be some line break
13244             var pos = lineStarts[lineIndex + 1] - 1;
13245             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13246             // walk backwards skipping line breaks, stop the the beginning of current line.
13247             // i.e:
13248             // <some text>
13249             // $ <- end of line for this position should match the start position
13250             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13251                 pos--;
13252             }
13253             return pos;
13254         }
13255     }
13256     ts.getEndLinePosition = getEndLinePosition;
13257     /**
13258      * Returns a value indicating whether a name is unique globally or within the current file.
13259      * 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`.
13260      */
13261     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13262         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13263     }
13264     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13265     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13266     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13267     // in the tree), it is definitely missing. However, a node may be defined, but still be
13268     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13269     // get anything in the source code that it expects at that location. For example:
13270     //
13271     //          let a: ;
13272     //
13273     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13274     // code). So the parser will attempt to parse out a type, and will create an actual node.
13275     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13276     // contained within it.
13277     function nodeIsMissing(node) {
13278         if (node === undefined) {
13279             return true;
13280         }
13281         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13282     }
13283     ts.nodeIsMissing = nodeIsMissing;
13284     function nodeIsPresent(node) {
13285         return !nodeIsMissing(node);
13286     }
13287     ts.nodeIsPresent = nodeIsPresent;
13288     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13289         if (from === undefined || from.length === 0)
13290             return to;
13291         var statementIndex = 0;
13292         // skip all prologue directives to insert at the correct position
13293         for (; statementIndex < to.length; ++statementIndex) {
13294             if (!isPrologueDirective(to[statementIndex])) {
13295                 break;
13296             }
13297         }
13298         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13299         return to;
13300     }
13301     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13302         if (statement === undefined)
13303             return to;
13304         var statementIndex = 0;
13305         // skip all prologue directives to insert at the correct position
13306         for (; statementIndex < to.length; ++statementIndex) {
13307             if (!isPrologueDirective(to[statementIndex])) {
13308                 break;
13309             }
13310         }
13311         to.splice(statementIndex, 0, statement);
13312         return to;
13313     }
13314     function isAnyPrologueDirective(node) {
13315         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13316     }
13317     /**
13318      * Prepends statements to an array while taking care of prologue directives.
13319      */
13320     function insertStatementsAfterStandardPrologue(to, from) {
13321         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13322     }
13323     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13324     function insertStatementsAfterCustomPrologue(to, from) {
13325         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13326     }
13327     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13328     /**
13329      * Prepends statements to an array while taking care of prologue directives.
13330      */
13331     function insertStatementAfterStandardPrologue(to, statement) {
13332         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13333     }
13334     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13335     function insertStatementAfterCustomPrologue(to, statement) {
13336         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13337     }
13338     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13339     /**
13340      * Determine if the given comment is a triple-slash
13341      *
13342      * @return true if the comment is a triple-slash comment else false
13343      */
13344     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13345         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13346         // so that we don't end up computing comment string and doing match for all // comments
13347         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13348             commentPos + 2 < commentEnd &&
13349             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13350             var textSubStr = text.substring(commentPos, commentEnd);
13351             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13352                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13353                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13354                 textSubStr.match(defaultLibReferenceRegEx) ?
13355                 true : false;
13356         }
13357         return false;
13358     }
13359     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13360     function isPinnedComment(text, start) {
13361         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13362             text.charCodeAt(start + 2) === 33 /* exclamation */;
13363     }
13364     ts.isPinnedComment = isPinnedComment;
13365     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13366         var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
13367             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13368             commentDirective,
13369         ]); }));
13370         var usedLines = ts.createMap();
13371         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13372         function getUnusedExpectations() {
13373             return ts.arrayFrom(directivesByLine.entries())
13374                 .filter(function (_a) {
13375                 var line = _a[0], directive = _a[1];
13376                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13377             })
13378                 .map(function (_a) {
13379                 var _ = _a[0], directive = _a[1];
13380                 return directive;
13381             });
13382         }
13383         function markUsed(line) {
13384             if (!directivesByLine.has("" + line)) {
13385                 return false;
13386             }
13387             usedLines.set("" + line, true);
13388             return true;
13389         }
13390     }
13391     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13392     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13393         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13394         // want to skip trivia because this will launch us forward to the next token.
13395         if (nodeIsMissing(node)) {
13396             return node.pos;
13397         }
13398         if (ts.isJSDocNode(node)) {
13399             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13400         }
13401         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13402             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13403         }
13404         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13405         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13406         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13407         // first child to determine the actual position of its first token.
13408         if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) {
13409             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13410         }
13411         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13412     }
13413     ts.getTokenPosOfNode = getTokenPosOfNode;
13414     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13415         if (nodeIsMissing(node) || !node.decorators) {
13416             return getTokenPosOfNode(node, sourceFile);
13417         }
13418         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13419     }
13420     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13421     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13422         if (includeTrivia === void 0) { includeTrivia = false; }
13423         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13424     }
13425     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13426     function isJSDocTypeExpressionOrChild(node) {
13427         return !!findAncestor(node, ts.isJSDocTypeExpression);
13428     }
13429     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13430         if (includeTrivia === void 0) { includeTrivia = false; }
13431         if (nodeIsMissing(node)) {
13432             return "";
13433         }
13434         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13435         if (isJSDocTypeExpressionOrChild(node)) {
13436             // strip space + asterisk at line start
13437             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13438         }
13439         return text;
13440     }
13441     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13442     function getTextOfNode(node, includeTrivia) {
13443         if (includeTrivia === void 0) { includeTrivia = false; }
13444         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13445     }
13446     ts.getTextOfNode = getTextOfNode;
13447     function getPos(range) {
13448         return range.pos;
13449     }
13450     /**
13451      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13452      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13453      */
13454     function indexOfNode(nodeArray, node) {
13455         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13456     }
13457     ts.indexOfNode = indexOfNode;
13458     /**
13459      * Gets flags that control emit behavior of a node.
13460      */
13461     function getEmitFlags(node) {
13462         var emitNode = node.emitNode;
13463         return emitNode && emitNode.flags || 0;
13464     }
13465     ts.getEmitFlags = getEmitFlags;
13466     function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13467         // If we don't need to downlevel and we can reach the original source text using
13468         // the node's parent reference, then simply get the text as it was originally written.
13469         if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13470             ts.isBigIntLiteral(node))) {
13471             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13472         }
13473         // If we can't reach the original source text, use the canonical form if it's a number,
13474         // or a (possibly escaped) quoted form of the original text if it's string-like.
13475         switch (node.kind) {
13476             case 10 /* StringLiteral */: {
13477                 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13478                     neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13479                         escapeNonAsciiString;
13480                 if (node.singleQuote) {
13481                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13482                 }
13483                 else {
13484                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13485                 }
13486             }
13487             case 14 /* NoSubstitutionTemplateLiteral */:
13488             case 15 /* TemplateHead */:
13489             case 16 /* TemplateMiddle */:
13490             case 17 /* TemplateTail */: {
13491                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13492                 // had to include a backslash: `not \${a} substitution`.
13493                 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13494                     escapeNonAsciiString;
13495                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13496                 switch (node.kind) {
13497                     case 14 /* NoSubstitutionTemplateLiteral */:
13498                         return "`" + rawText + "`";
13499                     case 15 /* TemplateHead */:
13500                         return "`" + rawText + "${";
13501                     case 16 /* TemplateMiddle */:
13502                         return "}" + rawText + "${";
13503                     case 17 /* TemplateTail */:
13504                         return "}" + rawText + "`";
13505                 }
13506                 break;
13507             }
13508             case 8 /* NumericLiteral */:
13509             case 9 /* BigIntLiteral */:
13510             case 13 /* RegularExpressionLiteral */:
13511                 return node.text;
13512         }
13513         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13514     }
13515     ts.getLiteralText = getLiteralText;
13516     function getTextOfConstantValue(value) {
13517         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13518     }
13519     ts.getTextOfConstantValue = getTextOfConstantValue;
13520     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13521     // all non-alphanumeric characters with underscores
13522     function makeIdentifierFromModuleName(moduleName) {
13523         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13524     }
13525     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13526     function isBlockOrCatchScoped(declaration) {
13527         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13528             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13529     }
13530     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13531     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13532         var node = getRootDeclaration(declaration);
13533         return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
13534     }
13535     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13536     function isAmbientModule(node) {
13537         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13538     }
13539     ts.isAmbientModule = isAmbientModule;
13540     function isModuleWithStringLiteralName(node) {
13541         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13542     }
13543     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13544     function isNonGlobalAmbientModule(node) {
13545         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13546     }
13547     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13548     /**
13549      * An effective module (namespace) declaration is either
13550      * 1. An actual declaration: namespace X { ... }
13551      * 2. A Javascript declaration, which is:
13552      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13553      */
13554     function isEffectiveModuleDeclaration(node) {
13555         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13556     }
13557     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13558     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13559     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13560         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13561     }
13562     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13563     function isShorthandAmbientModule(node) {
13564         // The only kind of module that can be missing a body is a shorthand ambient module.
13565         return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
13566     }
13567     function isBlockScopedContainerTopLevel(node) {
13568         return node.kind === 290 /* SourceFile */ ||
13569             node.kind === 249 /* ModuleDeclaration */ ||
13570             ts.isFunctionLike(node);
13571     }
13572     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13573     function isGlobalScopeAugmentation(module) {
13574         return !!(module.flags & 1024 /* GlobalAugmentation */);
13575     }
13576     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13577     function isExternalModuleAugmentation(node) {
13578         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13579     }
13580     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13581     function isModuleAugmentationExternal(node) {
13582         // external module augmentation is a ambient module declaration that is either:
13583         // - defined in the top level scope and source file is an external module
13584         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13585         switch (node.parent.kind) {
13586             case 290 /* SourceFile */:
13587                 return ts.isExternalModule(node.parent);
13588             case 250 /* ModuleBlock */:
13589                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13590         }
13591         return false;
13592     }
13593     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13594     function getNonAugmentationDeclaration(symbol) {
13595         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13596     }
13597     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13598     function isEffectiveExternalModule(node, compilerOptions) {
13599         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13600     }
13601     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13602     /**
13603      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13604      */
13605     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13606         // We can only verify strict mode for JS/TS files
13607         switch (node.scriptKind) {
13608             case 1 /* JS */:
13609             case 3 /* TS */:
13610             case 2 /* JSX */:
13611             case 4 /* TSX */:
13612                 break;
13613             default:
13614                 return false;
13615         }
13616         // Strict mode does not matter for declaration files.
13617         if (node.isDeclarationFile) {
13618             return false;
13619         }
13620         // If `alwaysStrict` is set, then treat the file as strict.
13621         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13622             return true;
13623         }
13624         // Starting with a "use strict" directive indicates the file is strict.
13625         if (ts.startsWithUseStrict(node.statements)) {
13626             return true;
13627         }
13628         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13629             // ECMAScript Modules are always strict.
13630             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13631                 return true;
13632             }
13633             // Other modules are strict unless otherwise specified.
13634             return !compilerOptions.noImplicitUseStrict;
13635         }
13636         return false;
13637     }
13638     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13639     function isBlockScope(node, parentNode) {
13640         switch (node.kind) {
13641             case 290 /* SourceFile */:
13642             case 251 /* CaseBlock */:
13643             case 280 /* CatchClause */:
13644             case 249 /* ModuleDeclaration */:
13645             case 230 /* ForStatement */:
13646             case 231 /* ForInStatement */:
13647             case 232 /* ForOfStatement */:
13648             case 162 /* Constructor */:
13649             case 161 /* MethodDeclaration */:
13650             case 163 /* GetAccessor */:
13651             case 164 /* SetAccessor */:
13652             case 244 /* FunctionDeclaration */:
13653             case 201 /* FunctionExpression */:
13654             case 202 /* ArrowFunction */:
13655                 return true;
13656             case 223 /* Block */:
13657                 // function block is not considered block-scope container
13658                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13659                 return !ts.isFunctionLike(parentNode);
13660         }
13661         return false;
13662     }
13663     ts.isBlockScope = isBlockScope;
13664     function isDeclarationWithTypeParameters(node) {
13665         switch (node.kind) {
13666             case 315 /* JSDocCallbackTag */:
13667             case 322 /* JSDocTypedefTag */:
13668             case 305 /* JSDocSignature */:
13669                 return true;
13670             default:
13671                 ts.assertType(node);
13672                 return isDeclarationWithTypeParameterChildren(node);
13673         }
13674     }
13675     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13676     function isDeclarationWithTypeParameterChildren(node) {
13677         switch (node.kind) {
13678             case 165 /* CallSignature */:
13679             case 166 /* ConstructSignature */:
13680             case 160 /* MethodSignature */:
13681             case 167 /* IndexSignature */:
13682             case 170 /* FunctionType */:
13683             case 171 /* ConstructorType */:
13684             case 300 /* JSDocFunctionType */:
13685             case 245 /* ClassDeclaration */:
13686             case 214 /* ClassExpression */:
13687             case 246 /* InterfaceDeclaration */:
13688             case 247 /* TypeAliasDeclaration */:
13689             case 321 /* JSDocTemplateTag */:
13690             case 244 /* FunctionDeclaration */:
13691             case 161 /* MethodDeclaration */:
13692             case 162 /* Constructor */:
13693             case 163 /* GetAccessor */:
13694             case 164 /* SetAccessor */:
13695             case 201 /* FunctionExpression */:
13696             case 202 /* ArrowFunction */:
13697                 return true;
13698             default:
13699                 ts.assertType(node);
13700                 return false;
13701         }
13702     }
13703     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13704     function isAnyImportSyntax(node) {
13705         switch (node.kind) {
13706             case 254 /* ImportDeclaration */:
13707             case 253 /* ImportEqualsDeclaration */:
13708                 return true;
13709             default:
13710                 return false;
13711         }
13712     }
13713     ts.isAnyImportSyntax = isAnyImportSyntax;
13714     function isLateVisibilityPaintedStatement(node) {
13715         switch (node.kind) {
13716             case 254 /* ImportDeclaration */:
13717             case 253 /* ImportEqualsDeclaration */:
13718             case 225 /* VariableStatement */:
13719             case 245 /* ClassDeclaration */:
13720             case 244 /* FunctionDeclaration */:
13721             case 249 /* ModuleDeclaration */:
13722             case 247 /* TypeAliasDeclaration */:
13723             case 246 /* InterfaceDeclaration */:
13724             case 248 /* EnumDeclaration */:
13725                 return true;
13726             default:
13727                 return false;
13728         }
13729     }
13730     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13731     function isAnyImportOrReExport(node) {
13732         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13733     }
13734     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13735     // Gets the nearest enclosing block scope container that has the provided node
13736     // as a descendant, that is not the provided node.
13737     function getEnclosingBlockScopeContainer(node) {
13738         return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13739     }
13740     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13741     // Return display name of an identifier
13742     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13743     // text of the expression in the computed property.
13744     function declarationNameToString(name) {
13745         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13746     }
13747     ts.declarationNameToString = declarationNameToString;
13748     function getNameFromIndexInfo(info) {
13749         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13750     }
13751     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13752     function isComputedNonLiteralName(name) {
13753         return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13754     }
13755     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13756     function getTextOfPropertyName(name) {
13757         switch (name.kind) {
13758             case 75 /* Identifier */:
13759             case 76 /* PrivateIdentifier */:
13760                 return name.escapedText;
13761             case 10 /* StringLiteral */:
13762             case 8 /* NumericLiteral */:
13763             case 14 /* NoSubstitutionTemplateLiteral */:
13764                 return ts.escapeLeadingUnderscores(name.text);
13765             case 154 /* ComputedPropertyName */:
13766                 if (isStringOrNumericLiteralLike(name.expression))
13767                     return ts.escapeLeadingUnderscores(name.expression.text);
13768                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13769             default:
13770                 return ts.Debug.assertNever(name);
13771         }
13772     }
13773     ts.getTextOfPropertyName = getTextOfPropertyName;
13774     function entityNameToString(name) {
13775         switch (name.kind) {
13776             case 104 /* ThisKeyword */:
13777                 return "this";
13778             case 76 /* PrivateIdentifier */:
13779             case 75 /* Identifier */:
13780                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13781             case 153 /* QualifiedName */:
13782                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13783             case 194 /* PropertyAccessExpression */:
13784                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13785                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13786                 }
13787                 else {
13788                     return ts.Debug.assertNever(name.name);
13789                 }
13790             default:
13791                 return ts.Debug.assertNever(name);
13792         }
13793     }
13794     ts.entityNameToString = entityNameToString;
13795     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13796         var sourceFile = getSourceFileOfNode(node);
13797         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13798     }
13799     ts.createDiagnosticForNode = createDiagnosticForNode;
13800     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13801         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13802         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13803     }
13804     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13805     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13806         var span = getErrorSpanForNode(sourceFile, node);
13807         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13808     }
13809     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13810     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13811         var sourceFile = getSourceFileOfNode(node);
13812         var span = getErrorSpanForNode(sourceFile, node);
13813         return {
13814             file: sourceFile,
13815             start: span.start,
13816             length: span.length,
13817             code: messageChain.code,
13818             category: messageChain.category,
13819             messageText: messageChain.next ? messageChain : messageChain.messageText,
13820             relatedInformation: relatedInformation
13821         };
13822     }
13823     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13824     function createDiagnosticForRange(sourceFile, range, message) {
13825         return {
13826             file: sourceFile,
13827             start: range.pos,
13828             length: range.end - range.pos,
13829             code: message.code,
13830             category: message.category,
13831             messageText: message.message,
13832         };
13833     }
13834     ts.createDiagnosticForRange = createDiagnosticForRange;
13835     function getSpanOfTokenAtPosition(sourceFile, pos) {
13836         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13837         scanner.scan();
13838         var start = scanner.getTokenPos();
13839         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13840     }
13841     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13842     function getErrorSpanForArrowFunction(sourceFile, node) {
13843         var pos = ts.skipTrivia(sourceFile.text, node.pos);
13844         if (node.body && node.body.kind === 223 /* Block */) {
13845             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13846             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13847             if (startLine < endLine) {
13848                 // The arrow function spans multiple lines,
13849                 // make the error span be the first line, inclusive.
13850                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13851             }
13852         }
13853         return ts.createTextSpanFromBounds(pos, node.end);
13854     }
13855     function getErrorSpanForNode(sourceFile, node) {
13856         var errorNode = node;
13857         switch (node.kind) {
13858             case 290 /* SourceFile */:
13859                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13860                 if (pos_1 === sourceFile.text.length) {
13861                     // file is empty - return span for the beginning of the file
13862                     return ts.createTextSpan(0, 0);
13863                 }
13864                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13865             // This list is a work in progress. Add missing node kinds to improve their error
13866             // spans.
13867             case 242 /* VariableDeclaration */:
13868             case 191 /* BindingElement */:
13869             case 245 /* ClassDeclaration */:
13870             case 214 /* ClassExpression */:
13871             case 246 /* InterfaceDeclaration */:
13872             case 249 /* ModuleDeclaration */:
13873             case 248 /* EnumDeclaration */:
13874             case 284 /* EnumMember */:
13875             case 244 /* FunctionDeclaration */:
13876             case 201 /* FunctionExpression */:
13877             case 161 /* MethodDeclaration */:
13878             case 163 /* GetAccessor */:
13879             case 164 /* SetAccessor */:
13880             case 247 /* TypeAliasDeclaration */:
13881             case 159 /* PropertyDeclaration */:
13882             case 158 /* PropertySignature */:
13883                 errorNode = node.name;
13884                 break;
13885             case 202 /* ArrowFunction */:
13886                 return getErrorSpanForArrowFunction(sourceFile, node);
13887             case 277 /* CaseClause */:
13888             case 278 /* DefaultClause */:
13889                 var start = ts.skipTrivia(sourceFile.text, node.pos);
13890                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13891                 return ts.createTextSpanFromBounds(start, end);
13892         }
13893         if (errorNode === undefined) {
13894             // If we don't have a better node, then just set the error on the first token of
13895             // construct.
13896             return getSpanOfTokenAtPosition(sourceFile, node.pos);
13897         }
13898         ts.Debug.assert(!ts.isJSDoc(errorNode));
13899         var isMissing = nodeIsMissing(errorNode);
13900         var pos = isMissing || ts.isJsxText(node)
13901             ? errorNode.pos
13902             : ts.skipTrivia(sourceFile.text, errorNode.pos);
13903         // These asserts should all be satisfied for a properly constructed `errorNode`.
13904         if (isMissing) {
13905             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13906             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13907         }
13908         else {
13909             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13910             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13911         }
13912         return ts.createTextSpanFromBounds(pos, errorNode.end);
13913     }
13914     ts.getErrorSpanForNode = getErrorSpanForNode;
13915     function isExternalOrCommonJsModule(file) {
13916         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13917     }
13918     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13919     function isJsonSourceFile(file) {
13920         return file.scriptKind === 6 /* JSON */;
13921     }
13922     ts.isJsonSourceFile = isJsonSourceFile;
13923     function isEnumConst(node) {
13924         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13925     }
13926     ts.isEnumConst = isEnumConst;
13927     function isDeclarationReadonly(declaration) {
13928         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13929     }
13930     ts.isDeclarationReadonly = isDeclarationReadonly;
13931     function isVarConst(node) {
13932         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13933     }
13934     ts.isVarConst = isVarConst;
13935     function isLet(node) {
13936         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13937     }
13938     ts.isLet = isLet;
13939     function isSuperCall(n) {
13940         return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
13941     }
13942     ts.isSuperCall = isSuperCall;
13943     function isImportCall(n) {
13944         return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
13945     }
13946     ts.isImportCall = isImportCall;
13947     function isImportMeta(n) {
13948         return ts.isMetaProperty(n)
13949             && n.keywordToken === 96 /* ImportKeyword */
13950             && n.name.escapedText === "meta";
13951     }
13952     ts.isImportMeta = isImportMeta;
13953     function isLiteralImportTypeNode(n) {
13954         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13955     }
13956     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13957     function isPrologueDirective(node) {
13958         return node.kind === 226 /* ExpressionStatement */
13959             && node.expression.kind === 10 /* StringLiteral */;
13960     }
13961     ts.isPrologueDirective = isPrologueDirective;
13962     function isCustomPrologue(node) {
13963         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13964     }
13965     ts.isCustomPrologue = isCustomPrologue;
13966     function isHoistedFunction(node) {
13967         return isCustomPrologue(node)
13968             && ts.isFunctionDeclaration(node);
13969     }
13970     ts.isHoistedFunction = isHoistedFunction;
13971     function isHoistedVariable(node) {
13972         return ts.isIdentifier(node.name)
13973             && !node.initializer;
13974     }
13975     function isHoistedVariableStatement(node) {
13976         return isCustomPrologue(node)
13977             && ts.isVariableStatement(node)
13978             && ts.every(node.declarationList.declarations, isHoistedVariable);
13979     }
13980     ts.isHoistedVariableStatement = isHoistedVariableStatement;
13981     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13982         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13983     }
13984     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13985     function getJSDocCommentRanges(node, text) {
13986         var commentRanges = (node.kind === 156 /* Parameter */ ||
13987             node.kind === 155 /* TypeParameter */ ||
13988             node.kind === 201 /* FunctionExpression */ ||
13989             node.kind === 202 /* ArrowFunction */ ||
13990             node.kind === 200 /* ParenthesizedExpression */) ?
13991             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13992             ts.getLeadingCommentRanges(text, node.pos);
13993         // True if the comment starts with '/**' but not if it is '/**/'
13994         return ts.filter(commentRanges, function (comment) {
13995             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13996                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13997                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13998         });
13999     }
14000     ts.getJSDocCommentRanges = getJSDocCommentRanges;
14001     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14002     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
14003     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14004     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
14005     function isPartOfTypeNode(node) {
14006         if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
14007             return true;
14008         }
14009         switch (node.kind) {
14010             case 125 /* AnyKeyword */:
14011             case 148 /* UnknownKeyword */:
14012             case 140 /* NumberKeyword */:
14013             case 151 /* BigIntKeyword */:
14014             case 143 /* StringKeyword */:
14015             case 128 /* BooleanKeyword */:
14016             case 144 /* SymbolKeyword */:
14017             case 141 /* ObjectKeyword */:
14018             case 146 /* UndefinedKeyword */:
14019             case 137 /* NeverKeyword */:
14020                 return true;
14021             case 110 /* VoidKeyword */:
14022                 return node.parent.kind !== 205 /* VoidExpression */;
14023             case 216 /* ExpressionWithTypeArguments */:
14024                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
14025             case 155 /* TypeParameter */:
14026                 return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
14027             // Identifiers and qualified names may be type nodes, depending on their context. Climb
14028             // above them to find the lowest container
14029             case 75 /* Identifier */:
14030                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
14031                 if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
14032                     node = node.parent;
14033                 }
14034                 else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
14035                     node = node.parent;
14036                 }
14037                 // At this point, node is either a qualified name or an identifier
14038                 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'.");
14039             // falls through
14040             case 153 /* QualifiedName */:
14041             case 194 /* PropertyAccessExpression */:
14042             case 104 /* ThisKeyword */: {
14043                 var parent = node.parent;
14044                 if (parent.kind === 172 /* TypeQuery */) {
14045                     return false;
14046                 }
14047                 if (parent.kind === 188 /* ImportType */) {
14048                     return !parent.isTypeOf;
14049                 }
14050                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
14051                 //
14052                 //     let a: A.B.C;
14053                 //
14054                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
14055                 // Only C and A.B.C are type nodes.
14056                 if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
14057                     return true;
14058                 }
14059                 switch (parent.kind) {
14060                     case 216 /* ExpressionWithTypeArguments */:
14061                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14062                     case 155 /* TypeParameter */:
14063                         return node === parent.constraint;
14064                     case 321 /* JSDocTemplateTag */:
14065                         return node === parent.constraint;
14066                     case 159 /* PropertyDeclaration */:
14067                     case 158 /* PropertySignature */:
14068                     case 156 /* Parameter */:
14069                     case 242 /* VariableDeclaration */:
14070                         return node === parent.type;
14071                     case 244 /* FunctionDeclaration */:
14072                     case 201 /* FunctionExpression */:
14073                     case 202 /* ArrowFunction */:
14074                     case 162 /* Constructor */:
14075                     case 161 /* MethodDeclaration */:
14076                     case 160 /* MethodSignature */:
14077                     case 163 /* GetAccessor */:
14078                     case 164 /* SetAccessor */:
14079                         return node === parent.type;
14080                     case 165 /* CallSignature */:
14081                     case 166 /* ConstructSignature */:
14082                     case 167 /* IndexSignature */:
14083                         return node === parent.type;
14084                     case 199 /* TypeAssertionExpression */:
14085                         return node === parent.type;
14086                     case 196 /* CallExpression */:
14087                     case 197 /* NewExpression */:
14088                         return ts.contains(parent.typeArguments, node);
14089                     case 198 /* TaggedTemplateExpression */:
14090                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
14091                         return false;
14092                 }
14093             }
14094         }
14095         return false;
14096     }
14097     ts.isPartOfTypeNode = isPartOfTypeNode;
14098     function isChildOfNodeWithKind(node, kind) {
14099         while (node) {
14100             if (node.kind === kind) {
14101                 return true;
14102             }
14103             node = node.parent;
14104         }
14105         return false;
14106     }
14107     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
14108     // Warning: This has the same semantics as the forEach family of functions,
14109     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
14110     function forEachReturnStatement(body, visitor) {
14111         return traverse(body);
14112         function traverse(node) {
14113             switch (node.kind) {
14114                 case 235 /* ReturnStatement */:
14115                     return visitor(node);
14116                 case 251 /* CaseBlock */:
14117                 case 223 /* Block */:
14118                 case 227 /* IfStatement */:
14119                 case 228 /* DoStatement */:
14120                 case 229 /* WhileStatement */:
14121                 case 230 /* ForStatement */:
14122                 case 231 /* ForInStatement */:
14123                 case 232 /* ForOfStatement */:
14124                 case 236 /* WithStatement */:
14125                 case 237 /* SwitchStatement */:
14126                 case 277 /* CaseClause */:
14127                 case 278 /* DefaultClause */:
14128                 case 238 /* LabeledStatement */:
14129                 case 240 /* TryStatement */:
14130                 case 280 /* CatchClause */:
14131                     return ts.forEachChild(node, traverse);
14132             }
14133         }
14134     }
14135     ts.forEachReturnStatement = forEachReturnStatement;
14136     function forEachYieldExpression(body, visitor) {
14137         return traverse(body);
14138         function traverse(node) {
14139             switch (node.kind) {
14140                 case 212 /* YieldExpression */:
14141                     visitor(node);
14142                     var operand = node.expression;
14143                     if (operand) {
14144                         traverse(operand);
14145                     }
14146                     return;
14147                 case 248 /* EnumDeclaration */:
14148                 case 246 /* InterfaceDeclaration */:
14149                 case 249 /* ModuleDeclaration */:
14150                 case 247 /* TypeAliasDeclaration */:
14151                     // These are not allowed inside a generator now, but eventually they may be allowed
14152                     // as local types. Regardless, skip them to avoid the work.
14153                     return;
14154                 default:
14155                     if (ts.isFunctionLike(node)) {
14156                         if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
14157                             // Note that we will not include methods/accessors of a class because they would require
14158                             // first descending into the class. This is by design.
14159                             traverse(node.name.expression);
14160                             return;
14161                         }
14162                     }
14163                     else if (!isPartOfTypeNode(node)) {
14164                         // This is the general case, which should include mostly expressions and statements.
14165                         // Also includes NodeArrays.
14166                         ts.forEachChild(node, traverse);
14167                     }
14168             }
14169         }
14170     }
14171     ts.forEachYieldExpression = forEachYieldExpression;
14172     /**
14173      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14174      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14175      *
14176      * @param node The type node.
14177      */
14178     function getRestParameterElementType(node) {
14179         if (node && node.kind === 174 /* ArrayType */) {
14180             return node.elementType;
14181         }
14182         else if (node && node.kind === 169 /* TypeReference */) {
14183             return ts.singleOrUndefined(node.typeArguments);
14184         }
14185         else {
14186             return undefined;
14187         }
14188     }
14189     ts.getRestParameterElementType = getRestParameterElementType;
14190     function getMembersOfDeclaration(node) {
14191         switch (node.kind) {
14192             case 246 /* InterfaceDeclaration */:
14193             case 245 /* ClassDeclaration */:
14194             case 214 /* ClassExpression */:
14195             case 173 /* TypeLiteral */:
14196                 return node.members;
14197             case 193 /* ObjectLiteralExpression */:
14198                 return node.properties;
14199         }
14200     }
14201     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14202     function isVariableLike(node) {
14203         if (node) {
14204             switch (node.kind) {
14205                 case 191 /* BindingElement */:
14206                 case 284 /* EnumMember */:
14207                 case 156 /* Parameter */:
14208                 case 281 /* PropertyAssignment */:
14209                 case 159 /* PropertyDeclaration */:
14210                 case 158 /* PropertySignature */:
14211                 case 282 /* ShorthandPropertyAssignment */:
14212                 case 242 /* VariableDeclaration */:
14213                     return true;
14214             }
14215         }
14216         return false;
14217     }
14218     ts.isVariableLike = isVariableLike;
14219     function isVariableLikeOrAccessor(node) {
14220         return isVariableLike(node) || ts.isAccessor(node);
14221     }
14222     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14223     function isVariableDeclarationInVariableStatement(node) {
14224         return node.parent.kind === 243 /* VariableDeclarationList */
14225             && node.parent.parent.kind === 225 /* VariableStatement */;
14226     }
14227     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14228     function isValidESSymbolDeclaration(node) {
14229         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14230             ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
14231                 ts.isPropertySignature(node) && hasReadonlyModifier(node);
14232     }
14233     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14234     function introducesArgumentsExoticObject(node) {
14235         switch (node.kind) {
14236             case 161 /* MethodDeclaration */:
14237             case 160 /* MethodSignature */:
14238             case 162 /* Constructor */:
14239             case 163 /* GetAccessor */:
14240             case 164 /* SetAccessor */:
14241             case 244 /* FunctionDeclaration */:
14242             case 201 /* FunctionExpression */:
14243                 return true;
14244         }
14245         return false;
14246     }
14247     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14248     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14249         while (true) {
14250             if (beforeUnwrapLabelCallback) {
14251                 beforeUnwrapLabelCallback(node);
14252             }
14253             if (node.statement.kind !== 238 /* LabeledStatement */) {
14254                 return node.statement;
14255             }
14256             node = node.statement;
14257         }
14258     }
14259     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14260     function isFunctionBlock(node) {
14261         return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
14262     }
14263     ts.isFunctionBlock = isFunctionBlock;
14264     function isObjectLiteralMethod(node) {
14265         return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
14266     }
14267     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14268     function isObjectLiteralOrClassExpressionMethod(node) {
14269         return node.kind === 161 /* MethodDeclaration */ &&
14270             (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
14271                 node.parent.kind === 214 /* ClassExpression */);
14272     }
14273     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14274     function isIdentifierTypePredicate(predicate) {
14275         return predicate && predicate.kind === 1 /* Identifier */;
14276     }
14277     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14278     function isThisTypePredicate(predicate) {
14279         return predicate && predicate.kind === 0 /* This */;
14280     }
14281     ts.isThisTypePredicate = isThisTypePredicate;
14282     function getPropertyAssignment(objectLiteral, key, key2) {
14283         return objectLiteral.properties.filter(function (property) {
14284             if (property.kind === 281 /* PropertyAssignment */) {
14285                 var propName = getTextOfPropertyName(property.name);
14286                 return key === propName || (!!key2 && key2 === propName);
14287             }
14288             return false;
14289         });
14290     }
14291     ts.getPropertyAssignment = getPropertyAssignment;
14292     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14293         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14294             var expression = tsConfigSourceFile.statements[0].expression;
14295             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14296         }
14297     }
14298     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14299     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14300         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14301             return ts.isArrayLiteralExpression(property.initializer) ?
14302                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14303                 undefined;
14304         });
14305     }
14306     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14307     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14308         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14309         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14310     }
14311     ts.getTsConfigPropArray = getTsConfigPropArray;
14312     function getContainingFunction(node) {
14313         return findAncestor(node.parent, ts.isFunctionLike);
14314     }
14315     ts.getContainingFunction = getContainingFunction;
14316     function getContainingFunctionDeclaration(node) {
14317         return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14318     }
14319     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14320     function getContainingClass(node) {
14321         return findAncestor(node.parent, ts.isClassLike);
14322     }
14323     ts.getContainingClass = getContainingClass;
14324     function getThisContainer(node, includeArrowFunctions) {
14325         ts.Debug.assert(node.kind !== 290 /* SourceFile */);
14326         while (true) {
14327             node = node.parent;
14328             if (!node) {
14329                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14330             }
14331             switch (node.kind) {
14332                 case 154 /* ComputedPropertyName */:
14333                     // If the grandparent node is an object literal (as opposed to a class),
14334                     // then the computed property is not a 'this' container.
14335                     // A computed property name in a class needs to be a this container
14336                     // so that we can error on it.
14337                     if (ts.isClassLike(node.parent.parent)) {
14338                         return node;
14339                     }
14340                     // If this is a computed property, then the parent should not
14341                     // make it a this container. The parent might be a property
14342                     // in an object literal, like a method or accessor. But in order for
14343                     // such a parent to be a this container, the reference must be in
14344                     // the *body* of the container.
14345                     node = node.parent;
14346                     break;
14347                 case 157 /* Decorator */:
14348                     // Decorators are always applied outside of the body of a class or method.
14349                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14350                         // If the decorator's parent is a Parameter, we resolve the this container from
14351                         // the grandparent class declaration.
14352                         node = node.parent.parent;
14353                     }
14354                     else if (ts.isClassElement(node.parent)) {
14355                         // If the decorator's parent is a class element, we resolve the 'this' container
14356                         // from the parent class declaration.
14357                         node = node.parent;
14358                     }
14359                     break;
14360                 case 202 /* ArrowFunction */:
14361                     if (!includeArrowFunctions) {
14362                         continue;
14363                     }
14364                 // falls through
14365                 case 244 /* FunctionDeclaration */:
14366                 case 201 /* FunctionExpression */:
14367                 case 249 /* ModuleDeclaration */:
14368                 case 159 /* PropertyDeclaration */:
14369                 case 158 /* PropertySignature */:
14370                 case 161 /* MethodDeclaration */:
14371                 case 160 /* MethodSignature */:
14372                 case 162 /* Constructor */:
14373                 case 163 /* GetAccessor */:
14374                 case 164 /* SetAccessor */:
14375                 case 165 /* CallSignature */:
14376                 case 166 /* ConstructSignature */:
14377                 case 167 /* IndexSignature */:
14378                 case 248 /* EnumDeclaration */:
14379                 case 290 /* SourceFile */:
14380                     return node;
14381             }
14382         }
14383     }
14384     ts.getThisContainer = getThisContainer;
14385     function getNewTargetContainer(node) {
14386         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14387         if (container) {
14388             switch (container.kind) {
14389                 case 162 /* Constructor */:
14390                 case 244 /* FunctionDeclaration */:
14391                 case 201 /* FunctionExpression */:
14392                     return container;
14393             }
14394         }
14395         return undefined;
14396     }
14397     ts.getNewTargetContainer = getNewTargetContainer;
14398     /**
14399      * Given an super call/property node, returns the closest node where
14400      * - a super call/property access is legal in the node and not legal in the parent node the node.
14401      *   i.e. super call is legal in constructor but not legal in the class body.
14402      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14403      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14404      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14405      */
14406     function getSuperContainer(node, stopOnFunctions) {
14407         while (true) {
14408             node = node.parent;
14409             if (!node) {
14410                 return node;
14411             }
14412             switch (node.kind) {
14413                 case 154 /* ComputedPropertyName */:
14414                     node = node.parent;
14415                     break;
14416                 case 244 /* FunctionDeclaration */:
14417                 case 201 /* FunctionExpression */:
14418                 case 202 /* ArrowFunction */:
14419                     if (!stopOnFunctions) {
14420                         continue;
14421                     }
14422                 // falls through
14423                 case 159 /* PropertyDeclaration */:
14424                 case 158 /* PropertySignature */:
14425                 case 161 /* MethodDeclaration */:
14426                 case 160 /* MethodSignature */:
14427                 case 162 /* Constructor */:
14428                 case 163 /* GetAccessor */:
14429                 case 164 /* SetAccessor */:
14430                     return node;
14431                 case 157 /* Decorator */:
14432                     // Decorators are always applied outside of the body of a class or method.
14433                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14434                         // If the decorator's parent is a Parameter, we resolve the this container from
14435                         // the grandparent class declaration.
14436                         node = node.parent.parent;
14437                     }
14438                     else if (ts.isClassElement(node.parent)) {
14439                         // If the decorator's parent is a class element, we resolve the 'this' container
14440                         // from the parent class declaration.
14441                         node = node.parent;
14442                     }
14443                     break;
14444             }
14445         }
14446     }
14447     ts.getSuperContainer = getSuperContainer;
14448     function getImmediatelyInvokedFunctionExpression(func) {
14449         if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
14450             var prev = func;
14451             var parent = func.parent;
14452             while (parent.kind === 200 /* ParenthesizedExpression */) {
14453                 prev = parent;
14454                 parent = parent.parent;
14455             }
14456             if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
14457                 return parent;
14458             }
14459         }
14460     }
14461     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14462     function isSuperOrSuperProperty(node) {
14463         return node.kind === 102 /* SuperKeyword */
14464             || isSuperProperty(node);
14465     }
14466     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14467     /**
14468      * Determines whether a node is a property or element access expression for `super`.
14469      */
14470     function isSuperProperty(node) {
14471         var kind = node.kind;
14472         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14473             && node.expression.kind === 102 /* SuperKeyword */;
14474     }
14475     ts.isSuperProperty = isSuperProperty;
14476     /**
14477      * Determines whether a node is a property or element access expression for `this`.
14478      */
14479     function isThisProperty(node) {
14480         var kind = node.kind;
14481         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14482             && node.expression.kind === 104 /* ThisKeyword */;
14483     }
14484     ts.isThisProperty = isThisProperty;
14485     function getEntityNameFromTypeNode(node) {
14486         switch (node.kind) {
14487             case 169 /* TypeReference */:
14488                 return node.typeName;
14489             case 216 /* ExpressionWithTypeArguments */:
14490                 return isEntityNameExpression(node.expression)
14491                     ? node.expression
14492                     : undefined;
14493             case 75 /* Identifier */:
14494             case 153 /* QualifiedName */:
14495                 return node;
14496         }
14497         return undefined;
14498     }
14499     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14500     function getInvokedExpression(node) {
14501         switch (node.kind) {
14502             case 198 /* TaggedTemplateExpression */:
14503                 return node.tag;
14504             case 268 /* JsxOpeningElement */:
14505             case 267 /* JsxSelfClosingElement */:
14506                 return node.tagName;
14507             default:
14508                 return node.expression;
14509         }
14510     }
14511     ts.getInvokedExpression = getInvokedExpression;
14512     function nodeCanBeDecorated(node, parent, grandparent) {
14513         // private names cannot be used with decorators yet
14514         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14515             return false;
14516         }
14517         switch (node.kind) {
14518             case 245 /* ClassDeclaration */:
14519                 // classes are valid targets
14520                 return true;
14521             case 159 /* PropertyDeclaration */:
14522                 // property declarations are valid if their parent is a class declaration.
14523                 return parent.kind === 245 /* ClassDeclaration */;
14524             case 163 /* GetAccessor */:
14525             case 164 /* SetAccessor */:
14526             case 161 /* MethodDeclaration */:
14527                 // if this method has a body and its parent is a class declaration, this is a valid target.
14528                 return node.body !== undefined
14529                     && parent.kind === 245 /* ClassDeclaration */;
14530             case 156 /* Parameter */:
14531                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14532                 return parent.body !== undefined
14533                     && (parent.kind === 162 /* Constructor */
14534                         || parent.kind === 161 /* MethodDeclaration */
14535                         || parent.kind === 164 /* SetAccessor */)
14536                     && grandparent.kind === 245 /* ClassDeclaration */;
14537         }
14538         return false;
14539     }
14540     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14541     function nodeIsDecorated(node, parent, grandparent) {
14542         return node.decorators !== undefined
14543             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14544     }
14545     ts.nodeIsDecorated = nodeIsDecorated;
14546     function nodeOrChildIsDecorated(node, parent, grandparent) {
14547         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14548     }
14549     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14550     function childIsDecorated(node, parent) {
14551         switch (node.kind) {
14552             case 245 /* ClassDeclaration */:
14553                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14554             case 161 /* MethodDeclaration */:
14555             case 164 /* SetAccessor */:
14556                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14557             default:
14558                 return false;
14559         }
14560     }
14561     ts.childIsDecorated = childIsDecorated;
14562     function isJSXTagName(node) {
14563         var parent = node.parent;
14564         if (parent.kind === 268 /* JsxOpeningElement */ ||
14565             parent.kind === 267 /* JsxSelfClosingElement */ ||
14566             parent.kind === 269 /* JsxClosingElement */) {
14567             return parent.tagName === node;
14568         }
14569         return false;
14570     }
14571     ts.isJSXTagName = isJSXTagName;
14572     function isExpressionNode(node) {
14573         switch (node.kind) {
14574             case 102 /* SuperKeyword */:
14575             case 100 /* NullKeyword */:
14576             case 106 /* TrueKeyword */:
14577             case 91 /* FalseKeyword */:
14578             case 13 /* RegularExpressionLiteral */:
14579             case 192 /* ArrayLiteralExpression */:
14580             case 193 /* ObjectLiteralExpression */:
14581             case 194 /* PropertyAccessExpression */:
14582             case 195 /* ElementAccessExpression */:
14583             case 196 /* CallExpression */:
14584             case 197 /* NewExpression */:
14585             case 198 /* TaggedTemplateExpression */:
14586             case 217 /* AsExpression */:
14587             case 199 /* TypeAssertionExpression */:
14588             case 218 /* NonNullExpression */:
14589             case 200 /* ParenthesizedExpression */:
14590             case 201 /* FunctionExpression */:
14591             case 214 /* ClassExpression */:
14592             case 202 /* ArrowFunction */:
14593             case 205 /* VoidExpression */:
14594             case 203 /* DeleteExpression */:
14595             case 204 /* TypeOfExpression */:
14596             case 207 /* PrefixUnaryExpression */:
14597             case 208 /* PostfixUnaryExpression */:
14598             case 209 /* BinaryExpression */:
14599             case 210 /* ConditionalExpression */:
14600             case 213 /* SpreadElement */:
14601             case 211 /* TemplateExpression */:
14602             case 215 /* OmittedExpression */:
14603             case 266 /* JsxElement */:
14604             case 267 /* JsxSelfClosingElement */:
14605             case 270 /* JsxFragment */:
14606             case 212 /* YieldExpression */:
14607             case 206 /* AwaitExpression */:
14608             case 219 /* MetaProperty */:
14609                 return true;
14610             case 153 /* QualifiedName */:
14611                 while (node.parent.kind === 153 /* QualifiedName */) {
14612                     node = node.parent;
14613                 }
14614                 return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
14615             case 75 /* Identifier */:
14616                 if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
14617                     return true;
14618                 }
14619             // falls through
14620             case 8 /* NumericLiteral */:
14621             case 9 /* BigIntLiteral */:
14622             case 10 /* StringLiteral */:
14623             case 14 /* NoSubstitutionTemplateLiteral */:
14624             case 104 /* ThisKeyword */:
14625                 return isInExpressionContext(node);
14626             default:
14627                 return false;
14628         }
14629     }
14630     ts.isExpressionNode = isExpressionNode;
14631     function isInExpressionContext(node) {
14632         var parent = node.parent;
14633         switch (parent.kind) {
14634             case 242 /* VariableDeclaration */:
14635             case 156 /* Parameter */:
14636             case 159 /* PropertyDeclaration */:
14637             case 158 /* PropertySignature */:
14638             case 284 /* EnumMember */:
14639             case 281 /* PropertyAssignment */:
14640             case 191 /* BindingElement */:
14641                 return parent.initializer === node;
14642             case 226 /* ExpressionStatement */:
14643             case 227 /* IfStatement */:
14644             case 228 /* DoStatement */:
14645             case 229 /* WhileStatement */:
14646             case 235 /* ReturnStatement */:
14647             case 236 /* WithStatement */:
14648             case 237 /* SwitchStatement */:
14649             case 277 /* CaseClause */:
14650             case 239 /* ThrowStatement */:
14651                 return parent.expression === node;
14652             case 230 /* ForStatement */:
14653                 var forStatement = parent;
14654                 return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14655                     forStatement.condition === node ||
14656                     forStatement.incrementor === node;
14657             case 231 /* ForInStatement */:
14658             case 232 /* ForOfStatement */:
14659                 var forInStatement = parent;
14660                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14661                     forInStatement.expression === node;
14662             case 199 /* TypeAssertionExpression */:
14663             case 217 /* AsExpression */:
14664                 return node === parent.expression;
14665             case 221 /* TemplateSpan */:
14666                 return node === parent.expression;
14667             case 154 /* ComputedPropertyName */:
14668                 return node === parent.expression;
14669             case 157 /* Decorator */:
14670             case 276 /* JsxExpression */:
14671             case 275 /* JsxSpreadAttribute */:
14672             case 283 /* SpreadAssignment */:
14673                 return true;
14674             case 216 /* ExpressionWithTypeArguments */:
14675                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14676             case 282 /* ShorthandPropertyAssignment */:
14677                 return parent.objectAssignmentInitializer === node;
14678             default:
14679                 return isExpressionNode(parent);
14680         }
14681     }
14682     ts.isInExpressionContext = isInExpressionContext;
14683     function isPartOfTypeQuery(node) {
14684         while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
14685             node = node.parent;
14686         }
14687         return node.kind === 172 /* TypeQuery */;
14688     }
14689     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14690     function isExternalModuleImportEqualsDeclaration(node) {
14691         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
14692     }
14693     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14694     function getExternalModuleImportEqualsDeclarationExpression(node) {
14695         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14696         return node.moduleReference.expression;
14697     }
14698     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14699     function isInternalModuleImportEqualsDeclaration(node) {
14700         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
14701     }
14702     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14703     function isSourceFileJS(file) {
14704         return isInJSFile(file);
14705     }
14706     ts.isSourceFileJS = isSourceFileJS;
14707     function isSourceFileNotJS(file) {
14708         return !isInJSFile(file);
14709     }
14710     ts.isSourceFileNotJS = isSourceFileNotJS;
14711     function isInJSFile(node) {
14712         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14713     }
14714     ts.isInJSFile = isInJSFile;
14715     function isInJsonFile(node) {
14716         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14717     }
14718     ts.isInJsonFile = isInJsonFile;
14719     function isSourceFileNotJson(file) {
14720         return !isJsonSourceFile(file);
14721     }
14722     ts.isSourceFileNotJson = isSourceFileNotJson;
14723     function isInJSDoc(node) {
14724         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14725     }
14726     ts.isInJSDoc = isInJSDoc;
14727     function isJSDocIndexSignature(node) {
14728         return ts.isTypeReferenceNode(node) &&
14729             ts.isIdentifier(node.typeName) &&
14730             node.typeName.escapedText === "Object" &&
14731             node.typeArguments && node.typeArguments.length === 2 &&
14732             (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
14733     }
14734     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14735     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14736         if (callExpression.kind !== 196 /* CallExpression */) {
14737             return false;
14738         }
14739         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14740         if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
14741             return false;
14742         }
14743         if (args.length !== 1) {
14744             return false;
14745         }
14746         var arg = args[0];
14747         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14748     }
14749     ts.isRequireCall = isRequireCall;
14750     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14751         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14752     }
14753     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14754     function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
14755         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14756         return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14757     }
14758     ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
14759     function isSingleOrDoubleQuote(charCode) {
14760         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14761     }
14762     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14763     function isStringDoubleQuoted(str, sourceFile) {
14764         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14765     }
14766     ts.isStringDoubleQuoted = isStringDoubleQuoted;
14767     function getDeclarationOfExpando(node) {
14768         if (!node.parent) {
14769             return undefined;
14770         }
14771         var name;
14772         var decl;
14773         if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14774             if (!isInJSFile(node) && !isVarConst(node.parent)) {
14775                 return undefined;
14776             }
14777             name = node.parent.name;
14778             decl = node.parent;
14779         }
14780         else if (ts.isBinaryExpression(node.parent)) {
14781             var parentNode = node.parent;
14782             var parentNodeOperator = node.parent.operatorToken.kind;
14783             if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14784                 name = parentNode.left;
14785                 decl = name;
14786             }
14787             else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14788                 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14789                     name = parentNode.parent.name;
14790                     decl = parentNode.parent;
14791                 }
14792                 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14793                     name = parentNode.parent.left;
14794                     decl = name;
14795                 }
14796                 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14797                     return undefined;
14798                 }
14799             }
14800         }
14801         if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14802             return undefined;
14803         }
14804         return decl;
14805     }
14806     ts.getDeclarationOfExpando = getDeclarationOfExpando;
14807     function isAssignmentDeclaration(decl) {
14808         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14809     }
14810     ts.isAssignmentDeclaration = isAssignmentDeclaration;
14811     /** Get the initializer, taking into account defaulted Javascript initializers */
14812     function getEffectiveInitializer(node) {
14813         if (isInJSFile(node) && node.initializer &&
14814             ts.isBinaryExpression(node.initializer) &&
14815             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14816             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14817             return node.initializer.right;
14818         }
14819         return node.initializer;
14820     }
14821     ts.getEffectiveInitializer = getEffectiveInitializer;
14822     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14823     function getDeclaredExpandoInitializer(node) {
14824         var init = getEffectiveInitializer(node);
14825         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14826     }
14827     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14828     function hasExpandoValueProperty(node, isPrototypeAssignment) {
14829         return ts.forEach(node.properties, function (p) {
14830             return ts.isPropertyAssignment(p) &&
14831                 ts.isIdentifier(p.name) &&
14832                 p.name.escapedText === "value" &&
14833                 p.initializer &&
14834                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14835         });
14836     }
14837     /**
14838      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14839      * We treat the right hand side of assignments with container-like initalizers as declarations.
14840      */
14841     function getAssignedExpandoInitializer(node) {
14842         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14843             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14844             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14845                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14846         }
14847         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14848             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14849             if (result) {
14850                 return result;
14851             }
14852         }
14853     }
14854     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14855     /**
14856      * Recognized expando initializers are:
14857      * 1. (function() {})() -- IIFEs
14858      * 2. function() { } -- Function expressions
14859      * 3. class { } -- Class expressions
14860      * 4. {} -- Empty object literals
14861      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14862      *
14863      * This function returns the provided initializer, or undefined if it is not valid.
14864      */
14865     function getExpandoInitializer(initializer, isPrototypeAssignment) {
14866         if (ts.isCallExpression(initializer)) {
14867             var e = skipParentheses(initializer.expression);
14868             return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
14869         }
14870         if (initializer.kind === 201 /* FunctionExpression */ ||
14871             initializer.kind === 214 /* ClassExpression */ ||
14872             initializer.kind === 202 /* ArrowFunction */) {
14873             return initializer;
14874         }
14875         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14876             return initializer;
14877         }
14878     }
14879     ts.getExpandoInitializer = getExpandoInitializer;
14880     /**
14881      * A defaulted expando initializer matches the pattern
14882      * `Lhs = Lhs || ExpandoInitializer`
14883      * or `var Lhs = Lhs || ExpandoInitializer`
14884      *
14885      * The second Lhs is required to be the same as the first except that it may be prefixed with
14886      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14887      */
14888     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14889         var e = ts.isBinaryExpression(initializer)
14890             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14891             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14892         if (e && isSameEntityName(name, initializer.left)) {
14893             return e;
14894         }
14895     }
14896     function isDefaultedExpandoInitializer(node) {
14897         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14898             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14899                 undefined;
14900         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14901     }
14902     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14903     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14904     function getNameOfExpando(node) {
14905         if (ts.isBinaryExpression(node.parent)) {
14906             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14907             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14908                 return parent.left;
14909             }
14910         }
14911         else if (ts.isVariableDeclaration(node.parent)) {
14912             return node.parent.name;
14913         }
14914     }
14915     ts.getNameOfExpando = getNameOfExpando;
14916     /**
14917      * Is the 'declared' name the same as the one in the initializer?
14918      * @return true for identical entity names, as well as ones where the initializer is prefixed with
14919      * 'window', 'self' or 'global'. For example:
14920      *
14921      * var my = my || {}
14922      * var min = window.min || {}
14923      * my.app = self.my.app || class { }
14924      */
14925     function isSameEntityName(name, initializer) {
14926         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14927             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
14928         }
14929         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14930             (initializer.expression.kind === 104 /* ThisKeyword */ ||
14931                 ts.isIdentifier(initializer.expression) &&
14932                     (initializer.expression.escapedText === "window" ||
14933                         initializer.expression.escapedText === "self" ||
14934                         initializer.expression.escapedText === "global"))) {
14935             var nameOrArgument = getNameOrArgument(initializer);
14936             if (ts.isPrivateIdentifier(nameOrArgument)) {
14937                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14938             }
14939             return isSameEntityName(name, nameOrArgument);
14940         }
14941         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14942             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14943                 && isSameEntityName(name.expression, initializer.expression);
14944         }
14945         return false;
14946     }
14947     function getRightMostAssignedExpression(node) {
14948         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14949             node = node.right;
14950         }
14951         return node;
14952     }
14953     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14954     function isExportsIdentifier(node) {
14955         return ts.isIdentifier(node) && node.escapedText === "exports";
14956     }
14957     ts.isExportsIdentifier = isExportsIdentifier;
14958     function isModuleIdentifier(node) {
14959         return ts.isIdentifier(node) && node.escapedText === "module";
14960     }
14961     ts.isModuleIdentifier = isModuleIdentifier;
14962     function isModuleExportsAccessExpression(node) {
14963         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14964             && isModuleIdentifier(node.expression)
14965             && getElementOrPropertyAccessName(node) === "exports";
14966     }
14967     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14968     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14969     /// assignments we treat as special in the binder
14970     function getAssignmentDeclarationKind(expr) {
14971         var special = getAssignmentDeclarationKindWorker(expr);
14972         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14973     }
14974     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14975     function isBindableObjectDefinePropertyCall(expr) {
14976         return ts.length(expr.arguments) === 3 &&
14977             ts.isPropertyAccessExpression(expr.expression) &&
14978             ts.isIdentifier(expr.expression.expression) &&
14979             ts.idText(expr.expression.expression) === "Object" &&
14980             ts.idText(expr.expression.name) === "defineProperty" &&
14981             isStringOrNumericLiteralLike(expr.arguments[1]) &&
14982             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14983     }
14984     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14985     /** x.y OR x[0] */
14986     function isLiteralLikeAccess(node) {
14987         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14988     }
14989     ts.isLiteralLikeAccess = isLiteralLikeAccess;
14990     /** x[0] OR x['a'] OR x[Symbol.y] */
14991     function isLiteralLikeElementAccess(node) {
14992         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14993             isWellKnownSymbolSyntactically(node.argumentExpression));
14994     }
14995     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14996     /** Any series of property and element accesses. */
14997     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14998         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14999             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
15000     }
15001     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
15002     /** Any series of property and element accesses, ending in a literal element access */
15003     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
15004         return isLiteralLikeElementAccess(node)
15005             && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
15006                 isEntityNameExpression(node.expression) ||
15007                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
15008     }
15009     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
15010     function isBindableStaticNameExpression(node, excludeThisKeyword) {
15011         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
15012     }
15013     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
15014     function getNameOrArgument(expr) {
15015         if (ts.isPropertyAccessExpression(expr)) {
15016             return expr.name;
15017         }
15018         return expr.argumentExpression;
15019     }
15020     ts.getNameOrArgument = getNameOrArgument;
15021     function getAssignmentDeclarationKindWorker(expr) {
15022         if (ts.isCallExpression(expr)) {
15023             if (!isBindableObjectDefinePropertyCall(expr)) {
15024                 return 0 /* None */;
15025             }
15026             var entityName = expr.arguments[0];
15027             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
15028                 return 8 /* ObjectDefinePropertyExports */;
15029             }
15030             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
15031                 return 9 /* ObjectDefinePrototypeProperty */;
15032             }
15033             return 7 /* ObjectDefinePropertyValue */;
15034         }
15035         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
15036             return 0 /* None */;
15037         }
15038         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
15039             // F.prototype = { ... }
15040             return 6 /* Prototype */;
15041         }
15042         return getAssignmentDeclarationPropertyAccessKind(expr.left);
15043     }
15044     /**
15045      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
15046      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
15047      */
15048     /* @internal */
15049     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
15050         if (ts.isPropertyAccessExpression(node)) {
15051             return node.name;
15052         }
15053         var arg = skipParentheses(node.argumentExpression);
15054         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
15055             return arg;
15056         }
15057         return node;
15058     }
15059     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
15060     function getElementOrPropertyAccessName(node) {
15061         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
15062         if (name) {
15063             if (ts.isIdentifier(name)) {
15064                 return name.escapedText;
15065             }
15066             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
15067                 return ts.escapeLeadingUnderscores(name.text);
15068             }
15069         }
15070         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
15071             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
15072         }
15073         return undefined;
15074     }
15075     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
15076     function getAssignmentDeclarationPropertyAccessKind(lhs) {
15077         if (lhs.expression.kind === 104 /* ThisKeyword */) {
15078             return 4 /* ThisProperty */;
15079         }
15080         else if (isModuleExportsAccessExpression(lhs)) {
15081             // module.exports = expr
15082             return 2 /* ModuleExports */;
15083         }
15084         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
15085             if (isPrototypeAccess(lhs.expression)) {
15086                 // F.G....prototype.x = expr
15087                 return 3 /* PrototypeProperty */;
15088             }
15089             var nextToLast = lhs;
15090             while (!ts.isIdentifier(nextToLast.expression)) {
15091                 nextToLast = nextToLast.expression;
15092             }
15093             var id = nextToLast.expression;
15094             if ((id.escapedText === "exports" ||
15095                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
15096                 // ExportsProperty does not support binding with computed names
15097                 isBindableStaticAccessExpression(lhs)) {
15098                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
15099                 return 1 /* ExportsProperty */;
15100             }
15101             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
15102                 // F.G...x = expr
15103                 return 5 /* Property */;
15104             }
15105         }
15106         return 0 /* None */;
15107     }
15108     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
15109     function getInitializerOfBinaryExpression(expr) {
15110         while (ts.isBinaryExpression(expr.right)) {
15111             expr = expr.right;
15112         }
15113         return expr.right;
15114     }
15115     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
15116     function isPrototypePropertyAssignment(node) {
15117         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
15118     }
15119     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
15120     function isSpecialPropertyDeclaration(expr) {
15121         return isInJSFile(expr) &&
15122             expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
15123             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
15124             !!ts.getJSDocTypeTag(expr.parent);
15125     }
15126     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
15127     function setValueDeclaration(symbol, node) {
15128         var valueDeclaration = symbol.valueDeclaration;
15129         if (!valueDeclaration ||
15130             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
15131                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
15132             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
15133             // other kinds of value declarations take precedence over modules and assignment declarations
15134             symbol.valueDeclaration = node;
15135         }
15136     }
15137     ts.setValueDeclaration = setValueDeclaration;
15138     function isFunctionSymbol(symbol) {
15139         if (!symbol || !symbol.valueDeclaration) {
15140             return false;
15141         }
15142         var decl = symbol.valueDeclaration;
15143         return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
15144     }
15145     ts.isFunctionSymbol = isFunctionSymbol;
15146     function importFromModuleSpecifier(node) {
15147         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
15148     }
15149     ts.importFromModuleSpecifier = importFromModuleSpecifier;
15150     function tryGetImportFromModuleSpecifier(node) {
15151         switch (node.parent.kind) {
15152             case 254 /* ImportDeclaration */:
15153             case 260 /* ExportDeclaration */:
15154                 return node.parent;
15155             case 265 /* ExternalModuleReference */:
15156                 return node.parent.parent;
15157             case 196 /* CallExpression */:
15158                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15159             case 187 /* LiteralType */:
15160                 ts.Debug.assert(ts.isStringLiteral(node));
15161                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15162             default:
15163                 return undefined;
15164         }
15165     }
15166     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15167     function getExternalModuleName(node) {
15168         switch (node.kind) {
15169             case 254 /* ImportDeclaration */:
15170             case 260 /* ExportDeclaration */:
15171                 return node.moduleSpecifier;
15172             case 253 /* ImportEqualsDeclaration */:
15173                 return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15174             case 188 /* ImportType */:
15175                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15176             default:
15177                 return ts.Debug.assertNever(node);
15178         }
15179     }
15180     ts.getExternalModuleName = getExternalModuleName;
15181     function getNamespaceDeclarationNode(node) {
15182         switch (node.kind) {
15183             case 254 /* ImportDeclaration */:
15184                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15185             case 253 /* ImportEqualsDeclaration */:
15186                 return node;
15187             case 260 /* ExportDeclaration */:
15188                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15189             default:
15190                 return ts.Debug.assertNever(node);
15191         }
15192     }
15193     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15194     function isDefaultImport(node) {
15195         return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15196     }
15197     ts.isDefaultImport = isDefaultImport;
15198     function forEachImportClauseDeclaration(node, action) {
15199         if (node.name) {
15200             var result = action(node);
15201             if (result)
15202                 return result;
15203         }
15204         if (node.namedBindings) {
15205             var result = ts.isNamespaceImport(node.namedBindings)
15206                 ? action(node.namedBindings)
15207                 : ts.forEach(node.namedBindings.elements, action);
15208             if (result)
15209                 return result;
15210         }
15211     }
15212     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15213     function hasQuestionToken(node) {
15214         if (node) {
15215             switch (node.kind) {
15216                 case 156 /* Parameter */:
15217                 case 161 /* MethodDeclaration */:
15218                 case 160 /* MethodSignature */:
15219                 case 282 /* ShorthandPropertyAssignment */:
15220                 case 281 /* PropertyAssignment */:
15221                 case 159 /* PropertyDeclaration */:
15222                 case 158 /* PropertySignature */:
15223                     return node.questionToken !== undefined;
15224             }
15225         }
15226         return false;
15227     }
15228     ts.hasQuestionToken = hasQuestionToken;
15229     function isJSDocConstructSignature(node) {
15230         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15231         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15232         return !!name && name.escapedText === "new";
15233     }
15234     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15235     function isJSDocTypeAlias(node) {
15236         return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
15237     }
15238     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15239     function isTypeAlias(node) {
15240         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15241     }
15242     ts.isTypeAlias = isTypeAlias;
15243     function getSourceOfAssignment(node) {
15244         return ts.isExpressionStatement(node) &&
15245             ts.isBinaryExpression(node.expression) &&
15246             node.expression.operatorToken.kind === 62 /* EqualsToken */
15247             ? getRightMostAssignedExpression(node.expression)
15248             : undefined;
15249     }
15250     function getSourceOfDefaultedAssignment(node) {
15251         return ts.isExpressionStatement(node) &&
15252             ts.isBinaryExpression(node.expression) &&
15253             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15254             ts.isBinaryExpression(node.expression.right) &&
15255             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15256             ? node.expression.right.right
15257             : undefined;
15258     }
15259     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15260         switch (node.kind) {
15261             case 225 /* VariableStatement */:
15262                 var v = getSingleVariableOfVariableStatement(node);
15263                 return v && v.initializer;
15264             case 159 /* PropertyDeclaration */:
15265                 return node.initializer;
15266             case 281 /* PropertyAssignment */:
15267                 return node.initializer;
15268         }
15269     }
15270     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15271     function getSingleVariableOfVariableStatement(node) {
15272         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15273     }
15274     function getNestedModuleDeclaration(node) {
15275         return ts.isModuleDeclaration(node) &&
15276             node.body &&
15277             node.body.kind === 249 /* ModuleDeclaration */
15278             ? node.body
15279             : undefined;
15280     }
15281     function getJSDocCommentsAndTags(hostNode) {
15282         var result;
15283         // Pull parameter comments from declaring function as well
15284         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15285             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15286         }
15287         var node = hostNode;
15288         while (node && node.parent) {
15289             if (ts.hasJSDocNodes(node)) {
15290                 result = ts.append(result, ts.last(node.jsDoc));
15291             }
15292             if (node.kind === 156 /* Parameter */) {
15293                 result = ts.addRange(result, ts.getJSDocParameterTags(node));
15294                 break;
15295             }
15296             if (node.kind === 155 /* TypeParameter */) {
15297                 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
15298                 break;
15299             }
15300             node = getNextJSDocCommentLocation(node);
15301         }
15302         return result || ts.emptyArray;
15303     }
15304     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15305     function getNextJSDocCommentLocation(node) {
15306         var parent = node.parent;
15307         if (parent.kind === 281 /* PropertyAssignment */ ||
15308             parent.kind === 259 /* ExportAssignment */ ||
15309             parent.kind === 159 /* PropertyDeclaration */ ||
15310             parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
15311             getNestedModuleDeclaration(parent) ||
15312             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15313             return parent;
15314         }
15315         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15316         // /**
15317         //   * @param {number} name
15318         //   * @returns {number}
15319         //   */
15320         // var x = function(name) { return name.length; }
15321         else if (parent.parent &&
15322             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15323                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15324             return parent.parent;
15325         }
15326         else if (parent.parent && parent.parent.parent &&
15327             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15328                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15329                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15330             return parent.parent.parent;
15331         }
15332     }
15333     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15334     function getParameterSymbolFromJSDoc(node) {
15335         if (node.symbol) {
15336             return node.symbol;
15337         }
15338         if (!ts.isIdentifier(node.name)) {
15339             return undefined;
15340         }
15341         var name = node.name.escapedText;
15342         var decl = getHostSignatureFromJSDoc(node);
15343         if (!decl) {
15344             return undefined;
15345         }
15346         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
15347         return parameter && parameter.symbol;
15348     }
15349     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15350     function getHostSignatureFromJSDoc(node) {
15351         var host = getEffectiveJSDocHost(node);
15352         return host && ts.isFunctionLike(host) ? host : undefined;
15353     }
15354     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15355     function getEffectiveJSDocHost(node) {
15356         var host = getJSDocHost(node);
15357         var decl = getSourceOfDefaultedAssignment(host) ||
15358             getSourceOfAssignment(host) ||
15359             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15360             getSingleVariableOfVariableStatement(host) ||
15361             getNestedModuleDeclaration(host) ||
15362             host;
15363         return decl;
15364     }
15365     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15366     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15367     function getJSDocHost(node) {
15368         return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
15369     }
15370     ts.getJSDocHost = getJSDocHost;
15371     function getTypeParameterFromJsDoc(node) {
15372         var name = node.name.escapedText;
15373         var typeParameters = node.parent.parent.parent.typeParameters;
15374         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15375     }
15376     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15377     function hasRestParameter(s) {
15378         var last = ts.lastOrUndefined(s.parameters);
15379         return !!last && isRestParameter(last);
15380     }
15381     ts.hasRestParameter = hasRestParameter;
15382     function isRestParameter(node) {
15383         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15384         return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
15385     }
15386     ts.isRestParameter = isRestParameter;
15387     function hasTypeArguments(node) {
15388         return !!node.typeArguments;
15389     }
15390     ts.hasTypeArguments = hasTypeArguments;
15391     var AssignmentKind;
15392     (function (AssignmentKind) {
15393         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15394         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15395         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15396     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15397     function getAssignmentTargetKind(node) {
15398         var parent = node.parent;
15399         while (true) {
15400             switch (parent.kind) {
15401                 case 209 /* BinaryExpression */:
15402                     var binaryOperator = parent.operatorToken.kind;
15403                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15404                         binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
15405                         0 /* None */;
15406                 case 207 /* PrefixUnaryExpression */:
15407                 case 208 /* PostfixUnaryExpression */:
15408                     var unaryOperator = parent.operator;
15409                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15410                 case 231 /* ForInStatement */:
15411                 case 232 /* ForOfStatement */:
15412                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15413                 case 200 /* ParenthesizedExpression */:
15414                 case 192 /* ArrayLiteralExpression */:
15415                 case 213 /* SpreadElement */:
15416                 case 218 /* NonNullExpression */:
15417                     node = parent;
15418                     break;
15419                 case 282 /* ShorthandPropertyAssignment */:
15420                     if (parent.name !== node) {
15421                         return 0 /* None */;
15422                     }
15423                     node = parent.parent;
15424                     break;
15425                 case 281 /* PropertyAssignment */:
15426                     if (parent.name === node) {
15427                         return 0 /* None */;
15428                     }
15429                     node = parent.parent;
15430                     break;
15431                 default:
15432                     return 0 /* None */;
15433             }
15434             parent = node.parent;
15435         }
15436     }
15437     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15438     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15439     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15440     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15441     // (Note that `p` is not a target in the above examples, only `a`.)
15442     function isAssignmentTarget(node) {
15443         return getAssignmentTargetKind(node) !== 0 /* None */;
15444     }
15445     ts.isAssignmentTarget = isAssignmentTarget;
15446     /**
15447      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15448      * the same `var` declaration scope as the node's parent.
15449      */
15450     function isNodeWithPossibleHoistedDeclaration(node) {
15451         switch (node.kind) {
15452             case 223 /* Block */:
15453             case 225 /* VariableStatement */:
15454             case 236 /* WithStatement */:
15455             case 227 /* IfStatement */:
15456             case 237 /* SwitchStatement */:
15457             case 251 /* CaseBlock */:
15458             case 277 /* CaseClause */:
15459             case 278 /* DefaultClause */:
15460             case 238 /* LabeledStatement */:
15461             case 230 /* ForStatement */:
15462             case 231 /* ForInStatement */:
15463             case 232 /* ForOfStatement */:
15464             case 228 /* DoStatement */:
15465             case 229 /* WhileStatement */:
15466             case 240 /* TryStatement */:
15467             case 280 /* CatchClause */:
15468                 return true;
15469         }
15470         return false;
15471     }
15472     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15473     function isValueSignatureDeclaration(node) {
15474         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15475     }
15476     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15477     function walkUp(node, kind) {
15478         while (node && node.kind === kind) {
15479             node = node.parent;
15480         }
15481         return node;
15482     }
15483     function walkUpParenthesizedTypes(node) {
15484         return walkUp(node, 182 /* ParenthesizedType */);
15485     }
15486     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15487     function walkUpParenthesizedExpressions(node) {
15488         return walkUp(node, 200 /* ParenthesizedExpression */);
15489     }
15490     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15491     function skipParentheses(node) {
15492         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15493     }
15494     ts.skipParentheses = skipParentheses;
15495     function skipParenthesesUp(node) {
15496         while (node.kind === 200 /* ParenthesizedExpression */) {
15497             node = node.parent;
15498         }
15499         return node;
15500     }
15501     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15502     function isDeleteTarget(node) {
15503         if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
15504             return false;
15505         }
15506         node = walkUpParenthesizedExpressions(node.parent);
15507         return node && node.kind === 203 /* DeleteExpression */;
15508     }
15509     ts.isDeleteTarget = isDeleteTarget;
15510     function isNodeDescendantOf(node, ancestor) {
15511         while (node) {
15512             if (node === ancestor)
15513                 return true;
15514             node = node.parent;
15515         }
15516         return false;
15517     }
15518     ts.isNodeDescendantOf = isNodeDescendantOf;
15519     // True if `name` is the name of a declaration node
15520     function isDeclarationName(name) {
15521         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15522     }
15523     ts.isDeclarationName = isDeclarationName;
15524     // See GH#16030
15525     function getDeclarationFromName(name) {
15526         var parent = name.parent;
15527         switch (name.kind) {
15528             case 10 /* StringLiteral */:
15529             case 14 /* NoSubstitutionTemplateLiteral */:
15530             case 8 /* NumericLiteral */:
15531                 if (ts.isComputedPropertyName(parent))
15532                     return parent.parent;
15533             // falls through
15534             case 75 /* Identifier */:
15535                 if (ts.isDeclaration(parent)) {
15536                     return parent.name === name ? parent : undefined;
15537                 }
15538                 else if (ts.isQualifiedName(parent)) {
15539                     var tag = parent.parent;
15540                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15541                 }
15542                 else {
15543                     var binExp = parent.parent;
15544                     return ts.isBinaryExpression(binExp) &&
15545                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15546                         (binExp.left.symbol || binExp.symbol) &&
15547                         ts.getNameOfDeclaration(binExp) === name
15548                         ? binExp
15549                         : undefined;
15550                 }
15551             case 76 /* PrivateIdentifier */:
15552                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15553             default:
15554                 return undefined;
15555         }
15556     }
15557     ts.getDeclarationFromName = getDeclarationFromName;
15558     function isLiteralComputedPropertyDeclarationName(node) {
15559         return isStringOrNumericLiteralLike(node) &&
15560             node.parent.kind === 154 /* ComputedPropertyName */ &&
15561             ts.isDeclaration(node.parent.parent);
15562     }
15563     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15564     // Return true if the given identifier is classified as an IdentifierName
15565     function isIdentifierName(node) {
15566         var parent = node.parent;
15567         switch (parent.kind) {
15568             case 159 /* PropertyDeclaration */:
15569             case 158 /* PropertySignature */:
15570             case 161 /* MethodDeclaration */:
15571             case 160 /* MethodSignature */:
15572             case 163 /* GetAccessor */:
15573             case 164 /* SetAccessor */:
15574             case 284 /* EnumMember */:
15575             case 281 /* PropertyAssignment */:
15576             case 194 /* PropertyAccessExpression */:
15577                 // Name in member declaration or property name in property access
15578                 return parent.name === node;
15579             case 153 /* QualifiedName */:
15580                 // Name on right hand side of dot in a type query or type reference
15581                 if (parent.right === node) {
15582                     while (parent.kind === 153 /* QualifiedName */) {
15583                         parent = parent.parent;
15584                     }
15585                     return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
15586                 }
15587                 return false;
15588             case 191 /* BindingElement */:
15589             case 258 /* ImportSpecifier */:
15590                 // Property name in binding element or import specifier
15591                 return parent.propertyName === node;
15592             case 263 /* ExportSpecifier */:
15593             case 273 /* JsxAttribute */:
15594                 // Any name in an export specifier or JSX Attribute
15595                 return true;
15596         }
15597         return false;
15598     }
15599     ts.isIdentifierName = isIdentifierName;
15600     // An alias symbol is created by one of the following declarations:
15601     // import <symbol> = ...
15602     // import <symbol> from ...
15603     // import * as <symbol> from ...
15604     // import { x as <symbol> } from ...
15605     // export { x as <symbol> } from ...
15606     // export * as ns <symbol> from ...
15607     // export = <EntityNameExpression>
15608     // export default <EntityNameExpression>
15609     // module.exports = <EntityNameExpression>
15610     // {<Identifier>}
15611     // {name: <EntityNameExpression>}
15612     function isAliasSymbolDeclaration(node) {
15613         return node.kind === 253 /* ImportEqualsDeclaration */ ||
15614             node.kind === 252 /* NamespaceExportDeclaration */ ||
15615             node.kind === 255 /* ImportClause */ && !!node.name ||
15616             node.kind === 256 /* NamespaceImport */ ||
15617             node.kind === 262 /* NamespaceExport */ ||
15618             node.kind === 258 /* ImportSpecifier */ ||
15619             node.kind === 263 /* ExportSpecifier */ ||
15620             node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15621             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15622             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15623             node.kind === 282 /* ShorthandPropertyAssignment */ ||
15624             node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15625     }
15626     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15627     function getAliasDeclarationFromName(node) {
15628         switch (node.parent.kind) {
15629             case 255 /* ImportClause */:
15630             case 258 /* ImportSpecifier */:
15631             case 256 /* NamespaceImport */:
15632             case 263 /* ExportSpecifier */:
15633             case 259 /* ExportAssignment */:
15634             case 253 /* ImportEqualsDeclaration */:
15635                 return node.parent;
15636             case 153 /* QualifiedName */:
15637                 do {
15638                     node = node.parent;
15639                 } while (node.parent.kind === 153 /* QualifiedName */);
15640                 return getAliasDeclarationFromName(node);
15641         }
15642     }
15643     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15644     function isAliasableExpression(e) {
15645         return isEntityNameExpression(e) || ts.isClassExpression(e);
15646     }
15647     ts.isAliasableExpression = isAliasableExpression;
15648     function exportAssignmentIsAlias(node) {
15649         var e = getExportAssignmentExpression(node);
15650         return isAliasableExpression(e);
15651     }
15652     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15653     function getExportAssignmentExpression(node) {
15654         return ts.isExportAssignment(node) ? node.expression : node.right;
15655     }
15656     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15657     function getPropertyAssignmentAliasLikeExpression(node) {
15658         return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
15659             node.parent.right;
15660     }
15661     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15662     function getEffectiveBaseTypeNode(node) {
15663         var baseType = getClassExtendsHeritageElement(node);
15664         if (baseType && isInJSFile(node)) {
15665             // Prefer an @augments tag because it may have type parameters.
15666             var tag = ts.getJSDocAugmentsTag(node);
15667             if (tag) {
15668                 return tag.class;
15669             }
15670         }
15671         return baseType;
15672     }
15673     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15674     function getClassExtendsHeritageElement(node) {
15675         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15676         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15677     }
15678     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15679     function getEffectiveImplementsTypeNodes(node) {
15680         if (isInJSFile(node)) {
15681             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15682         }
15683         else {
15684             var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
15685             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15686         }
15687     }
15688     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15689     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15690     function getAllSuperTypeNodes(node) {
15691         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15692             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15693                 ts.emptyArray;
15694     }
15695     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15696     function getInterfaceBaseTypeNodes(node) {
15697         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15698         return heritageClause ? heritageClause.types : undefined;
15699     }
15700     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15701     function getHeritageClause(clauses, kind) {
15702         if (clauses) {
15703             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15704                 var clause = clauses_1[_i];
15705                 if (clause.token === kind) {
15706                     return clause;
15707                 }
15708             }
15709         }
15710         return undefined;
15711     }
15712     ts.getHeritageClause = getHeritageClause;
15713     function getAncestor(node, kind) {
15714         while (node) {
15715             if (node.kind === kind) {
15716                 return node;
15717             }
15718             node = node.parent;
15719         }
15720         return undefined;
15721     }
15722     ts.getAncestor = getAncestor;
15723     function isKeyword(token) {
15724         return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
15725     }
15726     ts.isKeyword = isKeyword;
15727     function isContextualKeyword(token) {
15728         return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
15729     }
15730     ts.isContextualKeyword = isContextualKeyword;
15731     function isNonContextualKeyword(token) {
15732         return isKeyword(token) && !isContextualKeyword(token);
15733     }
15734     ts.isNonContextualKeyword = isNonContextualKeyword;
15735     function isFutureReservedKeyword(token) {
15736         return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
15737     }
15738     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15739     function isStringANonContextualKeyword(name) {
15740         var token = ts.stringToToken(name);
15741         return token !== undefined && isNonContextualKeyword(token);
15742     }
15743     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15744     function isStringAKeyword(name) {
15745         var token = ts.stringToToken(name);
15746         return token !== undefined && isKeyword(token);
15747     }
15748     ts.isStringAKeyword = isStringAKeyword;
15749     function isIdentifierANonContextualKeyword(_a) {
15750         var originalKeywordKind = _a.originalKeywordKind;
15751         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15752     }
15753     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15754     function isTrivia(token) {
15755         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15756     }
15757     ts.isTrivia = isTrivia;
15758     var FunctionFlags;
15759     (function (FunctionFlags) {
15760         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15761         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15762         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15763         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15764         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15765     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15766     function getFunctionFlags(node) {
15767         if (!node) {
15768             return 4 /* Invalid */;
15769         }
15770         var flags = 0 /* Normal */;
15771         switch (node.kind) {
15772             case 244 /* FunctionDeclaration */:
15773             case 201 /* FunctionExpression */:
15774             case 161 /* MethodDeclaration */:
15775                 if (node.asteriskToken) {
15776                     flags |= 1 /* Generator */;
15777                 }
15778             // falls through
15779             case 202 /* ArrowFunction */:
15780                 if (hasModifier(node, 256 /* Async */)) {
15781                     flags |= 2 /* Async */;
15782                 }
15783                 break;
15784         }
15785         if (!node.body) {
15786             flags |= 4 /* Invalid */;
15787         }
15788         return flags;
15789     }
15790     ts.getFunctionFlags = getFunctionFlags;
15791     function isAsyncFunction(node) {
15792         switch (node.kind) {
15793             case 244 /* FunctionDeclaration */:
15794             case 201 /* FunctionExpression */:
15795             case 202 /* ArrowFunction */:
15796             case 161 /* MethodDeclaration */:
15797                 return node.body !== undefined
15798                     && node.asteriskToken === undefined
15799                     && hasModifier(node, 256 /* Async */);
15800         }
15801         return false;
15802     }
15803     ts.isAsyncFunction = isAsyncFunction;
15804     function isStringOrNumericLiteralLike(node) {
15805         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15806     }
15807     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15808     function isSignedNumericLiteral(node) {
15809         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15810     }
15811     ts.isSignedNumericLiteral = isSignedNumericLiteral;
15812     /**
15813      * A declaration has a dynamic name if all of the following are true:
15814      *   1. The declaration has a computed property name.
15815      *   2. The computed name is *not* expressed as a StringLiteral.
15816      *   3. The computed name is *not* expressed as a NumericLiteral.
15817      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
15818      *      immediately followed by a NumericLiteral.
15819      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15820      *      is a property of the Symbol constructor that denotes a built-in
15821      *      Symbol.
15822      */
15823     function hasDynamicName(declaration) {
15824         var name = ts.getNameOfDeclaration(declaration);
15825         return !!name && isDynamicName(name);
15826     }
15827     ts.hasDynamicName = hasDynamicName;
15828     function isDynamicName(name) {
15829         if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
15830             return false;
15831         }
15832         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
15833         return !isStringOrNumericLiteralLike(expr) &&
15834             !isSignedNumericLiteral(expr) &&
15835             !isWellKnownSymbolSyntactically(expr);
15836     }
15837     ts.isDynamicName = isDynamicName;
15838     /**
15839      * Checks if the expression is of the form:
15840      *    Symbol.name
15841      * where Symbol is literally the word "Symbol", and name is any identifierName
15842      */
15843     function isWellKnownSymbolSyntactically(node) {
15844         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15845     }
15846     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15847     function getPropertyNameForPropertyNameNode(name) {
15848         switch (name.kind) {
15849             case 75 /* Identifier */:
15850             case 76 /* PrivateIdentifier */:
15851                 return name.escapedText;
15852             case 10 /* StringLiteral */:
15853             case 8 /* NumericLiteral */:
15854                 return ts.escapeLeadingUnderscores(name.text);
15855             case 154 /* ComputedPropertyName */:
15856                 var nameExpression = name.expression;
15857                 if (isWellKnownSymbolSyntactically(nameExpression)) {
15858                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15859                 }
15860                 else if (isStringOrNumericLiteralLike(nameExpression)) {
15861                     return ts.escapeLeadingUnderscores(nameExpression.text);
15862                 }
15863                 return undefined;
15864             default:
15865                 return ts.Debug.assertNever(name);
15866         }
15867     }
15868     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15869     function isPropertyNameLiteral(node) {
15870         switch (node.kind) {
15871             case 75 /* Identifier */:
15872             case 10 /* StringLiteral */:
15873             case 14 /* NoSubstitutionTemplateLiteral */:
15874             case 8 /* NumericLiteral */:
15875                 return true;
15876             default:
15877                 return false;
15878         }
15879     }
15880     ts.isPropertyNameLiteral = isPropertyNameLiteral;
15881     function getTextOfIdentifierOrLiteral(node) {
15882         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15883     }
15884     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15885     function getEscapedTextOfIdentifierOrLiteral(node) {
15886         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15887     }
15888     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15889     function getPropertyNameForUniqueESSymbol(symbol) {
15890         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15891     }
15892     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15893     function getPropertyNameForKnownSymbolName(symbolName) {
15894         return "__@" + symbolName;
15895     }
15896     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15897     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15898         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15899     }
15900     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15901     function isKnownSymbol(symbol) {
15902         return ts.startsWith(symbol.escapedName, "__@");
15903     }
15904     ts.isKnownSymbol = isKnownSymbol;
15905     /**
15906      * Includes the word "Symbol" with unicode escapes
15907      */
15908     function isESSymbolIdentifier(node) {
15909         return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
15910     }
15911     ts.isESSymbolIdentifier = isESSymbolIdentifier;
15912     function isPushOrUnshiftIdentifier(node) {
15913         return node.escapedText === "push" || node.escapedText === "unshift";
15914     }
15915     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15916     function isParameterDeclaration(node) {
15917         var root = getRootDeclaration(node);
15918         return root.kind === 156 /* Parameter */;
15919     }
15920     ts.isParameterDeclaration = isParameterDeclaration;
15921     function getRootDeclaration(node) {
15922         while (node.kind === 191 /* BindingElement */) {
15923             node = node.parent.parent;
15924         }
15925         return node;
15926     }
15927     ts.getRootDeclaration = getRootDeclaration;
15928     function nodeStartsNewLexicalEnvironment(node) {
15929         var kind = node.kind;
15930         return kind === 162 /* Constructor */
15931             || kind === 201 /* FunctionExpression */
15932             || kind === 244 /* FunctionDeclaration */
15933             || kind === 202 /* ArrowFunction */
15934             || kind === 161 /* MethodDeclaration */
15935             || kind === 163 /* GetAccessor */
15936             || kind === 164 /* SetAccessor */
15937             || kind === 249 /* ModuleDeclaration */
15938             || kind === 290 /* SourceFile */;
15939     }
15940     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15941     function nodeIsSynthesized(range) {
15942         return positionIsSynthesized(range.pos)
15943             || positionIsSynthesized(range.end);
15944     }
15945     ts.nodeIsSynthesized = nodeIsSynthesized;
15946     function getOriginalSourceFile(sourceFile) {
15947         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15948     }
15949     ts.getOriginalSourceFile = getOriginalSourceFile;
15950     var Associativity;
15951     (function (Associativity) {
15952         Associativity[Associativity["Left"] = 0] = "Left";
15953         Associativity[Associativity["Right"] = 1] = "Right";
15954     })(Associativity = ts.Associativity || (ts.Associativity = {}));
15955     function getExpressionAssociativity(expression) {
15956         var operator = getOperator(expression);
15957         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15958         return getOperatorAssociativity(expression.kind, operator, hasArguments);
15959     }
15960     ts.getExpressionAssociativity = getExpressionAssociativity;
15961     function getOperatorAssociativity(kind, operator, hasArguments) {
15962         switch (kind) {
15963             case 197 /* NewExpression */:
15964                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15965             case 207 /* PrefixUnaryExpression */:
15966             case 204 /* TypeOfExpression */:
15967             case 205 /* VoidExpression */:
15968             case 203 /* DeleteExpression */:
15969             case 206 /* AwaitExpression */:
15970             case 210 /* ConditionalExpression */:
15971             case 212 /* YieldExpression */:
15972                 return 1 /* Right */;
15973             case 209 /* BinaryExpression */:
15974                 switch (operator) {
15975                     case 42 /* AsteriskAsteriskToken */:
15976                     case 62 /* EqualsToken */:
15977                     case 63 /* PlusEqualsToken */:
15978                     case 64 /* MinusEqualsToken */:
15979                     case 66 /* AsteriskAsteriskEqualsToken */:
15980                     case 65 /* AsteriskEqualsToken */:
15981                     case 67 /* SlashEqualsToken */:
15982                     case 68 /* PercentEqualsToken */:
15983                     case 69 /* LessThanLessThanEqualsToken */:
15984                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15985                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15986                     case 72 /* AmpersandEqualsToken */:
15987                     case 74 /* CaretEqualsToken */:
15988                     case 73 /* BarEqualsToken */:
15989                         return 1 /* Right */;
15990                 }
15991         }
15992         return 0 /* Left */;
15993     }
15994     ts.getOperatorAssociativity = getOperatorAssociativity;
15995     function getExpressionPrecedence(expression) {
15996         var operator = getOperator(expression);
15997         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15998         return getOperatorPrecedence(expression.kind, operator, hasArguments);
15999     }
16000     ts.getExpressionPrecedence = getExpressionPrecedence;
16001     function getOperator(expression) {
16002         if (expression.kind === 209 /* BinaryExpression */) {
16003             return expression.operatorToken.kind;
16004         }
16005         else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
16006             return expression.operator;
16007         }
16008         else {
16009             return expression.kind;
16010         }
16011     }
16012     ts.getOperator = getOperator;
16013     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
16014         switch (nodeKind) {
16015             case 327 /* CommaListExpression */:
16016                 return 0;
16017             case 213 /* SpreadElement */:
16018                 return 1;
16019             case 212 /* YieldExpression */:
16020                 return 2;
16021             case 210 /* ConditionalExpression */:
16022                 return 4;
16023             case 209 /* BinaryExpression */:
16024                 switch (operatorKind) {
16025                     case 27 /* CommaToken */:
16026                         return 0;
16027                     case 62 /* EqualsToken */:
16028                     case 63 /* PlusEqualsToken */:
16029                     case 64 /* MinusEqualsToken */:
16030                     case 66 /* AsteriskAsteriskEqualsToken */:
16031                     case 65 /* AsteriskEqualsToken */:
16032                     case 67 /* SlashEqualsToken */:
16033                     case 68 /* PercentEqualsToken */:
16034                     case 69 /* LessThanLessThanEqualsToken */:
16035                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16036                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16037                     case 72 /* AmpersandEqualsToken */:
16038                     case 74 /* CaretEqualsToken */:
16039                     case 73 /* BarEqualsToken */:
16040                         return 3;
16041                     default:
16042                         return getBinaryOperatorPrecedence(operatorKind);
16043                 }
16044             case 207 /* PrefixUnaryExpression */:
16045             case 204 /* TypeOfExpression */:
16046             case 205 /* VoidExpression */:
16047             case 203 /* DeleteExpression */:
16048             case 206 /* AwaitExpression */:
16049                 return 16;
16050             case 208 /* PostfixUnaryExpression */:
16051                 return 17;
16052             case 196 /* CallExpression */:
16053                 return 18;
16054             case 197 /* NewExpression */:
16055                 return hasArguments ? 19 : 18;
16056             case 198 /* TaggedTemplateExpression */:
16057             case 194 /* PropertyAccessExpression */:
16058             case 195 /* ElementAccessExpression */:
16059                 return 19;
16060             case 104 /* ThisKeyword */:
16061             case 102 /* SuperKeyword */:
16062             case 75 /* Identifier */:
16063             case 100 /* NullKeyword */:
16064             case 106 /* TrueKeyword */:
16065             case 91 /* FalseKeyword */:
16066             case 8 /* NumericLiteral */:
16067             case 9 /* BigIntLiteral */:
16068             case 10 /* StringLiteral */:
16069             case 192 /* ArrayLiteralExpression */:
16070             case 193 /* ObjectLiteralExpression */:
16071             case 201 /* FunctionExpression */:
16072             case 202 /* ArrowFunction */:
16073             case 214 /* ClassExpression */:
16074             case 266 /* JsxElement */:
16075             case 267 /* JsxSelfClosingElement */:
16076             case 270 /* JsxFragment */:
16077             case 13 /* RegularExpressionLiteral */:
16078             case 14 /* NoSubstitutionTemplateLiteral */:
16079             case 211 /* TemplateExpression */:
16080             case 200 /* ParenthesizedExpression */:
16081             case 215 /* OmittedExpression */:
16082                 return 20;
16083             default:
16084                 return -1;
16085         }
16086     }
16087     ts.getOperatorPrecedence = getOperatorPrecedence;
16088     function getBinaryOperatorPrecedence(kind) {
16089         switch (kind) {
16090             case 60 /* QuestionQuestionToken */:
16091                 return 4;
16092             case 56 /* BarBarToken */:
16093                 return 5;
16094             case 55 /* AmpersandAmpersandToken */:
16095                 return 6;
16096             case 51 /* BarToken */:
16097                 return 7;
16098             case 52 /* CaretToken */:
16099                 return 8;
16100             case 50 /* AmpersandToken */:
16101                 return 9;
16102             case 34 /* EqualsEqualsToken */:
16103             case 35 /* ExclamationEqualsToken */:
16104             case 36 /* EqualsEqualsEqualsToken */:
16105             case 37 /* ExclamationEqualsEqualsToken */:
16106                 return 10;
16107             case 29 /* LessThanToken */:
16108             case 31 /* GreaterThanToken */:
16109             case 32 /* LessThanEqualsToken */:
16110             case 33 /* GreaterThanEqualsToken */:
16111             case 98 /* InstanceOfKeyword */:
16112             case 97 /* InKeyword */:
16113             case 123 /* AsKeyword */:
16114                 return 11;
16115             case 47 /* LessThanLessThanToken */:
16116             case 48 /* GreaterThanGreaterThanToken */:
16117             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
16118                 return 12;
16119             case 39 /* PlusToken */:
16120             case 40 /* MinusToken */:
16121                 return 13;
16122             case 41 /* AsteriskToken */:
16123             case 43 /* SlashToken */:
16124             case 44 /* PercentToken */:
16125                 return 14;
16126             case 42 /* AsteriskAsteriskToken */:
16127                 return 15;
16128         }
16129         // -1 is lower than all other precedences.  Returning it will cause binary expression
16130         // parsing to stop.
16131         return -1;
16132     }
16133     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
16134     function createDiagnosticCollection() {
16135         var nonFileDiagnostics = []; // See GH#19873
16136         var filesWithDiagnostics = [];
16137         var fileDiagnostics = ts.createMap();
16138         var hasReadNonFileDiagnostics = false;
16139         return {
16140             add: add,
16141             lookup: lookup,
16142             getGlobalDiagnostics: getGlobalDiagnostics,
16143             getDiagnostics: getDiagnostics,
16144             reattachFileDiagnostics: reattachFileDiagnostics
16145         };
16146         function reattachFileDiagnostics(newFile) {
16147             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
16148         }
16149         function lookup(diagnostic) {
16150             var diagnostics;
16151             if (diagnostic.file) {
16152                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16153             }
16154             else {
16155                 diagnostics = nonFileDiagnostics;
16156             }
16157             if (!diagnostics) {
16158                 return undefined;
16159             }
16160             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16161             if (result >= 0) {
16162                 return diagnostics[result];
16163             }
16164             return undefined;
16165         }
16166         function add(diagnostic) {
16167             var diagnostics;
16168             if (diagnostic.file) {
16169                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16170                 if (!diagnostics) {
16171                     diagnostics = []; // See GH#19873
16172                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16173                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16174                 }
16175             }
16176             else {
16177                 // If we've already read the non-file diagnostics, do not modify the existing array.
16178                 if (hasReadNonFileDiagnostics) {
16179                     hasReadNonFileDiagnostics = false;
16180                     nonFileDiagnostics = nonFileDiagnostics.slice();
16181                 }
16182                 diagnostics = nonFileDiagnostics;
16183             }
16184             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16185         }
16186         function getGlobalDiagnostics() {
16187             hasReadNonFileDiagnostics = true;
16188             return nonFileDiagnostics;
16189         }
16190         function getDiagnostics(fileName) {
16191             if (fileName) {
16192                 return fileDiagnostics.get(fileName) || [];
16193             }
16194             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16195             if (!nonFileDiagnostics.length) {
16196                 return fileDiags;
16197             }
16198             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16199             return fileDiags;
16200         }
16201     }
16202     ts.createDiagnosticCollection = createDiagnosticCollection;
16203     var templateSubstitutionRegExp = /\$\{/g;
16204     function escapeTemplateSubstitution(str) {
16205         return str.replace(templateSubstitutionRegExp, "\\${");
16206     }
16207     /** @internal */
16208     function hasInvalidEscape(template) {
16209         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16210             ? template.templateFlags
16211             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16212     }
16213     ts.hasInvalidEscape = hasInvalidEscape;
16214     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16215     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16216     // the language service. These characters should be escaped when printing, and if any characters are added,
16217     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16218     // There is no reason for this other than that JSON.stringify does not handle it either.
16219     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16220     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16221     // Template strings should be preserved as much as possible
16222     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16223     var escapedCharsMap = ts.createMapFromTemplate({
16224         "\t": "\\t",
16225         "\v": "\\v",
16226         "\f": "\\f",
16227         "\b": "\\b",
16228         "\r": "\\r",
16229         "\n": "\\n",
16230         "\\": "\\\\",
16231         "\"": "\\\"",
16232         "\'": "\\\'",
16233         "\`": "\\\`",
16234         "\u2028": "\\u2028",
16235         "\u2029": "\\u2029",
16236         "\u0085": "\\u0085" // nextLine
16237     });
16238     function encodeUtf16EscapeSequence(charCode) {
16239         var hexCharCode = charCode.toString(16).toUpperCase();
16240         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16241         return "\\u" + paddedHexCode;
16242     }
16243     function getReplacement(c, offset, input) {
16244         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16245             var lookAhead = input.charCodeAt(offset + c.length);
16246             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16247                 // 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)
16248                 return "\\x00";
16249             }
16250             // Otherwise, keep printing a literal \0 for the null character
16251             return "\\0";
16252         }
16253         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16254     }
16255     /**
16256      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16257      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16258      * Note that this doesn't actually wrap the input in double quotes.
16259      */
16260     function escapeString(s, quoteChar) {
16261         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16262             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16263                 doubleQuoteEscapedCharsRegExp;
16264         return s.replace(escapedCharsRegExp, getReplacement);
16265     }
16266     ts.escapeString = escapeString;
16267     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16268     function escapeNonAsciiString(s, quoteChar) {
16269         s = escapeString(s, quoteChar);
16270         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16271         // Otherwise just return the original string.
16272         return nonAsciiCharacters.test(s) ?
16273             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16274             s;
16275     }
16276     ts.escapeNonAsciiString = escapeNonAsciiString;
16277     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16278     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16279     // the language service. These characters should be escaped when printing, and if any characters are added,
16280     // the map below must be updated.
16281     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16282     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16283     var jsxEscapedCharsMap = ts.createMapFromTemplate({
16284         "\"": "&quot;",
16285         "\'": "&apos;"
16286     });
16287     function encodeJsxCharacterEntity(charCode) {
16288         var hexCharCode = charCode.toString(16).toUpperCase();
16289         return "&#x" + hexCharCode + ";";
16290     }
16291     function getJsxAttributeStringReplacement(c) {
16292         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16293             return "&#0;";
16294         }
16295         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16296     }
16297     function escapeJsxAttributeString(s, quoteChar) {
16298         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16299             jsxDoubleQuoteEscapedCharsRegExp;
16300         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16301     }
16302     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16303     /**
16304      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16305      *
16306      * @return non-quoted string
16307      */
16308     function stripQuotes(name) {
16309         var length = name.length;
16310         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16311             return name.substring(1, length - 1);
16312         }
16313         return name;
16314     }
16315     ts.stripQuotes = stripQuotes;
16316     function isQuoteOrBacktick(charCode) {
16317         return charCode === 39 /* singleQuote */ ||
16318             charCode === 34 /* doubleQuote */ ||
16319             charCode === 96 /* backtick */;
16320     }
16321     function isIntrinsicJsxName(name) {
16322         var ch = name.charCodeAt(0);
16323         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16324     }
16325     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16326     var indentStrings = ["", "    "];
16327     function getIndentString(level) {
16328         if (indentStrings[level] === undefined) {
16329             indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16330         }
16331         return indentStrings[level];
16332     }
16333     ts.getIndentString = getIndentString;
16334     function getIndentSize() {
16335         return indentStrings[1].length;
16336     }
16337     ts.getIndentSize = getIndentSize;
16338     function createTextWriter(newLine) {
16339         var output;
16340         var indent;
16341         var lineStart;
16342         var lineCount;
16343         var linePos;
16344         var hasTrailingComment = false;
16345         function updateLineCountAndPosFor(s) {
16346             var lineStartsOfS = ts.computeLineStarts(s);
16347             if (lineStartsOfS.length > 1) {
16348                 lineCount = lineCount + lineStartsOfS.length - 1;
16349                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16350                 lineStart = (linePos - output.length) === 0;
16351             }
16352             else {
16353                 lineStart = false;
16354             }
16355         }
16356         function writeText(s) {
16357             if (s && s.length) {
16358                 if (lineStart) {
16359                     s = getIndentString(indent) + s;
16360                     lineStart = false;
16361                 }
16362                 output += s;
16363                 updateLineCountAndPosFor(s);
16364             }
16365         }
16366         function write(s) {
16367             if (s)
16368                 hasTrailingComment = false;
16369             writeText(s);
16370         }
16371         function writeComment(s) {
16372             if (s)
16373                 hasTrailingComment = true;
16374             writeText(s);
16375         }
16376         function reset() {
16377             output = "";
16378             indent = 0;
16379             lineStart = true;
16380             lineCount = 0;
16381             linePos = 0;
16382             hasTrailingComment = false;
16383         }
16384         function rawWrite(s) {
16385             if (s !== undefined) {
16386                 output += s;
16387                 updateLineCountAndPosFor(s);
16388                 hasTrailingComment = false;
16389             }
16390         }
16391         function writeLiteral(s) {
16392             if (s && s.length) {
16393                 write(s);
16394             }
16395         }
16396         function writeLine(force) {
16397             if (!lineStart || force) {
16398                 output += newLine;
16399                 lineCount++;
16400                 linePos = output.length;
16401                 lineStart = true;
16402                 hasTrailingComment = false;
16403             }
16404         }
16405         function getTextPosWithWriteLine() {
16406             return lineStart ? output.length : (output.length + newLine.length);
16407         }
16408         reset();
16409         return {
16410             write: write,
16411             rawWrite: rawWrite,
16412             writeLiteral: writeLiteral,
16413             writeLine: writeLine,
16414             increaseIndent: function () { indent++; },
16415             decreaseIndent: function () { indent--; },
16416             getIndent: function () { return indent; },
16417             getTextPos: function () { return output.length; },
16418             getLine: function () { return lineCount; },
16419             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16420             getText: function () { return output; },
16421             isAtStartOfLine: function () { return lineStart; },
16422             hasTrailingComment: function () { return hasTrailingComment; },
16423             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16424             clear: reset,
16425             reportInaccessibleThisError: ts.noop,
16426             reportPrivateInBaseOfClassExpression: ts.noop,
16427             reportInaccessibleUniqueSymbolError: ts.noop,
16428             trackSymbol: ts.noop,
16429             writeKeyword: write,
16430             writeOperator: write,
16431             writeParameter: write,
16432             writeProperty: write,
16433             writePunctuation: write,
16434             writeSpace: write,
16435             writeStringLiteral: write,
16436             writeSymbol: function (s, _) { return write(s); },
16437             writeTrailingSemicolon: write,
16438             writeComment: writeComment,
16439             getTextPosWithWriteLine: getTextPosWithWriteLine
16440         };
16441     }
16442     ts.createTextWriter = createTextWriter;
16443     function getTrailingSemicolonDeferringWriter(writer) {
16444         var pendingTrailingSemicolon = false;
16445         function commitPendingTrailingSemicolon() {
16446             if (pendingTrailingSemicolon) {
16447                 writer.writeTrailingSemicolon(";");
16448                 pendingTrailingSemicolon = false;
16449             }
16450         }
16451         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16452                 pendingTrailingSemicolon = true;
16453             },
16454             writeLiteral: function (s) {
16455                 commitPendingTrailingSemicolon();
16456                 writer.writeLiteral(s);
16457             },
16458             writeStringLiteral: function (s) {
16459                 commitPendingTrailingSemicolon();
16460                 writer.writeStringLiteral(s);
16461             },
16462             writeSymbol: function (s, sym) {
16463                 commitPendingTrailingSemicolon();
16464                 writer.writeSymbol(s, sym);
16465             },
16466             writePunctuation: function (s) {
16467                 commitPendingTrailingSemicolon();
16468                 writer.writePunctuation(s);
16469             },
16470             writeKeyword: function (s) {
16471                 commitPendingTrailingSemicolon();
16472                 writer.writeKeyword(s);
16473             },
16474             writeOperator: function (s) {
16475                 commitPendingTrailingSemicolon();
16476                 writer.writeOperator(s);
16477             },
16478             writeParameter: function (s) {
16479                 commitPendingTrailingSemicolon();
16480                 writer.writeParameter(s);
16481             },
16482             writeSpace: function (s) {
16483                 commitPendingTrailingSemicolon();
16484                 writer.writeSpace(s);
16485             },
16486             writeProperty: function (s) {
16487                 commitPendingTrailingSemicolon();
16488                 writer.writeProperty(s);
16489             },
16490             writeComment: function (s) {
16491                 commitPendingTrailingSemicolon();
16492                 writer.writeComment(s);
16493             },
16494             writeLine: function () {
16495                 commitPendingTrailingSemicolon();
16496                 writer.writeLine();
16497             },
16498             increaseIndent: function () {
16499                 commitPendingTrailingSemicolon();
16500                 writer.increaseIndent();
16501             },
16502             decreaseIndent: function () {
16503                 commitPendingTrailingSemicolon();
16504                 writer.decreaseIndent();
16505             } });
16506     }
16507     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16508     function hostUsesCaseSensitiveFileNames(host) {
16509         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16510     }
16511     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16512     function hostGetCanonicalFileName(host) {
16513         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16514     }
16515     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16516     function getResolvedExternalModuleName(host, file, referenceFile) {
16517         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16518     }
16519     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16520     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16521         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16522         if (!file || file.isDeclarationFile) {
16523             return undefined;
16524         }
16525         return getResolvedExternalModuleName(host, file);
16526     }
16527     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16528     /**
16529      * Resolves a local path to a path which is absolute to the base of the emit
16530      */
16531     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16532         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16533         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16534         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16535         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16536         var extensionless = removeFileExtension(relativePath);
16537         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16538     }
16539     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16540     function getOwnEmitOutputFilePath(fileName, host, extension) {
16541         var compilerOptions = host.getCompilerOptions();
16542         var emitOutputFilePathWithoutExtension;
16543         if (compilerOptions.outDir) {
16544             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16545         }
16546         else {
16547             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16548         }
16549         return emitOutputFilePathWithoutExtension + extension;
16550     }
16551     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16552     function getDeclarationEmitOutputFilePath(fileName, host) {
16553         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16554     }
16555     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16556     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16557         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16558         var path = outputDir
16559             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16560             : fileName;
16561         return removeFileExtension(path) + ".d.ts" /* Dts */;
16562     }
16563     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16564     /**
16565      * Gets the source files that are expected to have an emit output.
16566      *
16567      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16568      * transformations.
16569      *
16570      * @param host An EmitHost.
16571      * @param targetSourceFile An optional target source file to emit.
16572      */
16573     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16574         var options = host.getCompilerOptions();
16575         if (options.outFile || options.out) {
16576             var moduleKind = getEmitModuleKind(options);
16577             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16578             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16579             return ts.filter(host.getSourceFiles(), function (sourceFile) {
16580                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16581                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16582             });
16583         }
16584         else {
16585             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16586             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16587         }
16588     }
16589     ts.getSourceFilesToEmit = getSourceFilesToEmit;
16590     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16591     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16592         var options = host.getCompilerOptions();
16593         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16594             !sourceFile.isDeclarationFile &&
16595             !host.isSourceFileFromExternalLibrary(sourceFile) &&
16596             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16597             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16598     }
16599     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16600     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16601         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16602     }
16603     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16604     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16605         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16606         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16607         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16608         return ts.combinePaths(newDirPath, sourceFilePath);
16609     }
16610     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16611     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16612         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16613             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16614         }, sourceFiles);
16615     }
16616     ts.writeFile = writeFile;
16617     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16618         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16619             var parentDirectory = ts.getDirectoryPath(directoryPath);
16620             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16621             createDirectory(directoryPath);
16622         }
16623     }
16624     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16625         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
16626         // and fall back to creating it if the file write fails.
16627         try {
16628             writeFile(path, data, writeByteOrderMark);
16629         }
16630         catch (_a) {
16631             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16632             writeFile(path, data, writeByteOrderMark);
16633         }
16634     }
16635     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16636     function getLineOfLocalPosition(sourceFile, pos) {
16637         var lineStarts = ts.getLineStarts(sourceFile);
16638         return ts.computeLineOfPosition(lineStarts, pos);
16639     }
16640     ts.getLineOfLocalPosition = getLineOfLocalPosition;
16641     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16642         return ts.computeLineOfPosition(lineMap, pos);
16643     }
16644     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16645     function getFirstConstructorWithBody(node) {
16646         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16647     }
16648     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16649     function getSetAccessorValueParameter(accessor) {
16650         if (accessor && accessor.parameters.length > 0) {
16651             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16652             return accessor.parameters[hasThis ? 1 : 0];
16653         }
16654     }
16655     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16656     /** Get the type annotation for the value parameter. */
16657     function getSetAccessorTypeAnnotationNode(accessor) {
16658         var parameter = getSetAccessorValueParameter(accessor);
16659         return parameter && parameter.type;
16660     }
16661     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16662     function getThisParameter(signature) {
16663         // callback tags do not currently support this parameters
16664         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16665             var thisParameter = signature.parameters[0];
16666             if (parameterIsThisKeyword(thisParameter)) {
16667                 return thisParameter;
16668             }
16669         }
16670     }
16671     ts.getThisParameter = getThisParameter;
16672     function parameterIsThisKeyword(parameter) {
16673         return isThisIdentifier(parameter.name);
16674     }
16675     ts.parameterIsThisKeyword = parameterIsThisKeyword;
16676     function isThisIdentifier(node) {
16677         return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
16678     }
16679     ts.isThisIdentifier = isThisIdentifier;
16680     function identifierIsThisKeyword(id) {
16681         return id.originalKeywordKind === 104 /* ThisKeyword */;
16682     }
16683     ts.identifierIsThisKeyword = identifierIsThisKeyword;
16684     function getAllAccessorDeclarations(declarations, accessor) {
16685         // TODO: GH#18217
16686         var firstAccessor;
16687         var secondAccessor;
16688         var getAccessor;
16689         var setAccessor;
16690         if (hasDynamicName(accessor)) {
16691             firstAccessor = accessor;
16692             if (accessor.kind === 163 /* GetAccessor */) {
16693                 getAccessor = accessor;
16694             }
16695             else if (accessor.kind === 164 /* SetAccessor */) {
16696                 setAccessor = accessor;
16697             }
16698             else {
16699                 ts.Debug.fail("Accessor has wrong kind");
16700             }
16701         }
16702         else {
16703             ts.forEach(declarations, function (member) {
16704                 if (ts.isAccessor(member)
16705                     && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
16706                     var memberName = getPropertyNameForPropertyNameNode(member.name);
16707                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16708                     if (memberName === accessorName) {
16709                         if (!firstAccessor) {
16710                             firstAccessor = member;
16711                         }
16712                         else if (!secondAccessor) {
16713                             secondAccessor = member;
16714                         }
16715                         if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
16716                             // eslint-disable-next-line
16717                             getAccessor = member;
16718                         }
16719                         if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
16720                             // eslint-disable-next-line
16721                             setAccessor = member;
16722                         }
16723                     }
16724                 }
16725             });
16726         }
16727         return {
16728             firstAccessor: firstAccessor,
16729             secondAccessor: secondAccessor,
16730             getAccessor: getAccessor,
16731             setAccessor: setAccessor
16732         };
16733     }
16734     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16735     /**
16736      * Gets the effective type annotation of a variable, parameter, or property. If the node was
16737      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
16738      * functions only the JSDoc case.
16739      */
16740     function getEffectiveTypeAnnotationNode(node) {
16741         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16742             return undefined;
16743         var type = node.type;
16744         if (type || !isInJSFile(node))
16745             return type;
16746         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16747     }
16748     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16749     function getTypeAnnotationNode(node) {
16750         return node.type;
16751     }
16752     ts.getTypeAnnotationNode = getTypeAnnotationNode;
16753     /**
16754      * Gets the effective return type annotation of a signature. If the node was parsed in a
16755      * JavaScript file, gets the return type annotation from JSDoc.
16756      */
16757     function getEffectiveReturnTypeNode(node) {
16758         return ts.isJSDocSignature(node) ?
16759             node.type && node.type.typeExpression && node.type.typeExpression.type :
16760             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16761     }
16762     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16763     function getJSDocTypeParameterDeclarations(node) {
16764         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16765     }
16766     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16767     /** template tags are only available when a typedef isn't already using them */
16768     function isNonTypeAliasTemplate(tag) {
16769         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16770     }
16771     /**
16772      * Gets the effective type annotation of the value parameter of a set accessor. If the node
16773      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16774      */
16775     function getEffectiveSetAccessorTypeAnnotationNode(node) {
16776         var parameter = getSetAccessorValueParameter(node);
16777         return parameter && getEffectiveTypeAnnotationNode(parameter);
16778     }
16779     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16780     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16781         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16782     }
16783     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16784     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16785         // If the leading comments start on different line than the start of node, write new line
16786         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16787             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16788             writer.writeLine();
16789         }
16790     }
16791     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16792     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16793         // If the leading comments start on different line than the start of node, write new line
16794         if (pos !== commentPos &&
16795             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16796             writer.writeLine();
16797         }
16798     }
16799     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16800     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16801         if (comments && comments.length > 0) {
16802             if (leadingSeparator) {
16803                 writer.writeSpace(" ");
16804             }
16805             var emitInterveningSeparator = false;
16806             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16807                 var comment = comments_1[_i];
16808                 if (emitInterveningSeparator) {
16809                     writer.writeSpace(" ");
16810                     emitInterveningSeparator = false;
16811                 }
16812                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16813                 if (comment.hasTrailingNewLine) {
16814                     writer.writeLine();
16815                 }
16816                 else {
16817                     emitInterveningSeparator = true;
16818                 }
16819             }
16820             if (emitInterveningSeparator && trailingSeparator) {
16821                 writer.writeSpace(" ");
16822             }
16823         }
16824     }
16825     ts.emitComments = emitComments;
16826     /**
16827      * Detached comment is a comment at the top of file or function body that is separated from
16828      * the next statement by space.
16829      */
16830     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16831         var leadingComments;
16832         var currentDetachedCommentInfo;
16833         if (removeComments) {
16834             // removeComments is true, only reserve pinned comment at the top of file
16835             // For example:
16836             //      /*! Pinned Comment */
16837             //
16838             //      var x = 10;
16839             if (node.pos === 0) {
16840                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16841             }
16842         }
16843         else {
16844             // removeComments is false, just get detached as normal and bypass the process to filter comment
16845             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16846         }
16847         if (leadingComments) {
16848             var detachedComments = [];
16849             var lastComment = void 0;
16850             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16851                 var comment = leadingComments_1[_i];
16852                 if (lastComment) {
16853                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16854                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16855                     if (commentLine >= lastCommentLine + 2) {
16856                         // There was a blank line between the last comment and this comment.  This
16857                         // comment is not part of the copyright comments.  Return what we have so
16858                         // far.
16859                         break;
16860                     }
16861                 }
16862                 detachedComments.push(comment);
16863                 lastComment = comment;
16864             }
16865             if (detachedComments.length) {
16866                 // All comments look like they could have been part of the copyright header.  Make
16867                 // sure there is at least one blank line between it and the node.  If not, it's not
16868                 // a copyright header.
16869                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16870                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16871                 if (nodeLine >= lastCommentLine + 2) {
16872                     // Valid detachedComments
16873                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16874                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16875                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16876                 }
16877             }
16878         }
16879         return currentDetachedCommentInfo;
16880         function isPinnedCommentLocal(comment) {
16881             return isPinnedComment(text, comment.pos);
16882         }
16883     }
16884     ts.emitDetachedComments = emitDetachedComments;
16885     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16886         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16887             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16888             var lineCount = lineMap.length;
16889             var firstCommentLineIndent = void 0;
16890             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16891                 var nextLineStart = (currentLine + 1) === lineCount
16892                     ? text.length + 1
16893                     : lineMap[currentLine + 1];
16894                 if (pos !== commentPos) {
16895                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
16896                     if (firstCommentLineIndent === undefined) {
16897                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16898                     }
16899                     // These are number of spaces writer is going to write at current indent
16900                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16901                     // Number of spaces we want to be writing
16902                     // eg: Assume writer indent
16903                     // module m {
16904                     //         /* starts at character 9 this is line 1
16905                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
16906                     //   More left indented comment */                            --2  = 8 - 8 + 2
16907                     //     class c { }
16908                     // }
16909                     // module m {
16910                     //     /* this is line 1 -- Assume current writer indent 8
16911                     //      * line                                                --3 = 8 - 4 + 5
16912                     //            More right indented comment */                  --4 = 8 - 4 + 11
16913                     //     class c { }
16914                     // }
16915                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16916                     if (spacesToEmit > 0) {
16917                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16918                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16919                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16920                         writer.rawWrite(indentSizeSpaceString);
16921                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16922                         while (numberOfSingleSpacesToEmit) {
16923                             writer.rawWrite(" ");
16924                             numberOfSingleSpacesToEmit--;
16925                         }
16926                     }
16927                     else {
16928                         // No spaces to emit write empty string
16929                         writer.rawWrite("");
16930                     }
16931                 }
16932                 // Write the comment line text
16933                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16934                 pos = nextLineStart;
16935             }
16936         }
16937         else {
16938             // Single line comment of style //....
16939             writer.writeComment(text.substring(commentPos, commentEnd));
16940         }
16941     }
16942     ts.writeCommentRange = writeCommentRange;
16943     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16944         var end = Math.min(commentEnd, nextLineStart - 1);
16945         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16946         if (currentLineText) {
16947             // trimmed forward and ending spaces text
16948             writer.writeComment(currentLineText);
16949             if (end !== commentEnd) {
16950                 writer.writeLine();
16951             }
16952         }
16953         else {
16954             // Empty string - make sure we write empty line
16955             writer.rawWrite(newLine);
16956         }
16957     }
16958     function calculateIndent(text, pos, end) {
16959         var currentLineIndent = 0;
16960         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16961             if (text.charCodeAt(pos) === 9 /* tab */) {
16962                 // Tabs = TabSize = indent size and go to next tabStop
16963                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16964             }
16965             else {
16966                 // Single space
16967                 currentLineIndent++;
16968             }
16969         }
16970         return currentLineIndent;
16971     }
16972     function hasModifiers(node) {
16973         return getModifierFlags(node) !== 0 /* None */;
16974     }
16975     ts.hasModifiers = hasModifiers;
16976     function hasModifier(node, flags) {
16977         return !!getSelectedModifierFlags(node, flags);
16978     }
16979     ts.hasModifier = hasModifier;
16980     function hasStaticModifier(node) {
16981         return hasModifier(node, 32 /* Static */);
16982     }
16983     ts.hasStaticModifier = hasStaticModifier;
16984     function hasReadonlyModifier(node) {
16985         return hasModifier(node, 64 /* Readonly */);
16986     }
16987     ts.hasReadonlyModifier = hasReadonlyModifier;
16988     function getSelectedModifierFlags(node, flags) {
16989         return getModifierFlags(node) & flags;
16990     }
16991     ts.getSelectedModifierFlags = getSelectedModifierFlags;
16992     function getModifierFlags(node) {
16993         if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
16994             return 0 /* None */;
16995         }
16996         if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
16997             return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
16998         }
16999         var flags = getModifierFlagsNoCache(node);
17000         node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
17001         return flags;
17002     }
17003     ts.getModifierFlags = getModifierFlags;
17004     function getModifierFlagsNoCache(node) {
17005         var flags = 0 /* None */;
17006         if (node.modifiers) {
17007             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
17008                 var modifier = _a[_i];
17009                 flags |= modifierToFlag(modifier.kind);
17010             }
17011         }
17012         if (isInJSFile(node) && !!node.parent) {
17013             // getModifierFlagsNoCache should only be called when parent pointers are set,
17014             // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
17015             var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
17016                 | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
17017                 | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
17018                 | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
17019             flags |= tags;
17020         }
17021         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
17022             flags |= 1 /* Export */;
17023         }
17024         return flags;
17025     }
17026     ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
17027     function modifierToFlag(token) {
17028         switch (token) {
17029             case 120 /* StaticKeyword */: return 32 /* Static */;
17030             case 119 /* PublicKeyword */: return 4 /* Public */;
17031             case 118 /* ProtectedKeyword */: return 16 /* Protected */;
17032             case 117 /* PrivateKeyword */: return 8 /* Private */;
17033             case 122 /* AbstractKeyword */: return 128 /* Abstract */;
17034             case 89 /* ExportKeyword */: return 1 /* Export */;
17035             case 130 /* DeclareKeyword */: return 2 /* Ambient */;
17036             case 81 /* ConstKeyword */: return 2048 /* Const */;
17037             case 84 /* DefaultKeyword */: return 512 /* Default */;
17038             case 126 /* AsyncKeyword */: return 256 /* Async */;
17039             case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
17040         }
17041         return 0 /* None */;
17042     }
17043     ts.modifierToFlag = modifierToFlag;
17044     function isLogicalOperator(token) {
17045         return token === 56 /* BarBarToken */
17046             || token === 55 /* AmpersandAmpersandToken */
17047             || token === 53 /* ExclamationToken */;
17048     }
17049     ts.isLogicalOperator = isLogicalOperator;
17050     function isAssignmentOperator(token) {
17051         return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
17052     }
17053     ts.isAssignmentOperator = isAssignmentOperator;
17054     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
17055     function tryGetClassExtendingExpressionWithTypeArguments(node) {
17056         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
17057         return cls && !cls.isImplements ? cls.class : undefined;
17058     }
17059     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
17060     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
17061         return ts.isExpressionWithTypeArguments(node)
17062             && ts.isHeritageClause(node.parent)
17063             && ts.isClassLike(node.parent.parent)
17064             ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
17065             : undefined;
17066     }
17067     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
17068     function isAssignmentExpression(node, excludeCompoundAssignment) {
17069         return ts.isBinaryExpression(node)
17070             && (excludeCompoundAssignment
17071                 ? node.operatorToken.kind === 62 /* EqualsToken */
17072                 : isAssignmentOperator(node.operatorToken.kind))
17073             && ts.isLeftHandSideExpression(node.left);
17074     }
17075     ts.isAssignmentExpression = isAssignmentExpression;
17076     function isDestructuringAssignment(node) {
17077         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
17078             var kind = node.left.kind;
17079             return kind === 193 /* ObjectLiteralExpression */
17080                 || kind === 192 /* ArrayLiteralExpression */;
17081         }
17082         return false;
17083     }
17084     ts.isDestructuringAssignment = isDestructuringAssignment;
17085     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
17086         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
17087     }
17088     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
17089     function isEntityNameExpression(node) {
17090         return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
17091     }
17092     ts.isEntityNameExpression = isEntityNameExpression;
17093     function getFirstIdentifier(node) {
17094         switch (node.kind) {
17095             case 75 /* Identifier */:
17096                 return node;
17097             case 153 /* QualifiedName */:
17098                 do {
17099                     node = node.left;
17100                 } while (node.kind !== 75 /* Identifier */);
17101                 return node;
17102             case 194 /* PropertyAccessExpression */:
17103                 do {
17104                     node = node.expression;
17105                 } while (node.kind !== 75 /* Identifier */);
17106                 return node;
17107         }
17108     }
17109     ts.getFirstIdentifier = getFirstIdentifier;
17110     function isDottedName(node) {
17111         return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
17112             node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
17113             node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
17114     }
17115     ts.isDottedName = isDottedName;
17116     function isPropertyAccessEntityNameExpression(node) {
17117         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
17118     }
17119     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
17120     function tryGetPropertyAccessOrIdentifierToString(expr) {
17121         if (ts.isPropertyAccessExpression(expr)) {
17122             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
17123             if (baseStr !== undefined) {
17124                 return baseStr + "." + expr.name;
17125             }
17126         }
17127         else if (ts.isIdentifier(expr)) {
17128             return ts.unescapeLeadingUnderscores(expr.escapedText);
17129         }
17130         return undefined;
17131     }
17132     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
17133     function isPrototypeAccess(node) {
17134         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
17135     }
17136     ts.isPrototypeAccess = isPrototypeAccess;
17137     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
17138         return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
17139             (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
17140     }
17141     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
17142     function isEmptyObjectLiteral(expression) {
17143         return expression.kind === 193 /* ObjectLiteralExpression */ &&
17144             expression.properties.length === 0;
17145     }
17146     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
17147     function isEmptyArrayLiteral(expression) {
17148         return expression.kind === 192 /* ArrayLiteralExpression */ &&
17149             expression.elements.length === 0;
17150     }
17151     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
17152     function getLocalSymbolForExportDefault(symbol) {
17153         return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
17154     }
17155     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
17156     function isExportDefaultSymbol(symbol) {
17157         return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
17158     }
17159     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17160     function tryExtractTSExtension(fileName) {
17161         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17162     }
17163     ts.tryExtractTSExtension = tryExtractTSExtension;
17164     /**
17165      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17166      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17167      */
17168     function getExpandedCharCodes(input) {
17169         var output = [];
17170         var length = input.length;
17171         for (var i = 0; i < length; i++) {
17172             var charCode = input.charCodeAt(i);
17173             // handle utf8
17174             if (charCode < 0x80) {
17175                 output.push(charCode);
17176             }
17177             else if (charCode < 0x800) {
17178                 output.push((charCode >> 6) | 192);
17179                 output.push((charCode & 63) | 128);
17180             }
17181             else if (charCode < 0x10000) {
17182                 output.push((charCode >> 12) | 224);
17183                 output.push(((charCode >> 6) & 63) | 128);
17184                 output.push((charCode & 63) | 128);
17185             }
17186             else if (charCode < 0x20000) {
17187                 output.push((charCode >> 18) | 240);
17188                 output.push(((charCode >> 12) & 63) | 128);
17189                 output.push(((charCode >> 6) & 63) | 128);
17190                 output.push((charCode & 63) | 128);
17191             }
17192             else {
17193                 ts.Debug.assert(false, "Unexpected code point");
17194             }
17195         }
17196         return output;
17197     }
17198     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17199     /**
17200      * Converts a string to a base-64 encoded ASCII string.
17201      */
17202     function convertToBase64(input) {
17203         var result = "";
17204         var charCodes = getExpandedCharCodes(input);
17205         var i = 0;
17206         var length = charCodes.length;
17207         var byte1, byte2, byte3, byte4;
17208         while (i < length) {
17209             // Convert every 6-bits in the input 3 character points
17210             // into a base64 digit
17211             byte1 = charCodes[i] >> 2;
17212             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17213             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17214             byte4 = charCodes[i + 2] & 63;
17215             // We are out of characters in the input, set the extra
17216             // digits to 64 (padding character).
17217             if (i + 1 >= length) {
17218                 byte3 = byte4 = 64;
17219             }
17220             else if (i + 2 >= length) {
17221                 byte4 = 64;
17222             }
17223             // Write to the output
17224             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17225             i += 3;
17226         }
17227         return result;
17228     }
17229     ts.convertToBase64 = convertToBase64;
17230     function getStringFromExpandedCharCodes(codes) {
17231         var output = "";
17232         var i = 0;
17233         var length = codes.length;
17234         while (i < length) {
17235             var charCode = codes[i];
17236             if (charCode < 0x80) {
17237                 output += String.fromCharCode(charCode);
17238                 i++;
17239             }
17240             else if ((charCode & 192) === 192) {
17241                 var value = charCode & 63;
17242                 i++;
17243                 var nextCode = codes[i];
17244                 while ((nextCode & 192) === 128) {
17245                     value = (value << 6) | (nextCode & 63);
17246                     i++;
17247                     nextCode = codes[i];
17248                 }
17249                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17250                 output += String.fromCharCode(value);
17251             }
17252             else {
17253                 // We don't want to kill the process when decoding fails (due to a following char byte not
17254                 // following a leading char), so we just print the (bad) value
17255                 output += String.fromCharCode(charCode);
17256                 i++;
17257             }
17258         }
17259         return output;
17260     }
17261     function base64encode(host, input) {
17262         if (host && host.base64encode) {
17263             return host.base64encode(input);
17264         }
17265         return convertToBase64(input);
17266     }
17267     ts.base64encode = base64encode;
17268     function base64decode(host, input) {
17269         if (host && host.base64decode) {
17270             return host.base64decode(input);
17271         }
17272         var length = input.length;
17273         var expandedCharCodes = [];
17274         var i = 0;
17275         while (i < length) {
17276             // Stop decoding once padding characters are present
17277             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17278                 break;
17279             }
17280             // convert 4 input digits into three characters, ignoring padding characters at the end
17281             var ch1 = base64Digits.indexOf(input[i]);
17282             var ch2 = base64Digits.indexOf(input[i + 1]);
17283             var ch3 = base64Digits.indexOf(input[i + 2]);
17284             var ch4 = base64Digits.indexOf(input[i + 3]);
17285             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17286             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17287             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17288             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17289                 expandedCharCodes.push(code1);
17290             }
17291             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17292                 expandedCharCodes.push(code1, code2);
17293             }
17294             else {
17295                 expandedCharCodes.push(code1, code2, code3);
17296             }
17297             i += 4;
17298         }
17299         return getStringFromExpandedCharCodes(expandedCharCodes);
17300     }
17301     ts.base64decode = base64decode;
17302     function readJson(path, host) {
17303         try {
17304             var jsonText = host.readFile(path);
17305             if (!jsonText)
17306                 return {};
17307             var result = ts.parseConfigFileTextToJson(path, jsonText);
17308             if (result.error) {
17309                 return {};
17310             }
17311             return result.config;
17312         }
17313         catch (e) {
17314             // gracefully handle if readFile fails or returns not JSON
17315             return {};
17316         }
17317     }
17318     ts.readJson = readJson;
17319     function directoryProbablyExists(directoryName, host) {
17320         // if host does not support 'directoryExists' assume that directory will exist
17321         return !host.directoryExists || host.directoryExists(directoryName);
17322     }
17323     ts.directoryProbablyExists = directoryProbablyExists;
17324     var carriageReturnLineFeed = "\r\n";
17325     var lineFeed = "\n";
17326     function getNewLineCharacter(options, getNewLine) {
17327         switch (options.newLine) {
17328             case 0 /* CarriageReturnLineFeed */:
17329                 return carriageReturnLineFeed;
17330             case 1 /* LineFeed */:
17331                 return lineFeed;
17332         }
17333         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17334     }
17335     ts.getNewLineCharacter = getNewLineCharacter;
17336     /**
17337      * Creates a new TextRange from the provided pos and end.
17338      *
17339      * @param pos The start position.
17340      * @param end The end position.
17341      */
17342     function createRange(pos, end) {
17343         if (end === void 0) { end = pos; }
17344         ts.Debug.assert(end >= pos || end === -1);
17345         return { pos: pos, end: end };
17346     }
17347     ts.createRange = createRange;
17348     /**
17349      * Creates a new TextRange from a provided range with a new end position.
17350      *
17351      * @param range A TextRange.
17352      * @param end The new end position.
17353      */
17354     function moveRangeEnd(range, end) {
17355         return createRange(range.pos, end);
17356     }
17357     ts.moveRangeEnd = moveRangeEnd;
17358     /**
17359      * Creates a new TextRange from a provided range with a new start position.
17360      *
17361      * @param range A TextRange.
17362      * @param pos The new Start position.
17363      */
17364     function moveRangePos(range, pos) {
17365         return createRange(pos, range.end);
17366     }
17367     ts.moveRangePos = moveRangePos;
17368     /**
17369      * Moves the start position of a range past any decorators.
17370      */
17371     function moveRangePastDecorators(node) {
17372         return node.decorators && node.decorators.length > 0
17373             ? moveRangePos(node, node.decorators.end)
17374             : node;
17375     }
17376     ts.moveRangePastDecorators = moveRangePastDecorators;
17377     /**
17378      * Moves the start position of a range past any decorators or modifiers.
17379      */
17380     function moveRangePastModifiers(node) {
17381         return node.modifiers && node.modifiers.length > 0
17382             ? moveRangePos(node, node.modifiers.end)
17383             : moveRangePastDecorators(node);
17384     }
17385     ts.moveRangePastModifiers = moveRangePastModifiers;
17386     /**
17387      * Determines whether a TextRange has the same start and end positions.
17388      *
17389      * @param range A TextRange.
17390      */
17391     function isCollapsedRange(range) {
17392         return range.pos === range.end;
17393     }
17394     ts.isCollapsedRange = isCollapsedRange;
17395     /**
17396      * Creates a new TextRange for a token at the provides start position.
17397      *
17398      * @param pos The start position.
17399      * @param token The token.
17400      */
17401     function createTokenRange(pos, token) {
17402         return createRange(pos, pos + ts.tokenToString(token).length);
17403     }
17404     ts.createTokenRange = createTokenRange;
17405     function rangeIsOnSingleLine(range, sourceFile) {
17406         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17407     }
17408     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17409     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17410         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17411     }
17412     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17413     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17414         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17415     }
17416     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17417     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17418         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17419     }
17420     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17421     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17422         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17423     }
17424     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17425     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17426         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17427         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17428     }
17429     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17430     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17431         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17432     }
17433     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17434     function isNodeArrayMultiLine(list, sourceFile) {
17435         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17436     }
17437     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17438     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17439         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17440     }
17441     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17442     function getStartPositionOfRange(range, sourceFile, includeComments) {
17443         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17444     }
17445     ts.getStartPositionOfRange = getStartPositionOfRange;
17446     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17447         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17448         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17449         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17450     }
17451     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17452     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17453         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17454         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17455     }
17456     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17457     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17458         if (stopPos === void 0) { stopPos = 0; }
17459         while (pos-- > stopPos) {
17460             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17461                 return pos;
17462             }
17463         }
17464     }
17465     /**
17466      * Determines whether a name was originally the declaration name of an enum or namespace
17467      * declaration.
17468      */
17469     function isDeclarationNameOfEnumOrNamespace(node) {
17470         var parseNode = ts.getParseTreeNode(node);
17471         if (parseNode) {
17472             switch (parseNode.parent.kind) {
17473                 case 248 /* EnumDeclaration */:
17474                 case 249 /* ModuleDeclaration */:
17475                     return parseNode === parseNode.parent.name;
17476             }
17477         }
17478         return false;
17479     }
17480     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17481     function getInitializedVariables(node) {
17482         return ts.filter(node.declarations, isInitializedVariable);
17483     }
17484     ts.getInitializedVariables = getInitializedVariables;
17485     function isInitializedVariable(node) {
17486         return node.initializer !== undefined;
17487     }
17488     function isWatchSet(options) {
17489         // Firefox has Object.prototype.watch
17490         return options.watch && options.hasOwnProperty("watch");
17491     }
17492     ts.isWatchSet = isWatchSet;
17493     function closeFileWatcher(watcher) {
17494         watcher.close();
17495     }
17496     ts.closeFileWatcher = closeFileWatcher;
17497     function getCheckFlags(symbol) {
17498         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17499     }
17500     ts.getCheckFlags = getCheckFlags;
17501     function getDeclarationModifierFlagsFromSymbol(s) {
17502         if (s.valueDeclaration) {
17503             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17504             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17505         }
17506         if (getCheckFlags(s) & 6 /* Synthetic */) {
17507             var checkFlags = s.checkFlags;
17508             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17509                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17510                     16 /* Protected */;
17511             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17512             return accessModifier | staticModifier;
17513         }
17514         if (s.flags & 4194304 /* Prototype */) {
17515             return 4 /* Public */ | 32 /* Static */;
17516         }
17517         return 0;
17518     }
17519     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17520     function skipAlias(symbol, checker) {
17521         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17522     }
17523     ts.skipAlias = skipAlias;
17524     /** See comment on `declareModuleMember` in `binder.ts`. */
17525     function getCombinedLocalAndExportSymbolFlags(symbol) {
17526         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17527     }
17528     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17529     function isWriteOnlyAccess(node) {
17530         return accessKind(node) === 1 /* Write */;
17531     }
17532     ts.isWriteOnlyAccess = isWriteOnlyAccess;
17533     function isWriteAccess(node) {
17534         return accessKind(node) !== 0 /* Read */;
17535     }
17536     ts.isWriteAccess = isWriteAccess;
17537     var AccessKind;
17538     (function (AccessKind) {
17539         /** Only reads from a variable. */
17540         AccessKind[AccessKind["Read"] = 0] = "Read";
17541         /** Only writes to a variable without using the result. E.g.: `x++;`. */
17542         AccessKind[AccessKind["Write"] = 1] = "Write";
17543         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17544         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17545     })(AccessKind || (AccessKind = {}));
17546     function accessKind(node) {
17547         var parent = node.parent;
17548         if (!parent)
17549             return 0 /* Read */;
17550         switch (parent.kind) {
17551             case 200 /* ParenthesizedExpression */:
17552                 return accessKind(parent);
17553             case 208 /* PostfixUnaryExpression */:
17554             case 207 /* PrefixUnaryExpression */:
17555                 var operator = parent.operator;
17556                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17557             case 209 /* BinaryExpression */:
17558                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17559                 return left === node && isAssignmentOperator(operatorToken.kind) ?
17560                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17561                     : 0 /* Read */;
17562             case 194 /* PropertyAccessExpression */:
17563                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17564             case 281 /* PropertyAssignment */: {
17565                 var parentAccess = accessKind(parent.parent);
17566                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17567                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17568             }
17569             case 282 /* ShorthandPropertyAssignment */:
17570                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17571                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17572             case 192 /* ArrayLiteralExpression */:
17573                 return accessKind(parent);
17574             default:
17575                 return 0 /* Read */;
17576         }
17577         function writeOrReadWrite() {
17578             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17579             return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17580         }
17581     }
17582     function reverseAccessKind(a) {
17583         switch (a) {
17584             case 0 /* Read */:
17585                 return 1 /* Write */;
17586             case 1 /* Write */:
17587                 return 0 /* Read */;
17588             case 2 /* ReadWrite */:
17589                 return 2 /* ReadWrite */;
17590             default:
17591                 return ts.Debug.assertNever(a);
17592         }
17593     }
17594     function compareDataObjects(dst, src) {
17595         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17596             return false;
17597         }
17598         for (var e in dst) {
17599             if (typeof dst[e] === "object") {
17600                 if (!compareDataObjects(dst[e], src[e])) {
17601                     return false;
17602                 }
17603             }
17604             else if (typeof dst[e] !== "function") {
17605                 if (dst[e] !== src[e]) {
17606                     return false;
17607                 }
17608             }
17609         }
17610         return true;
17611     }
17612     ts.compareDataObjects = compareDataObjects;
17613     /**
17614      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17615      */
17616     function clearMap(map, onDeleteValue) {
17617         // Remove all
17618         map.forEach(onDeleteValue);
17619         map.clear();
17620     }
17621     ts.clearMap = clearMap;
17622     /**
17623      * Mutates the map with newMap such that keys in map will be same as newMap.
17624      */
17625     function mutateMapSkippingNewValues(map, newMap, options) {
17626         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17627         // Needs update
17628         map.forEach(function (existingValue, key) {
17629             var valueInNewMap = newMap.get(key);
17630             // Not present any more in new map, remove it
17631             if (valueInNewMap === undefined) {
17632                 map.delete(key);
17633                 onDeleteValue(existingValue, key);
17634             }
17635             // If present notify about existing values
17636             else if (onExistingValue) {
17637                 onExistingValue(existingValue, valueInNewMap, key);
17638             }
17639         });
17640     }
17641     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17642     /**
17643      * Mutates the map with newMap such that keys in map will be same as newMap.
17644      */
17645     function mutateMap(map, newMap, options) {
17646         // Needs update
17647         mutateMapSkippingNewValues(map, newMap, options);
17648         var createNewValue = options.createNewValue;
17649         // Add new values that are not already present
17650         newMap.forEach(function (valueInNewMap, key) {
17651             if (!map.has(key)) {
17652                 // New values
17653                 map.set(key, createNewValue(key, valueInNewMap));
17654             }
17655         });
17656     }
17657     ts.mutateMap = mutateMap;
17658     // Return true if the given type is the constructor type for an abstract class
17659     function isAbstractConstructorType(type) {
17660         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17661     }
17662     ts.isAbstractConstructorType = isAbstractConstructorType;
17663     function isAbstractConstructorSymbol(symbol) {
17664         if (symbol.flags & 32 /* Class */) {
17665             var declaration = getClassLikeDeclarationOfSymbol(symbol);
17666             return !!declaration && hasModifier(declaration, 128 /* Abstract */);
17667         }
17668         return false;
17669     }
17670     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17671     function getClassLikeDeclarationOfSymbol(symbol) {
17672         return ts.find(symbol.declarations, ts.isClassLike);
17673     }
17674     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17675     function getObjectFlags(type) {
17676         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17677     }
17678     ts.getObjectFlags = getObjectFlags;
17679     function typeHasCallOrConstructSignatures(type, checker) {
17680         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17681     }
17682     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17683     function forSomeAncestorDirectory(directory, callback) {
17684         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17685     }
17686     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17687     function isUMDExportSymbol(symbol) {
17688         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17689     }
17690     ts.isUMDExportSymbol = isUMDExportSymbol;
17691     function showModuleSpecifier(_a) {
17692         var moduleSpecifier = _a.moduleSpecifier;
17693         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17694     }
17695     ts.showModuleSpecifier = showModuleSpecifier;
17696     function getLastChild(node) {
17697         var lastChild;
17698         ts.forEachChild(node, function (child) {
17699             if (nodeIsPresent(child))
17700                 lastChild = child;
17701         }, function (children) {
17702             // As an optimization, jump straight to the end of the list.
17703             for (var i = children.length - 1; i >= 0; i--) {
17704                 if (nodeIsPresent(children[i])) {
17705                     lastChild = children[i];
17706                     break;
17707                 }
17708             }
17709         });
17710         return lastChild;
17711     }
17712     ts.getLastChild = getLastChild;
17713     function addToSeen(seen, key, value) {
17714         if (value === void 0) { value = true; }
17715         key = String(key);
17716         if (seen.has(key)) {
17717             return false;
17718         }
17719         seen.set(key, value);
17720         return true;
17721     }
17722     ts.addToSeen = addToSeen;
17723     function isObjectTypeDeclaration(node) {
17724         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17725     }
17726     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17727     function isTypeNodeKind(kind) {
17728         return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
17729             || kind === 125 /* AnyKeyword */
17730             || kind === 148 /* UnknownKeyword */
17731             || kind === 140 /* NumberKeyword */
17732             || kind === 151 /* BigIntKeyword */
17733             || kind === 141 /* ObjectKeyword */
17734             || kind === 128 /* BooleanKeyword */
17735             || kind === 143 /* StringKeyword */
17736             || kind === 144 /* SymbolKeyword */
17737             || kind === 104 /* ThisKeyword */
17738             || kind === 110 /* VoidKeyword */
17739             || kind === 146 /* UndefinedKeyword */
17740             || kind === 100 /* NullKeyword */
17741             || kind === 137 /* NeverKeyword */
17742             || kind === 216 /* ExpressionWithTypeArguments */
17743             || kind === 295 /* JSDocAllType */
17744             || kind === 296 /* JSDocUnknownType */
17745             || kind === 297 /* JSDocNullableType */
17746             || kind === 298 /* JSDocNonNullableType */
17747             || kind === 299 /* JSDocOptionalType */
17748             || kind === 300 /* JSDocFunctionType */
17749             || kind === 301 /* JSDocVariadicType */;
17750     }
17751     ts.isTypeNodeKind = isTypeNodeKind;
17752     function isAccessExpression(node) {
17753         return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
17754     }
17755     ts.isAccessExpression = isAccessExpression;
17756     function getNameOfAccessExpression(node) {
17757         if (node.kind === 194 /* PropertyAccessExpression */) {
17758             return node.name;
17759         }
17760         ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
17761         return node.argumentExpression;
17762     }
17763     ts.getNameOfAccessExpression = getNameOfAccessExpression;
17764     function isBundleFileTextLike(section) {
17765         switch (section.kind) {
17766             case "text" /* Text */:
17767             case "internal" /* Internal */:
17768                 return true;
17769             default:
17770                 return false;
17771         }
17772     }
17773     ts.isBundleFileTextLike = isBundleFileTextLike;
17774     function isNamedImportsOrExports(node) {
17775         return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
17776     }
17777     ts.isNamedImportsOrExports = isNamedImportsOrExports;
17778     function Symbol(flags, name) {
17779         this.flags = flags;
17780         this.escapedName = name;
17781         this.declarations = undefined;
17782         this.valueDeclaration = undefined;
17783         this.id = undefined;
17784         this.mergeId = undefined;
17785         this.parent = undefined;
17786     }
17787     function Type(checker, flags) {
17788         this.flags = flags;
17789         if (ts.Debug.isDebugging) {
17790             this.checker = checker;
17791         }
17792     }
17793     function Signature(checker, flags) {
17794         this.flags = flags;
17795         if (ts.Debug.isDebugging) {
17796             this.checker = checker;
17797         }
17798     }
17799     function Node(kind, pos, end) {
17800         this.pos = pos;
17801         this.end = end;
17802         this.kind = kind;
17803         this.id = 0;
17804         this.flags = 0 /* None */;
17805         this.modifierFlagsCache = 0 /* None */;
17806         this.transformFlags = 0 /* None */;
17807         this.parent = undefined;
17808         this.original = undefined;
17809     }
17810     function Token(kind, pos, end) {
17811         this.pos = pos;
17812         this.end = end;
17813         this.kind = kind;
17814         this.id = 0;
17815         this.flags = 0 /* None */;
17816         this.transformFlags = 0 /* None */;
17817         this.parent = undefined;
17818     }
17819     function Identifier(kind, pos, end) {
17820         this.pos = pos;
17821         this.end = end;
17822         this.kind = kind;
17823         this.id = 0;
17824         this.flags = 0 /* None */;
17825         this.transformFlags = 0 /* None */;
17826         this.parent = undefined;
17827         this.original = undefined;
17828         this.flowNode = undefined;
17829     }
17830     function SourceMapSource(fileName, text, skipTrivia) {
17831         this.fileName = fileName;
17832         this.text = text;
17833         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17834     }
17835     // eslint-disable-next-line prefer-const
17836     ts.objectAllocator = {
17837         getNodeConstructor: function () { return Node; },
17838         getTokenConstructor: function () { return Token; },
17839         getIdentifierConstructor: function () { return Identifier; },
17840         getPrivateIdentifierConstructor: function () { return Node; },
17841         getSourceFileConstructor: function () { return Node; },
17842         getSymbolConstructor: function () { return Symbol; },
17843         getTypeConstructor: function () { return Type; },
17844         getSignatureConstructor: function () { return Signature; },
17845         getSourceMapSourceConstructor: function () { return SourceMapSource; },
17846     };
17847     function setObjectAllocator(alloc) {
17848         ts.objectAllocator = alloc;
17849     }
17850     ts.setObjectAllocator = setObjectAllocator;
17851     function formatStringFromArgs(text, args, baseIndex) {
17852         if (baseIndex === void 0) { baseIndex = 0; }
17853         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17854     }
17855     ts.formatStringFromArgs = formatStringFromArgs;
17856     /* @internal */
17857     function setLocalizedDiagnosticMessages(messages) {
17858         ts.localizedDiagnosticMessages = messages;
17859     }
17860     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17861     function getLocaleSpecificMessage(message) {
17862         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17863     }
17864     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17865     function createFileDiagnostic(file, start, length, message) {
17866         ts.Debug.assertGreaterThanOrEqual(start, 0);
17867         ts.Debug.assertGreaterThanOrEqual(length, 0);
17868         if (file) {
17869             ts.Debug.assertLessThanOrEqual(start, file.text.length);
17870             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17871         }
17872         var text = getLocaleSpecificMessage(message);
17873         if (arguments.length > 4) {
17874             text = formatStringFromArgs(text, arguments, 4);
17875         }
17876         return {
17877             file: file,
17878             start: start,
17879             length: length,
17880             messageText: text,
17881             category: message.category,
17882             code: message.code,
17883             reportsUnnecessary: message.reportsUnnecessary,
17884         };
17885     }
17886     ts.createFileDiagnostic = createFileDiagnostic;
17887     function formatMessage(_dummy, message) {
17888         var text = getLocaleSpecificMessage(message);
17889         if (arguments.length > 2) {
17890             text = formatStringFromArgs(text, arguments, 2);
17891         }
17892         return text;
17893     }
17894     ts.formatMessage = formatMessage;
17895     function createCompilerDiagnostic(message) {
17896         var text = getLocaleSpecificMessage(message);
17897         if (arguments.length > 1) {
17898             text = formatStringFromArgs(text, arguments, 1);
17899         }
17900         return {
17901             file: undefined,
17902             start: undefined,
17903             length: undefined,
17904             messageText: text,
17905             category: message.category,
17906             code: message.code,
17907             reportsUnnecessary: message.reportsUnnecessary,
17908         };
17909     }
17910     ts.createCompilerDiagnostic = createCompilerDiagnostic;
17911     function createCompilerDiagnosticFromMessageChain(chain) {
17912         return {
17913             file: undefined,
17914             start: undefined,
17915             length: undefined,
17916             code: chain.code,
17917             category: chain.category,
17918             messageText: chain.next ? chain : chain.messageText,
17919         };
17920     }
17921     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17922     function chainDiagnosticMessages(details, message) {
17923         var text = getLocaleSpecificMessage(message);
17924         if (arguments.length > 2) {
17925             text = formatStringFromArgs(text, arguments, 2);
17926         }
17927         return {
17928             messageText: text,
17929             category: message.category,
17930             code: message.code,
17931             next: details === undefined || Array.isArray(details) ? details : [details]
17932         };
17933     }
17934     ts.chainDiagnosticMessages = chainDiagnosticMessages;
17935     function concatenateDiagnosticMessageChains(headChain, tailChain) {
17936         var lastChain = headChain;
17937         while (lastChain.next) {
17938             lastChain = lastChain.next[0];
17939         }
17940         lastChain.next = [tailChain];
17941     }
17942     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17943     function getDiagnosticFilePath(diagnostic) {
17944         return diagnostic.file ? diagnostic.file.path : undefined;
17945     }
17946     function compareDiagnostics(d1, d2) {
17947         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17948             compareRelatedInformation(d1, d2) ||
17949             0 /* EqualTo */;
17950     }
17951     ts.compareDiagnostics = compareDiagnostics;
17952     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17953         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17954             ts.compareValues(d1.start, d2.start) ||
17955             ts.compareValues(d1.length, d2.length) ||
17956             ts.compareValues(d1.code, d2.code) ||
17957             compareMessageText(d1.messageText, d2.messageText) ||
17958             0 /* EqualTo */;
17959     }
17960     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17961     function compareRelatedInformation(d1, d2) {
17962         if (!d1.relatedInformation && !d2.relatedInformation) {
17963             return 0 /* EqualTo */;
17964         }
17965         if (d1.relatedInformation && d2.relatedInformation) {
17966             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17967                 var d2i = d2.relatedInformation[index];
17968                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17969             }) || 0 /* EqualTo */;
17970         }
17971         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17972     }
17973     function compareMessageText(t1, t2) {
17974         if (typeof t1 === "string" && typeof t2 === "string") {
17975             return ts.compareStringsCaseSensitive(t1, t2);
17976         }
17977         else if (typeof t1 === "string") {
17978             return -1 /* LessThan */;
17979         }
17980         else if (typeof t2 === "string") {
17981             return 1 /* GreaterThan */;
17982         }
17983         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17984         if (res) {
17985             return res;
17986         }
17987         if (!t1.next && !t2.next) {
17988             return 0 /* EqualTo */;
17989         }
17990         if (!t1.next) {
17991             return -1 /* LessThan */;
17992         }
17993         if (!t2.next) {
17994             return 1 /* GreaterThan */;
17995         }
17996         var len = Math.min(t1.next.length, t2.next.length);
17997         for (var i = 0; i < len; i++) {
17998             res = compareMessageText(t1.next[i], t2.next[i]);
17999             if (res) {
18000                 return res;
18001             }
18002         }
18003         if (t1.next.length < t2.next.length) {
18004             return -1 /* LessThan */;
18005         }
18006         else if (t1.next.length > t2.next.length) {
18007             return 1 /* GreaterThan */;
18008         }
18009         return 0 /* EqualTo */;
18010     }
18011     function getEmitScriptTarget(compilerOptions) {
18012         return compilerOptions.target || 0 /* ES3 */;
18013     }
18014     ts.getEmitScriptTarget = getEmitScriptTarget;
18015     function getEmitModuleKind(compilerOptions) {
18016         return typeof compilerOptions.module === "number" ?
18017             compilerOptions.module :
18018             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
18019     }
18020     ts.getEmitModuleKind = getEmitModuleKind;
18021     function getEmitModuleResolutionKind(compilerOptions) {
18022         var moduleResolution = compilerOptions.moduleResolution;
18023         if (moduleResolution === undefined) {
18024             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
18025         }
18026         return moduleResolution;
18027     }
18028     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
18029     function hasJsonModuleEmitEnabled(options) {
18030         switch (getEmitModuleKind(options)) {
18031             case ts.ModuleKind.CommonJS:
18032             case ts.ModuleKind.AMD:
18033             case ts.ModuleKind.ES2015:
18034             case ts.ModuleKind.ES2020:
18035             case ts.ModuleKind.ESNext:
18036                 return true;
18037             default:
18038                 return false;
18039         }
18040     }
18041     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
18042     function unreachableCodeIsError(options) {
18043         return options.allowUnreachableCode === false;
18044     }
18045     ts.unreachableCodeIsError = unreachableCodeIsError;
18046     function unusedLabelIsError(options) {
18047         return options.allowUnusedLabels === false;
18048     }
18049     ts.unusedLabelIsError = unusedLabelIsError;
18050     function getAreDeclarationMapsEnabled(options) {
18051         return !!(getEmitDeclarations(options) && options.declarationMap);
18052     }
18053     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
18054     function getAllowSyntheticDefaultImports(compilerOptions) {
18055         var moduleKind = getEmitModuleKind(compilerOptions);
18056         return compilerOptions.allowSyntheticDefaultImports !== undefined
18057             ? compilerOptions.allowSyntheticDefaultImports
18058             : compilerOptions.esModuleInterop ||
18059                 moduleKind === ts.ModuleKind.System;
18060     }
18061     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
18062     function getEmitDeclarations(compilerOptions) {
18063         return !!(compilerOptions.declaration || compilerOptions.composite);
18064     }
18065     ts.getEmitDeclarations = getEmitDeclarations;
18066     function isIncrementalCompilation(options) {
18067         return !!(options.incremental || options.composite);
18068     }
18069     ts.isIncrementalCompilation = isIncrementalCompilation;
18070     function getStrictOptionValue(compilerOptions, flag) {
18071         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
18072     }
18073     ts.getStrictOptionValue = getStrictOptionValue;
18074     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
18075         return oldOptions !== newOptions &&
18076             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18077     }
18078     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
18079     function compilerOptionsAffectEmit(newOptions, oldOptions) {
18080         return oldOptions !== newOptions &&
18081             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18082     }
18083     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
18084     function getCompilerOptionValue(options, option) {
18085         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
18086     }
18087     ts.getCompilerOptionValue = getCompilerOptionValue;
18088     function hasZeroOrOneAsteriskCharacter(str) {
18089         var seenAsterisk = false;
18090         for (var i = 0; i < str.length; i++) {
18091             if (str.charCodeAt(i) === 42 /* asterisk */) {
18092                 if (!seenAsterisk) {
18093                     seenAsterisk = true;
18094                 }
18095                 else {
18096                     // have already seen asterisk
18097                     return false;
18098                 }
18099             }
18100         }
18101         return true;
18102     }
18103     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
18104     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
18105         var result = ts.createMap();
18106         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
18107             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
18108                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
18109             })));
18110         }));
18111         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
18112             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
18113             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
18114             result.set(commonOriginal, commonResolved);
18115         }
18116         return result;
18117     }
18118     ts.discoverProbableSymlinks = discoverProbableSymlinks;
18119     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
18120         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
18121         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
18122         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
18123             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
18124             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
18125             aParts.pop();
18126             bParts.pop();
18127         }
18128         return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
18129     }
18130     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
18131     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
18132     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
18133         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
18134     }
18135     function stripLeadingDirectorySeparator(s) {
18136         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
18137     }
18138     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
18139         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
18140         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
18141     }
18142     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
18143     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
18144     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
18145     // proof.
18146     var reservedCharacterPattern = /[^\w\s\/]/g;
18147     function regExpEscape(text) {
18148         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
18149     }
18150     ts.regExpEscape = regExpEscape;
18151     function escapeRegExpCharacter(match) {
18152         return "\\" + match;
18153     }
18154     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
18155     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
18156     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
18157     var filesMatcher = {
18158         /**
18159          * Matches any single directory segment unless it is the last segment and a .min.js file
18160          * Breakdown:
18161          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18162          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18163          */
18164         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18165         /**
18166          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18167          * files or directories, does not match subdirectories that start with a . character
18168          */
18169         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18170         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18171     };
18172     var directoriesMatcher = {
18173         singleAsteriskRegexFragment: "[^/]*",
18174         /**
18175          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18176          * files or directories, does not match subdirectories that start with a . character
18177          */
18178         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18179         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18180     };
18181     var excludeMatcher = {
18182         singleAsteriskRegexFragment: "[^/]*",
18183         doubleAsteriskRegexFragment: "(/.+?)?",
18184         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18185     };
18186     var wildcardMatchers = {
18187         files: filesMatcher,
18188         directories: directoriesMatcher,
18189         exclude: excludeMatcher
18190     };
18191     function getRegularExpressionForWildcard(specs, basePath, usage) {
18192         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18193         if (!patterns || !patterns.length) {
18194             return undefined;
18195         }
18196         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18197         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18198         var terminator = usage === "exclude" ? "($|/)" : "$";
18199         return "^(" + pattern + ")" + terminator;
18200     }
18201     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18202     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18203         if (specs === undefined || specs.length === 0) {
18204             return undefined;
18205         }
18206         return ts.flatMap(specs, function (spec) {
18207             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18208         });
18209     }
18210     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18211     /**
18212      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18213      * and does not contain any glob characters itself.
18214      */
18215     function isImplicitGlob(lastPathComponent) {
18216         return !/[.*?]/.test(lastPathComponent);
18217     }
18218     ts.isImplicitGlob = isImplicitGlob;
18219     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18220         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18221         var subpattern = "";
18222         var hasWrittenComponent = false;
18223         var components = ts.getNormalizedPathComponents(spec, basePath);
18224         var lastComponent = ts.last(components);
18225         if (usage !== "exclude" && lastComponent === "**") {
18226             return undefined;
18227         }
18228         // getNormalizedPathComponents includes the separator for the root component.
18229         // We need to remove to create our regex correctly.
18230         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18231         if (isImplicitGlob(lastComponent)) {
18232             components.push("**", "*");
18233         }
18234         var optionalCount = 0;
18235         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18236             var component = components_1[_i];
18237             if (component === "**") {
18238                 subpattern += doubleAsteriskRegexFragment;
18239             }
18240             else {
18241                 if (usage === "directories") {
18242                     subpattern += "(";
18243                     optionalCount++;
18244                 }
18245                 if (hasWrittenComponent) {
18246                     subpattern += ts.directorySeparator;
18247                 }
18248                 if (usage !== "exclude") {
18249                     var componentPattern = "";
18250                     // The * and ? wildcards should not match directories or files that start with . if they
18251                     // appear first in a component. Dotted directories and files can be included explicitly
18252                     // like so: **/.*/.*
18253                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18254                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18255                         component = component.substr(1);
18256                     }
18257                     else if (component.charCodeAt(0) === 63 /* question */) {
18258                         componentPattern += "[^./]";
18259                         component = component.substr(1);
18260                     }
18261                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18262                     // Patterns should not include subfolders like node_modules unless they are
18263                     // explicitly included as part of the path.
18264                     //
18265                     // As an optimization, if the component pattern is the same as the component,
18266                     // then there definitely were no wildcard characters and we do not need to
18267                     // add the exclusion pattern.
18268                     if (componentPattern !== component) {
18269                         subpattern += implicitExcludePathRegexPattern;
18270                     }
18271                     subpattern += componentPattern;
18272                 }
18273                 else {
18274                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18275                 }
18276             }
18277             hasWrittenComponent = true;
18278         }
18279         while (optionalCount > 0) {
18280             subpattern += ")?";
18281             optionalCount--;
18282         }
18283         return subpattern;
18284     }
18285     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18286         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18287     }
18288     /** @param path directory of the tsconfig.json */
18289     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18290         path = ts.normalizePath(path);
18291         currentDirectory = ts.normalizePath(currentDirectory);
18292         var absolutePath = ts.combinePaths(currentDirectory, path);
18293         return {
18294             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18295             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18296             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18297             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18298             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18299         };
18300     }
18301     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18302     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18303         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18304     }
18305     ts.getRegexFromPattern = getRegexFromPattern;
18306     /** @param path directory of the tsconfig.json */
18307     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18308         path = ts.normalizePath(path);
18309         currentDirectory = ts.normalizePath(currentDirectory);
18310         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18311         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18312         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18313         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18314         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18315         // If there are no "includes", then just put everything in results[0].
18316         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18317         var visited = ts.createMap();
18318         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18319         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18320             var basePath = _a[_i];
18321             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18322         }
18323         return ts.flatten(results);
18324         function visitDirectory(path, absolutePath, depth) {
18325             var canonicalPath = toCanonical(realpath(absolutePath));
18326             if (visited.has(canonicalPath))
18327                 return;
18328             visited.set(canonicalPath, true);
18329             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18330             var _loop_1 = function (current) {
18331                 var name = ts.combinePaths(path, current);
18332                 var absoluteName = ts.combinePaths(absolutePath, current);
18333                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18334                     return "continue";
18335                 if (excludeRegex && excludeRegex.test(absoluteName))
18336                     return "continue";
18337                 if (!includeFileRegexes) {
18338                     results[0].push(name);
18339                 }
18340                 else {
18341                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18342                     if (includeIndex !== -1) {
18343                         results[includeIndex].push(name);
18344                     }
18345                 }
18346             };
18347             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18348                 var current = _b[_i];
18349                 _loop_1(current);
18350             }
18351             if (depth !== undefined) {
18352                 depth--;
18353                 if (depth === 0) {
18354                     return;
18355                 }
18356             }
18357             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18358                 var current = _d[_c];
18359                 var name = ts.combinePaths(path, current);
18360                 var absoluteName = ts.combinePaths(absolutePath, current);
18361                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18362                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
18363                     visitDirectory(name, absoluteName, depth);
18364                 }
18365             }
18366         }
18367     }
18368     ts.matchFiles = matchFiles;
18369     /**
18370      * Computes the unique non-wildcard base paths amongst the provided include patterns.
18371      */
18372     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18373         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18374         var basePaths = [path];
18375         if (includes) {
18376             // Storage for literal base paths amongst the include patterns.
18377             var includeBasePaths = [];
18378             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18379                 var include = includes_1[_i];
18380                 // We also need to check the relative paths by converting them to absolute and normalizing
18381                 // in case they escape the base path (e.g "..\somedirectory")
18382                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18383                 // Append the literal and canonical candidate base paths.
18384                 includeBasePaths.push(getIncludeBasePath(absolute));
18385             }
18386             // Sort the offsets array using either the literal or canonical path representations.
18387             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18388             var _loop_2 = function (includeBasePath) {
18389                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18390                     basePaths.push(includeBasePath);
18391                 }
18392             };
18393             // Iterate over each include base path and include unique base paths that are not a
18394             // subpath of an existing base path
18395             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18396                 var includeBasePath = includeBasePaths_1[_a];
18397                 _loop_2(includeBasePath);
18398             }
18399         }
18400         return basePaths;
18401     }
18402     function getIncludeBasePath(absolute) {
18403         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18404         if (wildcardOffset < 0) {
18405             // No "*" or "?" in the path
18406             return !ts.hasExtension(absolute)
18407                 ? absolute
18408                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18409         }
18410         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18411     }
18412     function ensureScriptKind(fileName, scriptKind) {
18413         // Using scriptKind as a condition handles both:
18414         // - 'scriptKind' is unspecified and thus it is `undefined`
18415         // - 'scriptKind' is set and it is `Unknown` (0)
18416         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18417         // to get the ScriptKind from the file name. If it cannot be resolved
18418         // from the file name then the default 'TS' script kind is returned.
18419         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18420     }
18421     ts.ensureScriptKind = ensureScriptKind;
18422     function getScriptKindFromFileName(fileName) {
18423         var ext = fileName.substr(fileName.lastIndexOf("."));
18424         switch (ext.toLowerCase()) {
18425             case ".js" /* Js */:
18426                 return 1 /* JS */;
18427             case ".jsx" /* Jsx */:
18428                 return 2 /* JSX */;
18429             case ".ts" /* Ts */:
18430                 return 3 /* TS */;
18431             case ".tsx" /* Tsx */:
18432                 return 4 /* TSX */;
18433             case ".json" /* Json */:
18434                 return 6 /* JSON */;
18435             default:
18436                 return 0 /* Unknown */;
18437         }
18438     }
18439     ts.getScriptKindFromFileName = getScriptKindFromFileName;
18440     /**
18441      *  List of supported extensions in order of file resolution precedence.
18442      */
18443     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18444     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18445     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18446     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18447     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18448     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18449     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18450     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18451     function getSupportedExtensions(options, extraFileExtensions) {
18452         var needJsExtensions = options && options.allowJs;
18453         if (!extraFileExtensions || extraFileExtensions.length === 0) {
18454             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18455         }
18456         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18457         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18458     }
18459     ts.getSupportedExtensions = getSupportedExtensions;
18460     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18461         if (!options || !options.resolveJsonModule) {
18462             return supportedExtensions;
18463         }
18464         if (supportedExtensions === allSupportedExtensions) {
18465             return allSupportedExtensionsWithJson;
18466         }
18467         if (supportedExtensions === ts.supportedTSExtensions) {
18468             return ts.supportedTSExtensionsWithJson;
18469         }
18470         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18471     }
18472     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18473     function isJSLike(scriptKind) {
18474         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18475     }
18476     function hasJSFileExtension(fileName) {
18477         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18478     }
18479     ts.hasJSFileExtension = hasJSFileExtension;
18480     function hasTSFileExtension(fileName) {
18481         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18482     }
18483     ts.hasTSFileExtension = hasTSFileExtension;
18484     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18485         if (!fileName) {
18486             return false;
18487         }
18488         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18489         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18490             var extension = _a[_i];
18491             if (ts.fileExtensionIs(fileName, extension)) {
18492                 return true;
18493             }
18494         }
18495         return false;
18496     }
18497     ts.isSupportedSourceFileName = isSupportedSourceFileName;
18498     /**
18499      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18500      * aligned to the offset of the highest priority extension in the
18501      * allSupportedExtensions array.
18502      */
18503     var ExtensionPriority;
18504     (function (ExtensionPriority) {
18505         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18506         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18507         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18508         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18509     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18510     function getExtensionPriority(path, supportedExtensions) {
18511         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18512             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18513                 return adjustExtensionPriority(i, supportedExtensions);
18514             }
18515         }
18516         // If its not in the list of supported extensions, this is likely a
18517         // TypeScript file with a non-ts extension
18518         return 0 /* Highest */;
18519     }
18520     ts.getExtensionPriority = getExtensionPriority;
18521     /**
18522      * Adjusts an extension priority to be the highest priority within the same range.
18523      */
18524     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18525         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18526             return 0 /* TypeScriptFiles */;
18527         }
18528         else if (extensionPriority < supportedExtensions.length) {
18529             return 2 /* DeclarationAndJavaScriptFiles */;
18530         }
18531         else {
18532             return supportedExtensions.length;
18533         }
18534     }
18535     ts.adjustExtensionPriority = adjustExtensionPriority;
18536     /**
18537      * Gets the next lowest extension priority for a given priority.
18538      */
18539     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18540         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18541             return 2 /* DeclarationAndJavaScriptFiles */;
18542         }
18543         else {
18544             return supportedExtensions.length;
18545         }
18546     }
18547     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18548     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18549     function removeFileExtension(path) {
18550         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18551             var ext = extensionsToRemove_1[_i];
18552             var extensionless = tryRemoveExtension(path, ext);
18553             if (extensionless !== undefined) {
18554                 return extensionless;
18555             }
18556         }
18557         return path;
18558     }
18559     ts.removeFileExtension = removeFileExtension;
18560     function tryRemoveExtension(path, extension) {
18561         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18562     }
18563     ts.tryRemoveExtension = tryRemoveExtension;
18564     function removeExtension(path, extension) {
18565         return path.substring(0, path.length - extension.length);
18566     }
18567     ts.removeExtension = removeExtension;
18568     function changeExtension(path, newExtension) {
18569         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18570     }
18571     ts.changeExtension = changeExtension;
18572     function tryParsePattern(pattern) {
18573         // This should be verified outside of here and a proper error thrown.
18574         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18575         var indexOfStar = pattern.indexOf("*");
18576         return indexOfStar === -1 ? undefined : {
18577             prefix: pattern.substr(0, indexOfStar),
18578             suffix: pattern.substr(indexOfStar + 1)
18579         };
18580     }
18581     ts.tryParsePattern = tryParsePattern;
18582     function positionIsSynthesized(pos) {
18583         // This is a fast way of testing the following conditions:
18584         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
18585         return !(pos >= 0);
18586     }
18587     ts.positionIsSynthesized = positionIsSynthesized;
18588     /** True if an extension is one of the supported TypeScript extensions. */
18589     function extensionIsTS(ext) {
18590         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18591     }
18592     ts.extensionIsTS = extensionIsTS;
18593     function resolutionExtensionIsTSOrJson(ext) {
18594         return extensionIsTS(ext) || ext === ".json" /* Json */;
18595     }
18596     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18597     /**
18598      * Gets the extension from a path.
18599      * Path must have a valid extension.
18600      */
18601     function extensionFromPath(path) {
18602         var ext = tryGetExtensionFromPath(path);
18603         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18604     }
18605     ts.extensionFromPath = extensionFromPath;
18606     function isAnySupportedFileExtension(path) {
18607         return tryGetExtensionFromPath(path) !== undefined;
18608     }
18609     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18610     function tryGetExtensionFromPath(path) {
18611         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18612     }
18613     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18614     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18615         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18616     }
18617     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18618     ts.emptyFileSystemEntries = {
18619         files: ts.emptyArray,
18620         directories: ts.emptyArray
18621     };
18622     /**
18623      * patternStrings contains both pattern strings (containing "*") and regular strings.
18624      * Return an exact match if possible, or a pattern match, or undefined.
18625      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18626      */
18627     function matchPatternOrExact(patternStrings, candidate) {
18628         var patterns = [];
18629         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18630             var patternString = patternStrings_1[_i];
18631             if (!hasZeroOrOneAsteriskCharacter(patternString))
18632                 continue;
18633             var pattern = tryParsePattern(patternString);
18634             if (pattern) {
18635                 patterns.push(pattern);
18636             }
18637             else if (patternString === candidate) {
18638                 // pattern was matched as is - no need to search further
18639                 return patternString;
18640             }
18641         }
18642         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18643     }
18644     ts.matchPatternOrExact = matchPatternOrExact;
18645     function sliceAfter(arr, value) {
18646         var index = arr.indexOf(value);
18647         ts.Debug.assert(index !== -1);
18648         return arr.slice(index);
18649     }
18650     ts.sliceAfter = sliceAfter;
18651     function addRelatedInfo(diagnostic) {
18652         var _a;
18653         var relatedInformation = [];
18654         for (var _i = 1; _i < arguments.length; _i++) {
18655             relatedInformation[_i - 1] = arguments[_i];
18656         }
18657         if (!relatedInformation.length) {
18658             return diagnostic;
18659         }
18660         if (!diagnostic.relatedInformation) {
18661             diagnostic.relatedInformation = [];
18662         }
18663         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18664         return diagnostic;
18665     }
18666     ts.addRelatedInfo = addRelatedInfo;
18667     function minAndMax(arr, getValue) {
18668         ts.Debug.assert(arr.length !== 0);
18669         var min = getValue(arr[0]);
18670         var max = min;
18671         for (var i = 1; i < arr.length; i++) {
18672             var value = getValue(arr[i]);
18673             if (value < min) {
18674                 min = value;
18675             }
18676             else if (value > max) {
18677                 max = value;
18678             }
18679         }
18680         return { min: min, max: max };
18681     }
18682     ts.minAndMax = minAndMax;
18683     var NodeSet = /** @class */ (function () {
18684         function NodeSet() {
18685             this.map = ts.createMap();
18686         }
18687         NodeSet.prototype.add = function (node) {
18688             this.map.set(String(ts.getNodeId(node)), node);
18689         };
18690         NodeSet.prototype.tryAdd = function (node) {
18691             if (this.has(node))
18692                 return false;
18693             this.add(node);
18694             return true;
18695         };
18696         NodeSet.prototype.has = function (node) {
18697             return this.map.has(String(ts.getNodeId(node)));
18698         };
18699         NodeSet.prototype.forEach = function (cb) {
18700             this.map.forEach(cb);
18701         };
18702         NodeSet.prototype.some = function (pred) {
18703             return forEachEntry(this.map, pred) || false;
18704         };
18705         return NodeSet;
18706     }());
18707     ts.NodeSet = NodeSet;
18708     var NodeMap = /** @class */ (function () {
18709         function NodeMap() {
18710             this.map = ts.createMap();
18711         }
18712         NodeMap.prototype.get = function (node) {
18713             var res = this.map.get(String(ts.getNodeId(node)));
18714             return res && res.value;
18715         };
18716         NodeMap.prototype.getOrUpdate = function (node, setValue) {
18717             var res = this.get(node);
18718             if (res)
18719                 return res;
18720             var value = setValue();
18721             this.set(node, value);
18722             return value;
18723         };
18724         NodeMap.prototype.set = function (node, value) {
18725             this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
18726         };
18727         NodeMap.prototype.has = function (node) {
18728             return this.map.has(String(ts.getNodeId(node)));
18729         };
18730         NodeMap.prototype.forEach = function (cb) {
18731             this.map.forEach(function (_a) {
18732                 var node = _a.node, value = _a.value;
18733                 return cb(value, node);
18734             });
18735         };
18736         return NodeMap;
18737     }());
18738     ts.NodeMap = NodeMap;
18739     function rangeOfNode(node) {
18740         return { pos: getTokenPosOfNode(node), end: node.end };
18741     }
18742     ts.rangeOfNode = rangeOfNode;
18743     function rangeOfTypeParameters(typeParameters) {
18744         // Include the `<>`
18745         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18746     }
18747     ts.rangeOfTypeParameters = rangeOfTypeParameters;
18748     function skipTypeChecking(sourceFile, options, host) {
18749         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18750         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18751         // '/// <reference no-default-lib="true"/>' directive.
18752         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18753             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18754             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18755     }
18756     ts.skipTypeChecking = skipTypeChecking;
18757     function isJsonEqual(a, b) {
18758         // eslint-disable-next-line no-null/no-null
18759         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18760     }
18761     ts.isJsonEqual = isJsonEqual;
18762     function getOrUpdate(map, key, getDefault) {
18763         var got = map.get(key);
18764         if (got === undefined) {
18765             var value = getDefault();
18766             map.set(key, value);
18767             return value;
18768         }
18769         else {
18770             return got;
18771         }
18772     }
18773     ts.getOrUpdate = getOrUpdate;
18774     /**
18775      * Converts a bigint literal string, e.g. `0x1234n`,
18776      * to its decimal string representation, e.g. `4660`.
18777      */
18778     function parsePseudoBigInt(stringValue) {
18779         var log2Base;
18780         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18781             case 98 /* b */:
18782             case 66 /* B */: // 0b or 0B
18783                 log2Base = 1;
18784                 break;
18785             case 111 /* o */:
18786             case 79 /* O */: // 0o or 0O
18787                 log2Base = 3;
18788                 break;
18789             case 120 /* x */:
18790             case 88 /* X */: // 0x or 0X
18791                 log2Base = 4;
18792                 break;
18793             default: // already in decimal; omit trailing "n"
18794                 var nIndex = stringValue.length - 1;
18795                 // Skip leading 0s
18796                 var nonZeroStart = 0;
18797                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18798                     nonZeroStart++;
18799                 }
18800                 return stringValue.slice(nonZeroStart, nIndex) || "0";
18801         }
18802         // Omit leading "0b", "0o", or "0x", and trailing "n"
18803         var startIndex = 2, endIndex = stringValue.length - 1;
18804         var bitsNeeded = (endIndex - startIndex) * log2Base;
18805         // Stores the value specified by the string as a LE array of 16-bit integers
18806         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18807         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18808         // Add the digits, one at a time
18809         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18810             var segment = bitOffset >>> 4;
18811             var digitChar = stringValue.charCodeAt(i);
18812             // Find character range: 0-9 < A-F < a-f
18813             var digit = digitChar <= 57 /* _9 */
18814                 ? digitChar - 48 /* _0 */
18815                 : 10 + digitChar -
18816                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18817             var shiftedDigit = digit << (bitOffset & 15);
18818             segments[segment] |= shiftedDigit;
18819             var residual = shiftedDigit >>> 16;
18820             if (residual)
18821                 segments[segment + 1] |= residual; // overflows segment
18822         }
18823         // Repeatedly divide segments by 10 and add remainder to base10Value
18824         var base10Value = "";
18825         var firstNonzeroSegment = segments.length - 1;
18826         var segmentsRemaining = true;
18827         while (segmentsRemaining) {
18828             var mod10 = 0;
18829             segmentsRemaining = false;
18830             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18831                 var newSegment = mod10 << 16 | segments[segment];
18832                 var segmentValue = (newSegment / 10) | 0;
18833                 segments[segment] = segmentValue;
18834                 mod10 = newSegment - segmentValue * 10;
18835                 if (segmentValue && !segmentsRemaining) {
18836                     firstNonzeroSegment = segment;
18837                     segmentsRemaining = true;
18838                 }
18839             }
18840             base10Value = mod10 + base10Value;
18841         }
18842         return base10Value;
18843     }
18844     ts.parsePseudoBigInt = parsePseudoBigInt;
18845     function pseudoBigIntToString(_a) {
18846         var negative = _a.negative, base10Value = _a.base10Value;
18847         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18848     }
18849     ts.pseudoBigIntToString = pseudoBigIntToString;
18850     function isValidTypeOnlyAliasUseSite(useSite) {
18851         return !!(useSite.flags & 8388608 /* Ambient */)
18852             || isPartOfTypeQuery(useSite)
18853             || isIdentifierInNonEmittingHeritageClause(useSite)
18854             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18855             || !isExpressionNode(useSite);
18856     }
18857     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18858     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18859         return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
18860     }
18861     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18862     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18863         while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
18864             node = node.parent;
18865         }
18866         if (node.kind !== 154 /* ComputedPropertyName */) {
18867             return false;
18868         }
18869         if (hasModifier(node.parent, 128 /* Abstract */)) {
18870             return true;
18871         }
18872         var containerKind = node.parent.parent.kind;
18873         return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
18874     }
18875     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18876     function isIdentifierInNonEmittingHeritageClause(node) {
18877         if (node.kind !== 75 /* Identifier */)
18878             return false;
18879         var heritageClause = findAncestor(node.parent, function (parent) {
18880             switch (parent.kind) {
18881                 case 279 /* HeritageClause */:
18882                     return true;
18883                 case 194 /* PropertyAccessExpression */:
18884                 case 216 /* ExpressionWithTypeArguments */:
18885                     return false;
18886                 default:
18887                     return "quit";
18888             }
18889         });
18890         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
18891     }
18892     function isIdentifierTypeReference(node) {
18893         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18894     }
18895     ts.isIdentifierTypeReference = isIdentifierTypeReference;
18896     function arrayIsHomogeneous(array, comparer) {
18897         if (comparer === void 0) { comparer = ts.equateValues; }
18898         if (array.length < 2)
18899             return true;
18900         var first = array[0];
18901         for (var i = 1, length_1 = array.length; i < length_1; i++) {
18902             var target = array[i];
18903             if (!comparer(first, target))
18904                 return false;
18905         }
18906         return true;
18907     }
18908     ts.arrayIsHomogeneous = arrayIsHomogeneous;
18909 })(ts || (ts = {}));
18910 var ts;
18911 (function (ts) {
18912     var SignatureFlags;
18913     (function (SignatureFlags) {
18914         SignatureFlags[SignatureFlags["None"] = 0] = "None";
18915         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
18916         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
18917         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
18918         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
18919         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
18920     })(SignatureFlags || (SignatureFlags = {}));
18921     var NodeConstructor;
18922     var TokenConstructor;
18923     var IdentifierConstructor;
18924     var PrivateIdentifierConstructor;
18925     var SourceFileConstructor;
18926     function createNode(kind, pos, end) {
18927         if (kind === 290 /* SourceFile */) {
18928             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
18929         }
18930         else if (kind === 75 /* Identifier */) {
18931             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
18932         }
18933         else if (kind === 76 /* PrivateIdentifier */) {
18934             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
18935         }
18936         else if (!ts.isNodeKind(kind)) {
18937             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
18938         }
18939         else {
18940             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
18941         }
18942     }
18943     ts.createNode = createNode;
18944     function visitNode(cbNode, node) {
18945         return node && cbNode(node);
18946     }
18947     function visitNodes(cbNode, cbNodes, nodes) {
18948         if (nodes) {
18949             if (cbNodes) {
18950                 return cbNodes(nodes);
18951             }
18952             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
18953                 var node = nodes_1[_i];
18954                 var result = cbNode(node);
18955                 if (result) {
18956                     return result;
18957                 }
18958             }
18959         }
18960     }
18961     /*@internal*/
18962     function isJSDocLikeText(text, start) {
18963         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
18964             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
18965             text.charCodeAt(start + 3) !== 47 /* slash */;
18966     }
18967     ts.isJSDocLikeText = isJSDocLikeText;
18968     /**
18969      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
18970      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
18971      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
18972      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
18973      *
18974      * @param node a given node to visit its children
18975      * @param cbNode a callback to be invoked for all child nodes
18976      * @param cbNodes a callback to be invoked for embedded array
18977      *
18978      * @remarks `forEachChild` must visit the children of a node in the order
18979      * that they appear in the source code. The language service depends on this property to locate nodes by position.
18980      */
18981     function forEachChild(node, cbNode, cbNodes) {
18982         if (!node || node.kind <= 152 /* LastToken */) {
18983             return;
18984         }
18985         switch (node.kind) {
18986             case 153 /* QualifiedName */:
18987                 return visitNode(cbNode, node.left) ||
18988                     visitNode(cbNode, node.right);
18989             case 155 /* TypeParameter */:
18990                 return visitNode(cbNode, node.name) ||
18991                     visitNode(cbNode, node.constraint) ||
18992                     visitNode(cbNode, node.default) ||
18993                     visitNode(cbNode, node.expression);
18994             case 282 /* ShorthandPropertyAssignment */:
18995                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18996                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18997                     visitNode(cbNode, node.name) ||
18998                     visitNode(cbNode, node.questionToken) ||
18999                     visitNode(cbNode, node.exclamationToken) ||
19000                     visitNode(cbNode, node.equalsToken) ||
19001                     visitNode(cbNode, node.objectAssignmentInitializer);
19002             case 283 /* SpreadAssignment */:
19003                 return visitNode(cbNode, node.expression);
19004             case 156 /* Parameter */:
19005                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19006                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19007                     visitNode(cbNode, node.dotDotDotToken) ||
19008                     visitNode(cbNode, node.name) ||
19009                     visitNode(cbNode, node.questionToken) ||
19010                     visitNode(cbNode, node.type) ||
19011                     visitNode(cbNode, node.initializer);
19012             case 159 /* PropertyDeclaration */:
19013                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19014                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19015                     visitNode(cbNode, node.name) ||
19016                     visitNode(cbNode, node.questionToken) ||
19017                     visitNode(cbNode, node.exclamationToken) ||
19018                     visitNode(cbNode, node.type) ||
19019                     visitNode(cbNode, node.initializer);
19020             case 158 /* PropertySignature */:
19021                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19022                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19023                     visitNode(cbNode, node.name) ||
19024                     visitNode(cbNode, node.questionToken) ||
19025                     visitNode(cbNode, node.type) ||
19026                     visitNode(cbNode, node.initializer);
19027             case 281 /* PropertyAssignment */:
19028                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19029                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19030                     visitNode(cbNode, node.name) ||
19031                     visitNode(cbNode, node.questionToken) ||
19032                     visitNode(cbNode, node.initializer);
19033             case 242 /* VariableDeclaration */:
19034                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19035                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19036                     visitNode(cbNode, node.name) ||
19037                     visitNode(cbNode, node.exclamationToken) ||
19038                     visitNode(cbNode, node.type) ||
19039                     visitNode(cbNode, node.initializer);
19040             case 191 /* BindingElement */:
19041                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19042                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19043                     visitNode(cbNode, node.dotDotDotToken) ||
19044                     visitNode(cbNode, node.propertyName) ||
19045                     visitNode(cbNode, node.name) ||
19046                     visitNode(cbNode, node.initializer);
19047             case 170 /* FunctionType */:
19048             case 171 /* ConstructorType */:
19049             case 165 /* CallSignature */:
19050             case 166 /* ConstructSignature */:
19051             case 167 /* IndexSignature */:
19052                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19053                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19054                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19055                     visitNodes(cbNode, cbNodes, node.parameters) ||
19056                     visitNode(cbNode, node.type);
19057             case 161 /* MethodDeclaration */:
19058             case 160 /* MethodSignature */:
19059             case 162 /* Constructor */:
19060             case 163 /* GetAccessor */:
19061             case 164 /* SetAccessor */:
19062             case 201 /* FunctionExpression */:
19063             case 244 /* FunctionDeclaration */:
19064             case 202 /* ArrowFunction */:
19065                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19066                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19067                     visitNode(cbNode, node.asteriskToken) ||
19068                     visitNode(cbNode, node.name) ||
19069                     visitNode(cbNode, node.questionToken) ||
19070                     visitNode(cbNode, node.exclamationToken) ||
19071                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19072                     visitNodes(cbNode, cbNodes, node.parameters) ||
19073                     visitNode(cbNode, node.type) ||
19074                     visitNode(cbNode, node.equalsGreaterThanToken) ||
19075                     visitNode(cbNode, node.body);
19076             case 169 /* TypeReference */:
19077                 return visitNode(cbNode, node.typeName) ||
19078                     visitNodes(cbNode, cbNodes, node.typeArguments);
19079             case 168 /* TypePredicate */:
19080                 return visitNode(cbNode, node.assertsModifier) ||
19081                     visitNode(cbNode, node.parameterName) ||
19082                     visitNode(cbNode, node.type);
19083             case 172 /* TypeQuery */:
19084                 return visitNode(cbNode, node.exprName);
19085             case 173 /* TypeLiteral */:
19086                 return visitNodes(cbNode, cbNodes, node.members);
19087             case 174 /* ArrayType */:
19088                 return visitNode(cbNode, node.elementType);
19089             case 175 /* TupleType */:
19090                 return visitNodes(cbNode, cbNodes, node.elementTypes);
19091             case 178 /* UnionType */:
19092             case 179 /* IntersectionType */:
19093                 return visitNodes(cbNode, cbNodes, node.types);
19094             case 180 /* ConditionalType */:
19095                 return visitNode(cbNode, node.checkType) ||
19096                     visitNode(cbNode, node.extendsType) ||
19097                     visitNode(cbNode, node.trueType) ||
19098                     visitNode(cbNode, node.falseType);
19099             case 181 /* InferType */:
19100                 return visitNode(cbNode, node.typeParameter);
19101             case 188 /* ImportType */:
19102                 return visitNode(cbNode, node.argument) ||
19103                     visitNode(cbNode, node.qualifier) ||
19104                     visitNodes(cbNode, cbNodes, node.typeArguments);
19105             case 182 /* ParenthesizedType */:
19106             case 184 /* TypeOperator */:
19107                 return visitNode(cbNode, node.type);
19108             case 185 /* IndexedAccessType */:
19109                 return visitNode(cbNode, node.objectType) ||
19110                     visitNode(cbNode, node.indexType);
19111             case 186 /* MappedType */:
19112                 return visitNode(cbNode, node.readonlyToken) ||
19113                     visitNode(cbNode, node.typeParameter) ||
19114                     visitNode(cbNode, node.questionToken) ||
19115                     visitNode(cbNode, node.type);
19116             case 187 /* LiteralType */:
19117                 return visitNode(cbNode, node.literal);
19118             case 189 /* ObjectBindingPattern */:
19119             case 190 /* ArrayBindingPattern */:
19120                 return visitNodes(cbNode, cbNodes, node.elements);
19121             case 192 /* ArrayLiteralExpression */:
19122                 return visitNodes(cbNode, cbNodes, node.elements);
19123             case 193 /* ObjectLiteralExpression */:
19124                 return visitNodes(cbNode, cbNodes, node.properties);
19125             case 194 /* PropertyAccessExpression */:
19126                 return visitNode(cbNode, node.expression) ||
19127                     visitNode(cbNode, node.questionDotToken) ||
19128                     visitNode(cbNode, node.name);
19129             case 195 /* ElementAccessExpression */:
19130                 return visitNode(cbNode, node.expression) ||
19131                     visitNode(cbNode, node.questionDotToken) ||
19132                     visitNode(cbNode, node.argumentExpression);
19133             case 196 /* CallExpression */:
19134             case 197 /* NewExpression */:
19135                 return visitNode(cbNode, node.expression) ||
19136                     visitNode(cbNode, node.questionDotToken) ||
19137                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19138                     visitNodes(cbNode, cbNodes, node.arguments);
19139             case 198 /* TaggedTemplateExpression */:
19140                 return visitNode(cbNode, node.tag) ||
19141                     visitNode(cbNode, node.questionDotToken) ||
19142                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19143                     visitNode(cbNode, node.template);
19144             case 199 /* TypeAssertionExpression */:
19145                 return visitNode(cbNode, node.type) ||
19146                     visitNode(cbNode, node.expression);
19147             case 200 /* ParenthesizedExpression */:
19148                 return visitNode(cbNode, node.expression);
19149             case 203 /* DeleteExpression */:
19150                 return visitNode(cbNode, node.expression);
19151             case 204 /* TypeOfExpression */:
19152                 return visitNode(cbNode, node.expression);
19153             case 205 /* VoidExpression */:
19154                 return visitNode(cbNode, node.expression);
19155             case 207 /* PrefixUnaryExpression */:
19156                 return visitNode(cbNode, node.operand);
19157             case 212 /* YieldExpression */:
19158                 return visitNode(cbNode, node.asteriskToken) ||
19159                     visitNode(cbNode, node.expression);
19160             case 206 /* AwaitExpression */:
19161                 return visitNode(cbNode, node.expression);
19162             case 208 /* PostfixUnaryExpression */:
19163                 return visitNode(cbNode, node.operand);
19164             case 209 /* BinaryExpression */:
19165                 return visitNode(cbNode, node.left) ||
19166                     visitNode(cbNode, node.operatorToken) ||
19167                     visitNode(cbNode, node.right);
19168             case 217 /* AsExpression */:
19169                 return visitNode(cbNode, node.expression) ||
19170                     visitNode(cbNode, node.type);
19171             case 218 /* NonNullExpression */:
19172                 return visitNode(cbNode, node.expression);
19173             case 219 /* MetaProperty */:
19174                 return visitNode(cbNode, node.name);
19175             case 210 /* ConditionalExpression */:
19176                 return visitNode(cbNode, node.condition) ||
19177                     visitNode(cbNode, node.questionToken) ||
19178                     visitNode(cbNode, node.whenTrue) ||
19179                     visitNode(cbNode, node.colonToken) ||
19180                     visitNode(cbNode, node.whenFalse);
19181             case 213 /* SpreadElement */:
19182                 return visitNode(cbNode, node.expression);
19183             case 223 /* Block */:
19184             case 250 /* ModuleBlock */:
19185                 return visitNodes(cbNode, cbNodes, node.statements);
19186             case 290 /* SourceFile */:
19187                 return visitNodes(cbNode, cbNodes, node.statements) ||
19188                     visitNode(cbNode, node.endOfFileToken);
19189             case 225 /* VariableStatement */:
19190                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19191                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19192                     visitNode(cbNode, node.declarationList);
19193             case 243 /* VariableDeclarationList */:
19194                 return visitNodes(cbNode, cbNodes, node.declarations);
19195             case 226 /* ExpressionStatement */:
19196                 return visitNode(cbNode, node.expression);
19197             case 227 /* IfStatement */:
19198                 return visitNode(cbNode, node.expression) ||
19199                     visitNode(cbNode, node.thenStatement) ||
19200                     visitNode(cbNode, node.elseStatement);
19201             case 228 /* DoStatement */:
19202                 return visitNode(cbNode, node.statement) ||
19203                     visitNode(cbNode, node.expression);
19204             case 229 /* WhileStatement */:
19205                 return visitNode(cbNode, node.expression) ||
19206                     visitNode(cbNode, node.statement);
19207             case 230 /* ForStatement */:
19208                 return visitNode(cbNode, node.initializer) ||
19209                     visitNode(cbNode, node.condition) ||
19210                     visitNode(cbNode, node.incrementor) ||
19211                     visitNode(cbNode, node.statement);
19212             case 231 /* ForInStatement */:
19213                 return visitNode(cbNode, node.initializer) ||
19214                     visitNode(cbNode, node.expression) ||
19215                     visitNode(cbNode, node.statement);
19216             case 232 /* ForOfStatement */:
19217                 return visitNode(cbNode, node.awaitModifier) ||
19218                     visitNode(cbNode, node.initializer) ||
19219                     visitNode(cbNode, node.expression) ||
19220                     visitNode(cbNode, node.statement);
19221             case 233 /* ContinueStatement */:
19222             case 234 /* BreakStatement */:
19223                 return visitNode(cbNode, node.label);
19224             case 235 /* ReturnStatement */:
19225                 return visitNode(cbNode, node.expression);
19226             case 236 /* WithStatement */:
19227                 return visitNode(cbNode, node.expression) ||
19228                     visitNode(cbNode, node.statement);
19229             case 237 /* SwitchStatement */:
19230                 return visitNode(cbNode, node.expression) ||
19231                     visitNode(cbNode, node.caseBlock);
19232             case 251 /* CaseBlock */:
19233                 return visitNodes(cbNode, cbNodes, node.clauses);
19234             case 277 /* CaseClause */:
19235                 return visitNode(cbNode, node.expression) ||
19236                     visitNodes(cbNode, cbNodes, node.statements);
19237             case 278 /* DefaultClause */:
19238                 return visitNodes(cbNode, cbNodes, node.statements);
19239             case 238 /* LabeledStatement */:
19240                 return visitNode(cbNode, node.label) ||
19241                     visitNode(cbNode, node.statement);
19242             case 239 /* ThrowStatement */:
19243                 return visitNode(cbNode, node.expression);
19244             case 240 /* TryStatement */:
19245                 return visitNode(cbNode, node.tryBlock) ||
19246                     visitNode(cbNode, node.catchClause) ||
19247                     visitNode(cbNode, node.finallyBlock);
19248             case 280 /* CatchClause */:
19249                 return visitNode(cbNode, node.variableDeclaration) ||
19250                     visitNode(cbNode, node.block);
19251             case 157 /* Decorator */:
19252                 return visitNode(cbNode, node.expression);
19253             case 245 /* ClassDeclaration */:
19254             case 214 /* ClassExpression */:
19255                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19256                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19257                     visitNode(cbNode, node.name) ||
19258                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19259                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19260                     visitNodes(cbNode, cbNodes, node.members);
19261             case 246 /* InterfaceDeclaration */:
19262                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19263                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19264                     visitNode(cbNode, node.name) ||
19265                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19266                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19267                     visitNodes(cbNode, cbNodes, node.members);
19268             case 247 /* TypeAliasDeclaration */:
19269                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19270                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19271                     visitNode(cbNode, node.name) ||
19272                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19273                     visitNode(cbNode, node.type);
19274             case 248 /* EnumDeclaration */:
19275                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19276                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19277                     visitNode(cbNode, node.name) ||
19278                     visitNodes(cbNode, cbNodes, node.members);
19279             case 284 /* EnumMember */:
19280                 return visitNode(cbNode, node.name) ||
19281                     visitNode(cbNode, node.initializer);
19282             case 249 /* ModuleDeclaration */:
19283                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19284                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19285                     visitNode(cbNode, node.name) ||
19286                     visitNode(cbNode, node.body);
19287             case 253 /* ImportEqualsDeclaration */:
19288                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19289                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19290                     visitNode(cbNode, node.name) ||
19291                     visitNode(cbNode, node.moduleReference);
19292             case 254 /* ImportDeclaration */:
19293                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19294                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19295                     visitNode(cbNode, node.importClause) ||
19296                     visitNode(cbNode, node.moduleSpecifier);
19297             case 255 /* ImportClause */:
19298                 return visitNode(cbNode, node.name) ||
19299                     visitNode(cbNode, node.namedBindings);
19300             case 252 /* NamespaceExportDeclaration */:
19301                 return visitNode(cbNode, node.name);
19302             case 256 /* NamespaceImport */:
19303                 return visitNode(cbNode, node.name);
19304             case 262 /* NamespaceExport */:
19305                 return visitNode(cbNode, node.name);
19306             case 257 /* NamedImports */:
19307             case 261 /* NamedExports */:
19308                 return visitNodes(cbNode, cbNodes, node.elements);
19309             case 260 /* ExportDeclaration */:
19310                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19311                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19312                     visitNode(cbNode, node.exportClause) ||
19313                     visitNode(cbNode, node.moduleSpecifier);
19314             case 258 /* ImportSpecifier */:
19315             case 263 /* ExportSpecifier */:
19316                 return visitNode(cbNode, node.propertyName) ||
19317                     visitNode(cbNode, node.name);
19318             case 259 /* ExportAssignment */:
19319                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19320                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19321                     visitNode(cbNode, node.expression);
19322             case 211 /* TemplateExpression */:
19323                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
19324             case 221 /* TemplateSpan */:
19325                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
19326             case 154 /* ComputedPropertyName */:
19327                 return visitNode(cbNode, node.expression);
19328             case 279 /* HeritageClause */:
19329                 return visitNodes(cbNode, cbNodes, node.types);
19330             case 216 /* ExpressionWithTypeArguments */:
19331                 return visitNode(cbNode, node.expression) ||
19332                     visitNodes(cbNode, cbNodes, node.typeArguments);
19333             case 265 /* ExternalModuleReference */:
19334                 return visitNode(cbNode, node.expression);
19335             case 264 /* MissingDeclaration */:
19336                 return visitNodes(cbNode, cbNodes, node.decorators);
19337             case 327 /* CommaListExpression */:
19338                 return visitNodes(cbNode, cbNodes, node.elements);
19339             case 266 /* JsxElement */:
19340                 return visitNode(cbNode, node.openingElement) ||
19341                     visitNodes(cbNode, cbNodes, node.children) ||
19342                     visitNode(cbNode, node.closingElement);
19343             case 270 /* JsxFragment */:
19344                 return visitNode(cbNode, node.openingFragment) ||
19345                     visitNodes(cbNode, cbNodes, node.children) ||
19346                     visitNode(cbNode, node.closingFragment);
19347             case 267 /* JsxSelfClosingElement */:
19348             case 268 /* JsxOpeningElement */:
19349                 return visitNode(cbNode, node.tagName) ||
19350                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19351                     visitNode(cbNode, node.attributes);
19352             case 274 /* JsxAttributes */:
19353                 return visitNodes(cbNode, cbNodes, node.properties);
19354             case 273 /* JsxAttribute */:
19355                 return visitNode(cbNode, node.name) ||
19356                     visitNode(cbNode, node.initializer);
19357             case 275 /* JsxSpreadAttribute */:
19358                 return visitNode(cbNode, node.expression);
19359             case 276 /* JsxExpression */:
19360                 return visitNode(cbNode, node.dotDotDotToken) ||
19361                     visitNode(cbNode, node.expression);
19362             case 269 /* JsxClosingElement */:
19363                 return visitNode(cbNode, node.tagName);
19364             case 176 /* OptionalType */:
19365             case 177 /* RestType */:
19366             case 294 /* JSDocTypeExpression */:
19367             case 298 /* JSDocNonNullableType */:
19368             case 297 /* JSDocNullableType */:
19369             case 299 /* JSDocOptionalType */:
19370             case 301 /* JSDocVariadicType */:
19371                 return visitNode(cbNode, node.type);
19372             case 300 /* JSDocFunctionType */:
19373                 return visitNodes(cbNode, cbNodes, node.parameters) ||
19374                     visitNode(cbNode, node.type);
19375             case 303 /* JSDocComment */:
19376                 return visitNodes(cbNode, cbNodes, node.tags);
19377             case 317 /* JSDocParameterTag */:
19378             case 323 /* JSDocPropertyTag */:
19379                 return visitNode(cbNode, node.tagName) ||
19380                     (node.isNameFirst
19381                         ? visitNode(cbNode, node.name) ||
19382                             visitNode(cbNode, node.typeExpression)
19383                         : visitNode(cbNode, node.typeExpression) ||
19384                             visitNode(cbNode, node.name));
19385             case 309 /* JSDocAuthorTag */:
19386                 return visitNode(cbNode, node.tagName);
19387             case 308 /* JSDocImplementsTag */:
19388                 return visitNode(cbNode, node.tagName) ||
19389                     visitNode(cbNode, node.class);
19390             case 307 /* JSDocAugmentsTag */:
19391                 return visitNode(cbNode, node.tagName) ||
19392                     visitNode(cbNode, node.class);
19393             case 321 /* JSDocTemplateTag */:
19394                 return visitNode(cbNode, node.tagName) ||
19395                     visitNode(cbNode, node.constraint) ||
19396                     visitNodes(cbNode, cbNodes, node.typeParameters);
19397             case 322 /* JSDocTypedefTag */:
19398                 return visitNode(cbNode, node.tagName) ||
19399                     (node.typeExpression &&
19400                         node.typeExpression.kind === 294 /* JSDocTypeExpression */
19401                         ? visitNode(cbNode, node.typeExpression) ||
19402                             visitNode(cbNode, node.fullName)
19403                         : visitNode(cbNode, node.fullName) ||
19404                             visitNode(cbNode, node.typeExpression));
19405             case 315 /* JSDocCallbackTag */:
19406                 return visitNode(cbNode, node.tagName) ||
19407                     visitNode(cbNode, node.fullName) ||
19408                     visitNode(cbNode, node.typeExpression);
19409             case 318 /* JSDocReturnTag */:
19410             case 320 /* JSDocTypeTag */:
19411             case 319 /* JSDocThisTag */:
19412             case 316 /* JSDocEnumTag */:
19413                 return visitNode(cbNode, node.tagName) ||
19414                     visitNode(cbNode, node.typeExpression);
19415             case 305 /* JSDocSignature */:
19416                 return ts.forEach(node.typeParameters, cbNode) ||
19417                     ts.forEach(node.parameters, cbNode) ||
19418                     visitNode(cbNode, node.type);
19419             case 304 /* JSDocTypeLiteral */:
19420                 return ts.forEach(node.jsDocPropertyTags, cbNode);
19421             case 306 /* JSDocTag */:
19422             case 310 /* JSDocClassTag */:
19423             case 311 /* JSDocPublicTag */:
19424             case 312 /* JSDocPrivateTag */:
19425             case 313 /* JSDocProtectedTag */:
19426             case 314 /* JSDocReadonlyTag */:
19427                 return visitNode(cbNode, node.tagName);
19428             case 326 /* PartiallyEmittedExpression */:
19429                 return visitNode(cbNode, node.expression);
19430         }
19431     }
19432     ts.forEachChild = forEachChild;
19433     /** @internal */
19434     /**
19435      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
19436      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
19437      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
19438      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
19439      *
19440      * @param node a given node to visit its children
19441      * @param cbNode a callback to be invoked for all child nodes
19442      * @param cbNodes a callback to be invoked for embedded array
19443      *
19444      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
19445      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
19446      */
19447     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
19448         var stack = [rootNode];
19449         while (stack.length) {
19450             var parent = stack.pop();
19451             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
19452             if (res) {
19453                 return res;
19454             }
19455         }
19456         return;
19457         function gatherPossibleChildren(node) {
19458             var children = [];
19459             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
19460             return children;
19461             function addWorkItem(n) {
19462                 children.unshift(n);
19463             }
19464         }
19465         function visitAllPossibleChildren(parent, children) {
19466             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19467                 var child = children_1[_i];
19468                 if (ts.isArray(child)) {
19469                     if (cbNodes) {
19470                         var res = cbNodes(child, parent);
19471                         if (res) {
19472                             if (res === "skip")
19473                                 continue;
19474                             return res;
19475                         }
19476                     }
19477                     for (var i = child.length - 1; i >= 0; i--) {
19478                         var realChild = child[i];
19479                         var res = cbNode(realChild, parent);
19480                         if (res) {
19481                             if (res === "skip")
19482                                 continue;
19483                             return res;
19484                         }
19485                         stack.push(realChild);
19486                     }
19487                 }
19488                 else {
19489                     stack.push(child);
19490                     var res = cbNode(child, parent);
19491                     if (res) {
19492                         if (res === "skip")
19493                             continue;
19494                         return res;
19495                     }
19496                 }
19497             }
19498         }
19499     }
19500     ts.forEachChildRecursively = forEachChildRecursively;
19501     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
19502         if (setParentNodes === void 0) { setParentNodes = false; }
19503         ts.performance.mark("beforeParse");
19504         var result;
19505         ts.perfLogger.logStartParseSourceFile(fileName);
19506         if (languageVersion === 100 /* JSON */) {
19507             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
19508         }
19509         else {
19510             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
19511         }
19512         ts.perfLogger.logStopParseSourceFile();
19513         ts.performance.mark("afterParse");
19514         ts.performance.measure("Parse", "beforeParse", "afterParse");
19515         return result;
19516     }
19517     ts.createSourceFile = createSourceFile;
19518     function parseIsolatedEntityName(text, languageVersion) {
19519         return Parser.parseIsolatedEntityName(text, languageVersion);
19520     }
19521     ts.parseIsolatedEntityName = parseIsolatedEntityName;
19522     /**
19523      * Parse json text into SyntaxTree and return node and parse errors if any
19524      * @param fileName
19525      * @param sourceText
19526      */
19527     function parseJsonText(fileName, sourceText) {
19528         return Parser.parseJsonText(fileName, sourceText);
19529     }
19530     ts.parseJsonText = parseJsonText;
19531     // See also `isExternalOrCommonJsModule` in utilities.ts
19532     function isExternalModule(file) {
19533         return file.externalModuleIndicator !== undefined;
19534     }
19535     ts.isExternalModule = isExternalModule;
19536     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
19537     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
19538     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
19539     // this file as possible.
19540     //
19541     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
19542     // from this SourceFile that are being held onto may change as a result (including
19543     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
19544     // be used once 'update' is called on it.
19545     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
19546         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
19547         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
19548         // 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.
19549         // We will manually port the flag to the new source file.
19550         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
19551         return newSourceFile;
19552     }
19553     ts.updateSourceFile = updateSourceFile;
19554     /* @internal */
19555     function parseIsolatedJSDocComment(content, start, length) {
19556         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
19557         if (result && result.jsDoc) {
19558             // because the jsDocComment was parsed out of the source file, it might
19559             // not be covered by the fixupParentReferences.
19560             Parser.fixupParentReferences(result.jsDoc);
19561         }
19562         return result;
19563     }
19564     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
19565     /* @internal */
19566     // Exposed only for testing.
19567     function parseJSDocTypeExpressionForTests(content, start, length) {
19568         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
19569     }
19570     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
19571     // Implement the parser as a singleton module.  We do this for perf reasons because creating
19572     // parser instances can actually be expensive enough to impact us on projects with many source
19573     // files.
19574     var Parser;
19575     (function (Parser) {
19576         // Share a single scanner across all calls to parse a source file.  This helps speed things
19577         // up by avoiding the cost of creating/compiling scanners over and over again.
19578         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
19579         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
19580         // capture constructors in 'initializeState' to avoid null checks
19581         var NodeConstructor;
19582         var TokenConstructor;
19583         var IdentifierConstructor;
19584         var PrivateIdentifierConstructor;
19585         var SourceFileConstructor;
19586         var sourceFile;
19587         var parseDiagnostics;
19588         var syntaxCursor;
19589         var currentToken;
19590         var sourceText;
19591         var nodeCount;
19592         var identifiers;
19593         var privateIdentifiers;
19594         var identifierCount;
19595         var parsingContext;
19596         var notParenthesizedArrow;
19597         // Flags that dictate what parsing context we're in.  For example:
19598         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
19599         // that some tokens that would be considered identifiers may be considered keywords.
19600         //
19601         // When adding more parser context flags, consider which is the more common case that the
19602         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
19603         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
19604         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
19605         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
19606         // all nodes would need extra state on them to store this info.
19607         //
19608         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
19609         // grammar specification.
19610         //
19611         // An important thing about these context concepts.  By default they are effectively inherited
19612         // while parsing through every grammar production.  i.e. if you don't change them, then when
19613         // you parse a sub-production, it will have the same context values as the parent production.
19614         // This is great most of the time.  After all, consider all the 'expression' grammar productions
19615         // and how nearly all of them pass along the 'in' and 'yield' context values:
19616         //
19617         // EqualityExpression[In, Yield] :
19618         //      RelationalExpression[?In, ?Yield]
19619         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
19620         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
19621         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
19622         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
19623         //
19624         // Where you have to be careful is then understanding what the points are in the grammar
19625         // where the values are *not* passed along.  For example:
19626         //
19627         // SingleNameBinding[Yield,GeneratorParameter]
19628         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
19629         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
19630         //
19631         // Here this is saying that if the GeneratorParameter context flag is set, that we should
19632         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
19633         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
19634         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
19635         // should leave the 'yield' context flag alone.
19636         //
19637         // Getting this all correct is tricky and requires careful reading of the grammar to
19638         // understand when these values should be changed versus when they should be inherited.
19639         //
19640         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
19641         // parsing.  These context flags are naturally stored and restored through normal recursive
19642         // descent parsing and unwinding.
19643         var contextFlags;
19644         // Whether or not we've had a parse error since creating the last AST node.  If we have
19645         // encountered an error, it will be stored on the next AST node we create.  Parse errors
19646         // can be broken down into three categories:
19647         //
19648         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
19649         //    character that was completely not understood.
19650         //
19651         // 2) A token was expected, but was not present.  This type of error is commonly produced
19652         //    by the 'parseExpected' function.
19653         //
19654         // 3) A token was present that no parsing function was able to consume.  This type of error
19655         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
19656         //    decides to skip the token.
19657         //
19658         // In all of these cases, we want to mark the next node as having had an error before it.
19659         // With this mark, we can know in incremental settings if this node can be reused, or if
19660         // we have to reparse it.  If we don't keep this information around, we may just reuse the
19661         // node.  in that event we would then not produce the same errors as we did before, causing
19662         // significant confusion problems.
19663         //
19664         // Note: it is necessary that this value be saved/restored during speculative/lookahead
19665         // parsing.  During lookahead parsing, we will often create a node.  That node will have
19666         // this value attached, and then this value will be set back to 'false'.  If we decide to
19667         // rewind, we must get back to the same value we had prior to the lookahead.
19668         //
19669         // Note: any errors at the end of the file that do not precede a regular node, should get
19670         // attached to the EOF token.
19671         var parseErrorBeforeNextFinishedNode = false;
19672         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
19673             if (setParentNodes === void 0) { setParentNodes = false; }
19674             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
19675             if (scriptKind === 6 /* JSON */) {
19676                 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
19677                 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
19678                 result_2.referencedFiles = ts.emptyArray;
19679                 result_2.typeReferenceDirectives = ts.emptyArray;
19680                 result_2.libReferenceDirectives = ts.emptyArray;
19681                 result_2.amdDependencies = ts.emptyArray;
19682                 result_2.hasNoDefaultLib = false;
19683                 result_2.pragmas = ts.emptyMap;
19684                 return result_2;
19685             }
19686             initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
19687             var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
19688             clearState();
19689             return result;
19690         }
19691         Parser.parseSourceFile = parseSourceFile;
19692         function parseIsolatedEntityName(content, languageVersion) {
19693             // Choice of `isDeclarationFile` should be arbitrary
19694             initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
19695             // Prime the scanner.
19696             nextToken();
19697             var entityName = parseEntityName(/*allowReservedWords*/ true);
19698             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
19699             clearState();
19700             return isInvalid ? entityName : undefined;
19701         }
19702         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
19703         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
19704             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
19705             initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
19706             // Set source file so that errors will be reported with this file name
19707             sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
19708             sourceFile.flags = contextFlags;
19709             // Prime the scanner.
19710             nextToken();
19711             var pos = getNodePos();
19712             if (token() === 1 /* EndOfFileToken */) {
19713                 sourceFile.statements = createNodeArray([], pos, pos);
19714                 sourceFile.endOfFileToken = parseTokenNode();
19715             }
19716             else {
19717                 var statement = createNode(226 /* ExpressionStatement */);
19718                 switch (token()) {
19719                     case 22 /* OpenBracketToken */:
19720                         statement.expression = parseArrayLiteralExpression();
19721                         break;
19722                     case 106 /* TrueKeyword */:
19723                     case 91 /* FalseKeyword */:
19724                     case 100 /* NullKeyword */:
19725                         statement.expression = parseTokenNode();
19726                         break;
19727                     case 40 /* MinusToken */:
19728                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
19729                             statement.expression = parsePrefixUnaryExpression();
19730                         }
19731                         else {
19732                             statement.expression = parseObjectLiteralExpression();
19733                         }
19734                         break;
19735                     case 8 /* NumericLiteral */:
19736                     case 10 /* StringLiteral */:
19737                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
19738                             statement.expression = parseLiteralNode();
19739                             break;
19740                         }
19741                     // falls through
19742                     default:
19743                         statement.expression = parseObjectLiteralExpression();
19744                         break;
19745                 }
19746                 finishNode(statement);
19747                 sourceFile.statements = createNodeArray([statement], pos);
19748                 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
19749             }
19750             if (setParentNodes) {
19751                 fixupParentReferences(sourceFile);
19752             }
19753             sourceFile.nodeCount = nodeCount;
19754             sourceFile.identifierCount = identifierCount;
19755             sourceFile.identifiers = identifiers;
19756             sourceFile.parseDiagnostics = parseDiagnostics;
19757             var result = sourceFile;
19758             clearState();
19759             return result;
19760         }
19761         Parser.parseJsonText = parseJsonText;
19762         function getLanguageVariant(scriptKind) {
19763             // .tsx and .jsx files are treated as jsx language variant.
19764             return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19765         }
19766         function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
19767             NodeConstructor = ts.objectAllocator.getNodeConstructor();
19768             TokenConstructor = ts.objectAllocator.getTokenConstructor();
19769             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
19770             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
19771             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
19772             sourceText = _sourceText;
19773             syntaxCursor = _syntaxCursor;
19774             parseDiagnostics = [];
19775             parsingContext = 0;
19776             identifiers = ts.createMap();
19777             privateIdentifiers = ts.createMap();
19778             identifierCount = 0;
19779             nodeCount = 0;
19780             switch (scriptKind) {
19781                 case 1 /* JS */:
19782                 case 2 /* JSX */:
19783                     contextFlags = 131072 /* JavaScriptFile */;
19784                     break;
19785                 case 6 /* JSON */:
19786                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
19787                     break;
19788                 default:
19789                     contextFlags = 0 /* None */;
19790                     break;
19791             }
19792             parseErrorBeforeNextFinishedNode = false;
19793             // Initialize and prime the scanner before parsing the source elements.
19794             scanner.setText(sourceText);
19795             scanner.setOnError(scanError);
19796             scanner.setScriptTarget(languageVersion);
19797             scanner.setLanguageVariant(getLanguageVariant(scriptKind));
19798         }
19799         function clearState() {
19800             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
19801             scanner.clearCommentDirectives();
19802             scanner.setText("");
19803             scanner.setOnError(undefined);
19804             // Clear any data.  We don't want to accidentally hold onto it for too long.
19805             parseDiagnostics = undefined;
19806             sourceFile = undefined;
19807             identifiers = undefined;
19808             syntaxCursor = undefined;
19809             sourceText = undefined;
19810             notParenthesizedArrow = undefined;
19811         }
19812         function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
19813             var isDeclarationFile = isDeclarationFileName(fileName);
19814             if (isDeclarationFile) {
19815                 contextFlags |= 8388608 /* Ambient */;
19816             }
19817             sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
19818             sourceFile.flags = contextFlags;
19819             // Prime the scanner.
19820             nextToken();
19821             // 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
19822             processCommentPragmas(sourceFile, sourceText);
19823             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
19824             sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
19825             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
19826             sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
19827             setExternalModuleIndicator(sourceFile);
19828             sourceFile.commentDirectives = scanner.getCommentDirectives();
19829             sourceFile.nodeCount = nodeCount;
19830             sourceFile.identifierCount = identifierCount;
19831             sourceFile.identifiers = identifiers;
19832             sourceFile.parseDiagnostics = parseDiagnostics;
19833             if (setParentNodes) {
19834                 fixupParentReferences(sourceFile);
19835             }
19836             return sourceFile;
19837             function reportPragmaDiagnostic(pos, end, diagnostic) {
19838                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
19839             }
19840         }
19841         function addJSDocComment(node) {
19842             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
19843             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
19844             if (jsDoc.length)
19845                 node.jsDoc = jsDoc;
19846             return node;
19847         }
19848         function fixupParentReferences(rootNode) {
19849             // normally parent references are set during binding. However, for clients that only need
19850             // a syntax tree, and no semantic features, then the binding process is an unnecessary
19851             // overhead.  This functions allows us to set all the parents, without all the expense of
19852             // binding.
19853             forEachChildRecursively(rootNode, bindParentToChild);
19854             function bindParentToChild(child, parent) {
19855                 child.parent = parent;
19856                 if (ts.hasJSDocNodes(child)) {
19857                     for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19858                         var doc = _a[_i];
19859                         bindParentToChild(doc, child);
19860                         forEachChildRecursively(doc, bindParentToChild);
19861                     }
19862                 }
19863             }
19864         }
19865         Parser.fixupParentReferences = fixupParentReferences;
19866         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
19867             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
19868             // this is quite rare comparing to other nodes and createNode should be as fast as possible
19869             var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
19870             nodeCount++;
19871             sourceFile.text = sourceText;
19872             sourceFile.bindDiagnostics = [];
19873             sourceFile.bindSuggestionDiagnostics = undefined;
19874             sourceFile.languageVersion = languageVersion;
19875             sourceFile.fileName = ts.normalizePath(fileName);
19876             sourceFile.languageVariant = getLanguageVariant(scriptKind);
19877             sourceFile.isDeclarationFile = isDeclarationFile;
19878             sourceFile.scriptKind = scriptKind;
19879             return sourceFile;
19880         }
19881         function setContextFlag(val, flag) {
19882             if (val) {
19883                 contextFlags |= flag;
19884             }
19885             else {
19886                 contextFlags &= ~flag;
19887             }
19888         }
19889         function setDisallowInContext(val) {
19890             setContextFlag(val, 4096 /* DisallowInContext */);
19891         }
19892         function setYieldContext(val) {
19893             setContextFlag(val, 8192 /* YieldContext */);
19894         }
19895         function setDecoratorContext(val) {
19896             setContextFlag(val, 16384 /* DecoratorContext */);
19897         }
19898         function setAwaitContext(val) {
19899             setContextFlag(val, 32768 /* AwaitContext */);
19900         }
19901         function doOutsideOfContext(context, func) {
19902             // contextFlagsToClear will contain only the context flags that are
19903             // currently set that we need to temporarily clear
19904             // We don't just blindly reset to the previous flags to ensure
19905             // that we do not mutate cached flags for the incremental
19906             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19907             // HasAggregatedChildData).
19908             var contextFlagsToClear = context & contextFlags;
19909             if (contextFlagsToClear) {
19910                 // clear the requested context flags
19911                 setContextFlag(/*val*/ false, contextFlagsToClear);
19912                 var result = func();
19913                 // restore the context flags we just cleared
19914                 setContextFlag(/*val*/ true, contextFlagsToClear);
19915                 return result;
19916             }
19917             // no need to do anything special as we are not in any of the requested contexts
19918             return func();
19919         }
19920         function doInsideOfContext(context, func) {
19921             // contextFlagsToSet will contain only the context flags that
19922             // are not currently set that we need to temporarily enable.
19923             // We don't just blindly reset to the previous flags to ensure
19924             // that we do not mutate cached flags for the incremental
19925             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19926             // HasAggregatedChildData).
19927             var contextFlagsToSet = context & ~contextFlags;
19928             if (contextFlagsToSet) {
19929                 // set the requested context flags
19930                 setContextFlag(/*val*/ true, contextFlagsToSet);
19931                 var result = func();
19932                 // reset the context flags we just set
19933                 setContextFlag(/*val*/ false, contextFlagsToSet);
19934                 return result;
19935             }
19936             // no need to do anything special as we are already in all of the requested contexts
19937             return func();
19938         }
19939         function allowInAnd(func) {
19940             return doOutsideOfContext(4096 /* DisallowInContext */, func);
19941         }
19942         function disallowInAnd(func) {
19943             return doInsideOfContext(4096 /* DisallowInContext */, func);
19944         }
19945         function doInYieldContext(func) {
19946             return doInsideOfContext(8192 /* YieldContext */, func);
19947         }
19948         function doInDecoratorContext(func) {
19949             return doInsideOfContext(16384 /* DecoratorContext */, func);
19950         }
19951         function doInAwaitContext(func) {
19952             return doInsideOfContext(32768 /* AwaitContext */, func);
19953         }
19954         function doOutsideOfAwaitContext(func) {
19955             return doOutsideOfContext(32768 /* AwaitContext */, func);
19956         }
19957         function doInYieldAndAwaitContext(func) {
19958             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19959         }
19960         function doOutsideOfYieldAndAwaitContext(func) {
19961             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19962         }
19963         function inContext(flags) {
19964             return (contextFlags & flags) !== 0;
19965         }
19966         function inYieldContext() {
19967             return inContext(8192 /* YieldContext */);
19968         }
19969         function inDisallowInContext() {
19970             return inContext(4096 /* DisallowInContext */);
19971         }
19972         function inDecoratorContext() {
19973             return inContext(16384 /* DecoratorContext */);
19974         }
19975         function inAwaitContext() {
19976             return inContext(32768 /* AwaitContext */);
19977         }
19978         function parseErrorAtCurrentToken(message, arg0) {
19979             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
19980         }
19981         function parseErrorAtPosition(start, length, message, arg0) {
19982             // Don't report another error if it would just be at the same position as the last error.
19983             var lastError = ts.lastOrUndefined(parseDiagnostics);
19984             if (!lastError || start !== lastError.start) {
19985                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
19986             }
19987             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
19988             // node we finish so that it can't be reused incrementally.
19989             parseErrorBeforeNextFinishedNode = true;
19990         }
19991         function parseErrorAt(start, end, message, arg0) {
19992             parseErrorAtPosition(start, end - start, message, arg0);
19993         }
19994         function parseErrorAtRange(range, message, arg0) {
19995             parseErrorAt(range.pos, range.end, message, arg0);
19996         }
19997         function scanError(message, length) {
19998             parseErrorAtPosition(scanner.getTextPos(), length, message);
19999         }
20000         function getNodePos() {
20001             return scanner.getStartPos();
20002         }
20003         // Use this function to access the current token instead of reading the currentToken
20004         // variable. Since function results aren't narrowed in control flow analysis, this ensures
20005         // that the type checker doesn't make wrong assumptions about the type of the current
20006         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
20007         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
20008         // there is no performance penalty.
20009         function token() {
20010             return currentToken;
20011         }
20012         function nextTokenWithoutCheck() {
20013             return currentToken = scanner.scan();
20014         }
20015         function nextToken() {
20016             // if the keyword had an escape
20017             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
20018                 // issue a parse error for the escape
20019                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
20020             }
20021             return nextTokenWithoutCheck();
20022         }
20023         function nextTokenJSDoc() {
20024             return currentToken = scanner.scanJsDocToken();
20025         }
20026         function reScanGreaterToken() {
20027             return currentToken = scanner.reScanGreaterToken();
20028         }
20029         function reScanSlashToken() {
20030             return currentToken = scanner.reScanSlashToken();
20031         }
20032         function reScanTemplateToken(isTaggedTemplate) {
20033             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
20034         }
20035         function reScanTemplateHeadOrNoSubstitutionTemplate() {
20036             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
20037         }
20038         function reScanLessThanToken() {
20039             return currentToken = scanner.reScanLessThanToken();
20040         }
20041         function scanJsxIdentifier() {
20042             return currentToken = scanner.scanJsxIdentifier();
20043         }
20044         function scanJsxText() {
20045             return currentToken = scanner.scanJsxToken();
20046         }
20047         function scanJsxAttributeValue() {
20048             return currentToken = scanner.scanJsxAttributeValue();
20049         }
20050         function speculationHelper(callback, isLookAhead) {
20051             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
20052             // caller asked us to always reset our state).
20053             var saveToken = currentToken;
20054             var saveParseDiagnosticsLength = parseDiagnostics.length;
20055             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
20056             // Note: it is not actually necessary to save/restore the context flags here.  That's
20057             // because the saving/restoring of these flags happens naturally through the recursive
20058             // descent nature of our parser.  However, we still store this here just so we can
20059             // assert that invariant holds.
20060             var saveContextFlags = contextFlags;
20061             // If we're only looking ahead, then tell the scanner to only lookahead as well.
20062             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
20063             // same.
20064             var result = isLookAhead
20065                 ? scanner.lookAhead(callback)
20066                 : scanner.tryScan(callback);
20067             ts.Debug.assert(saveContextFlags === contextFlags);
20068             // If our callback returned something 'falsy' or we're just looking ahead,
20069             // then unconditionally restore us to where we were.
20070             if (!result || isLookAhead) {
20071                 currentToken = saveToken;
20072                 parseDiagnostics.length = saveParseDiagnosticsLength;
20073                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
20074             }
20075             return result;
20076         }
20077         /** Invokes the provided callback then unconditionally restores the parser to the state it
20078          * was in immediately prior to invoking the callback.  The result of invoking the callback
20079          * is returned from this function.
20080          */
20081         function lookAhead(callback) {
20082             return speculationHelper(callback, /*isLookAhead*/ true);
20083         }
20084         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
20085          * the parser to the state it was in immediately prior to invoking the callback.  If the
20086          * callback returns something truthy, then the parser state is not rolled back.  The result
20087          * of invoking the callback is returned from this function.
20088          */
20089         function tryParse(callback) {
20090             return speculationHelper(callback, /*isLookAhead*/ false);
20091         }
20092         // Ignore strict mode flag because we will report an error in type checker instead.
20093         function isIdentifier() {
20094             if (token() === 75 /* Identifier */) {
20095                 return true;
20096             }
20097             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
20098             // considered a keyword and is not an identifier.
20099             if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
20100                 return false;
20101             }
20102             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
20103             // considered a keyword and is not an identifier.
20104             if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
20105                 return false;
20106             }
20107             return token() > 112 /* LastReservedWord */;
20108         }
20109         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
20110             if (shouldAdvance === void 0) { shouldAdvance = true; }
20111             if (token() === kind) {
20112                 if (shouldAdvance) {
20113                     nextToken();
20114                 }
20115                 return true;
20116             }
20117             // Report specific message if provided with one.  Otherwise, report generic fallback message.
20118             if (diagnosticMessage) {
20119                 parseErrorAtCurrentToken(diagnosticMessage);
20120             }
20121             else {
20122                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
20123             }
20124             return false;
20125         }
20126         function parseExpectedJSDoc(kind) {
20127             if (token() === kind) {
20128                 nextTokenJSDoc();
20129                 return true;
20130             }
20131             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
20132             return false;
20133         }
20134         function parseOptional(t) {
20135             if (token() === t) {
20136                 nextToken();
20137                 return true;
20138             }
20139             return false;
20140         }
20141         function parseOptionalToken(t) {
20142             if (token() === t) {
20143                 return parseTokenNode();
20144             }
20145             return undefined;
20146         }
20147         function parseOptionalTokenJSDoc(t) {
20148             if (token() === t) {
20149                 return parseTokenNodeJSDoc();
20150             }
20151             return undefined;
20152         }
20153         function parseExpectedToken(t, diagnosticMessage, arg0) {
20154             return parseOptionalToken(t) ||
20155                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
20156         }
20157         function parseExpectedTokenJSDoc(t) {
20158             return parseOptionalTokenJSDoc(t) ||
20159                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
20160         }
20161         function parseTokenNode() {
20162             var node = createNode(token());
20163             nextToken();
20164             return finishNode(node);
20165         }
20166         function parseTokenNodeJSDoc() {
20167             var node = createNode(token());
20168             nextTokenJSDoc();
20169             return finishNode(node);
20170         }
20171         function canParseSemicolon() {
20172             // If there's a real semicolon, then we can always parse it out.
20173             if (token() === 26 /* SemicolonToken */) {
20174                 return true;
20175             }
20176             // We can parse out an optional semicolon in ASI cases in the following cases.
20177             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
20178         }
20179         function parseSemicolon() {
20180             if (canParseSemicolon()) {
20181                 if (token() === 26 /* SemicolonToken */) {
20182                     // consume the semicolon if it was explicitly provided.
20183                     nextToken();
20184                 }
20185                 return true;
20186             }
20187             else {
20188                 return parseExpected(26 /* SemicolonToken */);
20189             }
20190         }
20191         function createNode(kind, pos) {
20192             nodeCount++;
20193             var p = pos >= 0 ? pos : scanner.getStartPos();
20194             return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
20195                 kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
20196                     kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
20197                         new TokenConstructor(kind, p, p);
20198         }
20199         function createNodeWithJSDoc(kind, pos) {
20200             var node = createNode(kind, pos);
20201             if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
20202                 addJSDocComment(node);
20203             }
20204             return node;
20205         }
20206         function createNodeArray(elements, pos, end) {
20207             // Since the element list of a node array is typically created by starting with an empty array and
20208             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20209             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20210             var length = elements.length;
20211             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20212             array.pos = pos;
20213             array.end = end === undefined ? scanner.getStartPos() : end;
20214             return array;
20215         }
20216         function finishNode(node, end) {
20217             node.end = end === undefined ? scanner.getStartPos() : end;
20218             if (contextFlags) {
20219                 node.flags |= contextFlags;
20220             }
20221             // Keep track on the node if we encountered an error while parsing it.  If we did, then
20222             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
20223             // flag so that we don't mark any subsequent nodes.
20224             if (parseErrorBeforeNextFinishedNode) {
20225                 parseErrorBeforeNextFinishedNode = false;
20226                 node.flags |= 65536 /* ThisNodeHasError */;
20227             }
20228             return node;
20229         }
20230         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
20231             if (reportAtCurrentPosition) {
20232                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
20233             }
20234             else if (diagnosticMessage) {
20235                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
20236             }
20237             var result = createNode(kind);
20238             if (kind === 75 /* Identifier */) {
20239                 result.escapedText = "";
20240             }
20241             else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
20242                 result.text = "";
20243             }
20244             return finishNode(result);
20245         }
20246         function internIdentifier(text) {
20247             var identifier = identifiers.get(text);
20248             if (identifier === undefined) {
20249                 identifiers.set(text, identifier = text);
20250             }
20251             return identifier;
20252         }
20253         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
20254         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
20255         // each identifier in order to reduce memory consumption.
20256         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
20257             identifierCount++;
20258             if (isIdentifier) {
20259                 var node = createNode(75 /* Identifier */);
20260                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
20261                 if (token() !== 75 /* Identifier */) {
20262                     node.originalKeywordKind = token();
20263                 }
20264                 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
20265                 nextTokenWithoutCheck();
20266                 return finishNode(node);
20267             }
20268             if (token() === 76 /* PrivateIdentifier */) {
20269                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
20270                 return createIdentifier(/*isIdentifier*/ true);
20271             }
20272             // Only for end of file because the error gets reported incorrectly on embedded script tags.
20273             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
20274             var isReservedWord = scanner.isReservedWord();
20275             var msgArg = scanner.getTokenText();
20276             var defaultMessage = isReservedWord ?
20277                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
20278                 ts.Diagnostics.Identifier_expected;
20279             return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
20280         }
20281         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
20282             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
20283         }
20284         function parseIdentifierName(diagnosticMessage) {
20285             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
20286         }
20287         function isLiteralPropertyName() {
20288             return ts.tokenIsIdentifierOrKeyword(token()) ||
20289                 token() === 10 /* StringLiteral */ ||
20290                 token() === 8 /* NumericLiteral */;
20291         }
20292         function parsePropertyNameWorker(allowComputedPropertyNames) {
20293             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
20294                 var node = parseLiteralNode();
20295                 node.text = internIdentifier(node.text);
20296                 return node;
20297             }
20298             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
20299                 return parseComputedPropertyName();
20300             }
20301             if (token() === 76 /* PrivateIdentifier */) {
20302                 return parsePrivateIdentifier();
20303             }
20304             return parseIdentifierName();
20305         }
20306         function parsePropertyName() {
20307             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
20308         }
20309         function parseComputedPropertyName() {
20310             // PropertyName [Yield]:
20311             //      LiteralPropertyName
20312             //      ComputedPropertyName[?Yield]
20313             var node = createNode(154 /* ComputedPropertyName */);
20314             parseExpected(22 /* OpenBracketToken */);
20315             // We parse any expression (including a comma expression). But the grammar
20316             // says that only an assignment expression is allowed, so the grammar checker
20317             // will error if it sees a comma expression.
20318             node.expression = allowInAnd(parseExpression);
20319             parseExpected(23 /* CloseBracketToken */);
20320             return finishNode(node);
20321         }
20322         function internPrivateIdentifier(text) {
20323             var privateIdentifier = privateIdentifiers.get(text);
20324             if (privateIdentifier === undefined) {
20325                 privateIdentifiers.set(text, privateIdentifier = text);
20326             }
20327             return privateIdentifier;
20328         }
20329         function parsePrivateIdentifier() {
20330             var node = createNode(76 /* PrivateIdentifier */);
20331             node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
20332             nextToken();
20333             return finishNode(node);
20334         }
20335         function parseContextualModifier(t) {
20336             return token() === t && tryParse(nextTokenCanFollowModifier);
20337         }
20338         function nextTokenIsOnSameLineAndCanFollowModifier() {
20339             nextToken();
20340             if (scanner.hasPrecedingLineBreak()) {
20341                 return false;
20342             }
20343             return canFollowModifier();
20344         }
20345         function nextTokenCanFollowModifier() {
20346             switch (token()) {
20347                 case 81 /* ConstKeyword */:
20348                     // 'const' is only a modifier if followed by 'enum'.
20349                     return nextToken() === 88 /* EnumKeyword */;
20350                 case 89 /* ExportKeyword */:
20351                     nextToken();
20352                     if (token() === 84 /* DefaultKeyword */) {
20353                         return lookAhead(nextTokenCanFollowDefaultKeyword);
20354                     }
20355                     if (token() === 145 /* TypeKeyword */) {
20356                         return lookAhead(nextTokenCanFollowExportModifier);
20357                     }
20358                     return canFollowExportModifier();
20359                 case 84 /* DefaultKeyword */:
20360                     return nextTokenCanFollowDefaultKeyword();
20361                 case 120 /* StaticKeyword */:
20362                 case 131 /* GetKeyword */:
20363                 case 142 /* SetKeyword */:
20364                     nextToken();
20365                     return canFollowModifier();
20366                 default:
20367                     return nextTokenIsOnSameLineAndCanFollowModifier();
20368             }
20369         }
20370         function canFollowExportModifier() {
20371             return token() !== 41 /* AsteriskToken */
20372                 && token() !== 123 /* AsKeyword */
20373                 && token() !== 18 /* OpenBraceToken */
20374                 && canFollowModifier();
20375         }
20376         function nextTokenCanFollowExportModifier() {
20377             nextToken();
20378             return canFollowExportModifier();
20379         }
20380         function parseAnyContextualModifier() {
20381             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
20382         }
20383         function canFollowModifier() {
20384             return token() === 22 /* OpenBracketToken */
20385                 || token() === 18 /* OpenBraceToken */
20386                 || token() === 41 /* AsteriskToken */
20387                 || token() === 25 /* DotDotDotToken */
20388                 || isLiteralPropertyName();
20389         }
20390         function nextTokenCanFollowDefaultKeyword() {
20391             nextToken();
20392             return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
20393                 token() === 114 /* InterfaceKeyword */ ||
20394                 (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
20395                 (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
20396         }
20397         // True if positioned at the start of a list element
20398         function isListElement(parsingContext, inErrorRecovery) {
20399             var node = currentNode(parsingContext);
20400             if (node) {
20401                 return true;
20402             }
20403             switch (parsingContext) {
20404                 case 0 /* SourceElements */:
20405                 case 1 /* BlockStatements */:
20406                 case 3 /* SwitchClauseStatements */:
20407                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
20408                     // The problem is that ';' can show up in far too many contexts, and if we see one
20409                     // and assume it's a statement, then we may bail out inappropriately from whatever
20410                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
20411                     // we really don't want to assume the class is over and we're on a statement in the
20412                     // outer module.  We just want to consume and move on.
20413                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
20414                 case 2 /* SwitchClauses */:
20415                     return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20416                 case 4 /* TypeMembers */:
20417                     return lookAhead(isTypeMemberStart);
20418                 case 5 /* ClassMembers */:
20419                     // We allow semicolons as class elements (as specified by ES6) as long as we're
20420                     // not in error recovery.  If we're in error recovery, we don't want an errant
20421                     // semicolon to be treated as a class member (since they're almost always used
20422                     // for statements.
20423                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
20424                 case 6 /* EnumMembers */:
20425                     // Include open bracket computed properties. This technically also lets in indexers,
20426                     // which would be a candidate for improved error reporting.
20427                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
20428                 case 12 /* ObjectLiteralMembers */:
20429                     switch (token()) {
20430                         case 22 /* OpenBracketToken */:
20431                         case 41 /* AsteriskToken */:
20432                         case 25 /* DotDotDotToken */:
20433                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
20434                             return true;
20435                         default:
20436                             return isLiteralPropertyName();
20437                     }
20438                 case 18 /* RestProperties */:
20439                     return isLiteralPropertyName();
20440                 case 9 /* ObjectBindingElements */:
20441                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
20442                 case 7 /* HeritageClauseElement */:
20443                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
20444                     // That way we won't consume the body of a class in its heritage clause.
20445                     if (token() === 18 /* OpenBraceToken */) {
20446                         return lookAhead(isValidHeritageClauseObjectLiteral);
20447                     }
20448                     if (!inErrorRecovery) {
20449                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
20450                     }
20451                     else {
20452                         // If we're in error recovery we tighten up what we're willing to match.
20453                         // That way we don't treat something like "this" as a valid heritage clause
20454                         // element during recovery.
20455                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
20456                     }
20457                 case 8 /* VariableDeclarations */:
20458                     return isIdentifierOrPrivateIdentifierOrPattern();
20459                 case 10 /* ArrayBindingElements */:
20460                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
20461                 case 19 /* TypeParameters */:
20462                     return isIdentifier();
20463                 case 15 /* ArrayLiteralMembers */:
20464                     switch (token()) {
20465                         case 27 /* CommaToken */:
20466                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
20467                             return true;
20468                     }
20469                 // falls through
20470                 case 11 /* ArgumentExpressions */:
20471                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
20472                 case 16 /* Parameters */:
20473                     return isStartOfParameter(/*isJSDocParameter*/ false);
20474                 case 17 /* JSDocParameters */:
20475                     return isStartOfParameter(/*isJSDocParameter*/ true);
20476                 case 20 /* TypeArguments */:
20477                 case 21 /* TupleElementTypes */:
20478                     return token() === 27 /* CommaToken */ || isStartOfType();
20479                 case 22 /* HeritageClauses */:
20480                     return isHeritageClause();
20481                 case 23 /* ImportOrExportSpecifiers */:
20482                     return ts.tokenIsIdentifierOrKeyword(token());
20483                 case 13 /* JsxAttributes */:
20484                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
20485                 case 14 /* JsxChildren */:
20486                     return true;
20487             }
20488             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
20489         }
20490         function isValidHeritageClauseObjectLiteral() {
20491             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
20492             if (nextToken() === 19 /* CloseBraceToken */) {
20493                 // if we see "extends {}" then only treat the {} as what we're extending (and not
20494                 // the class body) if we have:
20495                 //
20496                 //      extends {} {
20497                 //      extends {},
20498                 //      extends {} extends
20499                 //      extends {} implements
20500                 var next = nextToken();
20501                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
20502             }
20503             return true;
20504         }
20505         function nextTokenIsIdentifier() {
20506             nextToken();
20507             return isIdentifier();
20508         }
20509         function nextTokenIsIdentifierOrKeyword() {
20510             nextToken();
20511             return ts.tokenIsIdentifierOrKeyword(token());
20512         }
20513         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
20514             nextToken();
20515             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
20516         }
20517         function isHeritageClauseExtendsOrImplementsKeyword() {
20518             if (token() === 113 /* ImplementsKeyword */ ||
20519                 token() === 90 /* ExtendsKeyword */) {
20520                 return lookAhead(nextTokenIsStartOfExpression);
20521             }
20522             return false;
20523         }
20524         function nextTokenIsStartOfExpression() {
20525             nextToken();
20526             return isStartOfExpression();
20527         }
20528         function nextTokenIsStartOfType() {
20529             nextToken();
20530             return isStartOfType();
20531         }
20532         // True if positioned at a list terminator
20533         function isListTerminator(kind) {
20534             if (token() === 1 /* EndOfFileToken */) {
20535                 // Being at the end of the file ends all lists.
20536                 return true;
20537             }
20538             switch (kind) {
20539                 case 1 /* BlockStatements */:
20540                 case 2 /* SwitchClauses */:
20541                 case 4 /* TypeMembers */:
20542                 case 5 /* ClassMembers */:
20543                 case 6 /* EnumMembers */:
20544                 case 12 /* ObjectLiteralMembers */:
20545                 case 9 /* ObjectBindingElements */:
20546                 case 23 /* ImportOrExportSpecifiers */:
20547                     return token() === 19 /* CloseBraceToken */;
20548                 case 3 /* SwitchClauseStatements */:
20549                     return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20550                 case 7 /* HeritageClauseElement */:
20551                     return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20552                 case 8 /* VariableDeclarations */:
20553                     return isVariableDeclaratorListTerminator();
20554                 case 19 /* TypeParameters */:
20555                     // Tokens other than '>' are here for better error recovery
20556                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20557                 case 11 /* ArgumentExpressions */:
20558                     // Tokens other than ')' are here for better error recovery
20559                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
20560                 case 15 /* ArrayLiteralMembers */:
20561                 case 21 /* TupleElementTypes */:
20562                 case 10 /* ArrayBindingElements */:
20563                     return token() === 23 /* CloseBracketToken */;
20564                 case 17 /* JSDocParameters */:
20565                 case 16 /* Parameters */:
20566                 case 18 /* RestProperties */:
20567                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
20568                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
20569                 case 20 /* TypeArguments */:
20570                     // All other tokens should cause the type-argument to terminate except comma token
20571                     return token() !== 27 /* CommaToken */;
20572                 case 22 /* HeritageClauses */:
20573                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
20574                 case 13 /* JsxAttributes */:
20575                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
20576                 case 14 /* JsxChildren */:
20577                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
20578                 default:
20579                     return false;
20580             }
20581         }
20582         function isVariableDeclaratorListTerminator() {
20583             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
20584             // with parsing the list of variable declarators.
20585             if (canParseSemicolon()) {
20586                 return true;
20587             }
20588             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
20589             // are done if we see an 'in' keyword in front of us. Same with for-of
20590             if (isInOrOfKeyword(token())) {
20591                 return true;
20592             }
20593             // ERROR RECOVERY TWEAK:
20594             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
20595             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
20596             // another variable declaration.
20597             if (token() === 38 /* EqualsGreaterThanToken */) {
20598                 return true;
20599             }
20600             // Keep trying to parse out variable declarators.
20601             return false;
20602         }
20603         // True if positioned at element or terminator of the current list or any enclosing list
20604         function isInSomeParsingContext() {
20605             for (var kind = 0; kind < 24 /* Count */; kind++) {
20606                 if (parsingContext & (1 << kind)) {
20607                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
20608                         return true;
20609                     }
20610                 }
20611             }
20612             return false;
20613         }
20614         // Parses a list of elements
20615         function parseList(kind, parseElement) {
20616             var saveParsingContext = parsingContext;
20617             parsingContext |= 1 << kind;
20618             var list = [];
20619             var listPos = getNodePos();
20620             while (!isListTerminator(kind)) {
20621                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20622                     var element = parseListElement(kind, parseElement);
20623                     list.push(element);
20624                     continue;
20625                 }
20626                 if (abortParsingListOrMoveToNextToken(kind)) {
20627                     break;
20628                 }
20629             }
20630             parsingContext = saveParsingContext;
20631             return createNodeArray(list, listPos);
20632         }
20633         function parseListElement(parsingContext, parseElement) {
20634             var node = currentNode(parsingContext);
20635             if (node) {
20636                 return consumeNode(node);
20637             }
20638             return parseElement();
20639         }
20640         function currentNode(parsingContext) {
20641             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
20642             //
20643             // If there is an outstanding parse error that we've encountered, but not attached to
20644             // some node, then we cannot get a node from the old source tree.  This is because we
20645             // want to mark the next node we encounter as being unusable.
20646             //
20647             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
20648             // on it (or its leftmost child) as having the error.  For now though, being conservative
20649             // is nice and likely won't ever affect perf.
20650             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
20651                 return undefined;
20652             }
20653             var node = syntaxCursor.currentNode(scanner.getStartPos());
20654             // Can't reuse a missing node.
20655             // Can't reuse a node that intersected the change range.
20656             // Can't reuse a node that contains a parse error.  This is necessary so that we
20657             // produce the same set of errors again.
20658             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
20659                 return undefined;
20660             }
20661             // We can only reuse a node if it was parsed under the same strict mode that we're
20662             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
20663             // the user added 'using strict' at the top of the file, then we can't use that node
20664             // again as the presence of strict mode may cause us to parse the tokens in the file
20665             // differently.
20666             //
20667             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
20668             // are unaffected by strict mode.  It's just the parser will decide what to do with it
20669             // differently depending on what mode it is in.
20670             //
20671             // This also applies to all our other context flags as well.
20672             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
20673             if (nodeContextFlags !== contextFlags) {
20674                 return undefined;
20675             }
20676             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
20677             // in the current list parsing context that we're currently at.
20678             if (!canReuseNode(node, parsingContext)) {
20679                 return undefined;
20680             }
20681             if (node.jsDocCache) {
20682                 // jsDocCache may include tags from parent nodes, which might have been modified.
20683                 node.jsDocCache = undefined;
20684             }
20685             return node;
20686         }
20687         function consumeNode(node) {
20688             // Move the scanner so it is after the node we just consumed.
20689             scanner.setTextPos(node.end);
20690             nextToken();
20691             return node;
20692         }
20693         function isReusableParsingContext(parsingContext) {
20694             switch (parsingContext) {
20695                 case 5 /* ClassMembers */:
20696                 case 2 /* SwitchClauses */:
20697                 case 0 /* SourceElements */:
20698                 case 1 /* BlockStatements */:
20699                 case 3 /* SwitchClauseStatements */:
20700                 case 6 /* EnumMembers */:
20701                 case 4 /* TypeMembers */:
20702                 case 8 /* VariableDeclarations */:
20703                 case 17 /* JSDocParameters */:
20704                 case 16 /* Parameters */:
20705                     return true;
20706             }
20707             return false;
20708         }
20709         function canReuseNode(node, parsingContext) {
20710             switch (parsingContext) {
20711                 case 5 /* ClassMembers */:
20712                     return isReusableClassMember(node);
20713                 case 2 /* SwitchClauses */:
20714                     return isReusableSwitchClause(node);
20715                 case 0 /* SourceElements */:
20716                 case 1 /* BlockStatements */:
20717                 case 3 /* SwitchClauseStatements */:
20718                     return isReusableStatement(node);
20719                 case 6 /* EnumMembers */:
20720                     return isReusableEnumMember(node);
20721                 case 4 /* TypeMembers */:
20722                     return isReusableTypeMember(node);
20723                 case 8 /* VariableDeclarations */:
20724                     return isReusableVariableDeclaration(node);
20725                 case 17 /* JSDocParameters */:
20726                 case 16 /* Parameters */:
20727                     return isReusableParameter(node);
20728                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
20729                 // you can do so safely.  Danger areas involve nodes that may involve speculative
20730                 // parsing.  If speculative parsing is involved with the node, then the range the
20731                 // parser reached while looking ahead might be in the edited range (see the example
20732                 // in canReuseVariableDeclaratorNode for a good case of this).
20733                 // case ParsingContext.HeritageClauses:
20734                 // This would probably be safe to reuse.  There is no speculative parsing with
20735                 // heritage clauses.
20736                 // case ParsingContext.TypeParameters:
20737                 // This would probably be safe to reuse.  There is no speculative parsing with
20738                 // type parameters.  Note that that's because type *parameters* only occur in
20739                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
20740                 // *expression* contexts.
20741                 // case ParsingContext.TupleElementTypes:
20742                 // This would probably be safe to reuse.  There is no speculative parsing with
20743                 // tuple types.
20744                 // Technically, type argument list types are probably safe to reuse.  While
20745                 // speculative parsing is involved with them (since type argument lists are only
20746                 // produced from speculative parsing a < as a type argument list), we only have
20747                 // the types because speculative parsing succeeded.  Thus, the lookahead never
20748                 // went past the end of the list and rewound.
20749                 // case ParsingContext.TypeArguments:
20750                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
20751                 // need a large amount of lookahead, and we should not reuse them as they may
20752                 // have actually intersected the edit.
20753                 // case ParsingContext.ArgumentExpressions:
20754                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
20755                 // cases.  i.e. a property assignment may end with an expression, and thus might
20756                 // have lookahead far beyond it's old node.
20757                 // case ParsingContext.ObjectLiteralMembers:
20758                 // This is probably not safe to reuse.  There can be speculative parsing with
20759                 // type names in a heritage clause.  There can be generic names in the type
20760                 // name list, and there can be left hand side expressions (which can have type
20761                 // arguments.)
20762                 // case ParsingContext.HeritageClauseElement:
20763                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
20764                 // on any given element. Same for children.
20765                 // case ParsingContext.JsxAttributes:
20766                 // case ParsingContext.JsxChildren:
20767             }
20768             return false;
20769         }
20770         function isReusableClassMember(node) {
20771             if (node) {
20772                 switch (node.kind) {
20773                     case 162 /* Constructor */:
20774                     case 167 /* IndexSignature */:
20775                     case 163 /* GetAccessor */:
20776                     case 164 /* SetAccessor */:
20777                     case 159 /* PropertyDeclaration */:
20778                     case 222 /* SemicolonClassElement */:
20779                         return true;
20780                     case 161 /* MethodDeclaration */:
20781                         // Method declarations are not necessarily reusable.  An object-literal
20782                         // may have a method calls "constructor(...)" and we must reparse that
20783                         // into an actual .ConstructorDeclaration.
20784                         var methodDeclaration = node;
20785                         var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
20786                             methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
20787                         return !nameIsConstructor;
20788                 }
20789             }
20790             return false;
20791         }
20792         function isReusableSwitchClause(node) {
20793             if (node) {
20794                 switch (node.kind) {
20795                     case 277 /* CaseClause */:
20796                     case 278 /* DefaultClause */:
20797                         return true;
20798                 }
20799             }
20800             return false;
20801         }
20802         function isReusableStatement(node) {
20803             if (node) {
20804                 switch (node.kind) {
20805                     case 244 /* FunctionDeclaration */:
20806                     case 225 /* VariableStatement */:
20807                     case 223 /* Block */:
20808                     case 227 /* IfStatement */:
20809                     case 226 /* ExpressionStatement */:
20810                     case 239 /* ThrowStatement */:
20811                     case 235 /* ReturnStatement */:
20812                     case 237 /* SwitchStatement */:
20813                     case 234 /* BreakStatement */:
20814                     case 233 /* ContinueStatement */:
20815                     case 231 /* ForInStatement */:
20816                     case 232 /* ForOfStatement */:
20817                     case 230 /* ForStatement */:
20818                     case 229 /* WhileStatement */:
20819                     case 236 /* WithStatement */:
20820                     case 224 /* EmptyStatement */:
20821                     case 240 /* TryStatement */:
20822                     case 238 /* LabeledStatement */:
20823                     case 228 /* DoStatement */:
20824                     case 241 /* DebuggerStatement */:
20825                     case 254 /* ImportDeclaration */:
20826                     case 253 /* ImportEqualsDeclaration */:
20827                     case 260 /* ExportDeclaration */:
20828                     case 259 /* ExportAssignment */:
20829                     case 249 /* ModuleDeclaration */:
20830                     case 245 /* ClassDeclaration */:
20831                     case 246 /* InterfaceDeclaration */:
20832                     case 248 /* EnumDeclaration */:
20833                     case 247 /* TypeAliasDeclaration */:
20834                         return true;
20835                 }
20836             }
20837             return false;
20838         }
20839         function isReusableEnumMember(node) {
20840             return node.kind === 284 /* EnumMember */;
20841         }
20842         function isReusableTypeMember(node) {
20843             if (node) {
20844                 switch (node.kind) {
20845                     case 166 /* ConstructSignature */:
20846                     case 160 /* MethodSignature */:
20847                     case 167 /* IndexSignature */:
20848                     case 158 /* PropertySignature */:
20849                     case 165 /* CallSignature */:
20850                         return true;
20851                 }
20852             }
20853             return false;
20854         }
20855         function isReusableVariableDeclaration(node) {
20856             if (node.kind !== 242 /* VariableDeclaration */) {
20857                 return false;
20858             }
20859             // Very subtle incremental parsing bug.  Consider the following code:
20860             //
20861             //      let v = new List < A, B
20862             //
20863             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
20864             // on one side and "B" on the other. If you then change that to:
20865             //
20866             //      let v = new List < A, B >()
20867             //
20868             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
20869             // start reparsing at "B" and we completely fail to handle this properly.
20870             //
20871             // In order to prevent this, we do not allow a variable declarator to be reused if it
20872             // has an initializer.
20873             var variableDeclarator = node;
20874             return variableDeclarator.initializer === undefined;
20875         }
20876         function isReusableParameter(node) {
20877             if (node.kind !== 156 /* Parameter */) {
20878                 return false;
20879             }
20880             // See the comment in isReusableVariableDeclaration for why we do this.
20881             var parameter = node;
20882             return parameter.initializer === undefined;
20883         }
20884         // Returns true if we should abort parsing.
20885         function abortParsingListOrMoveToNextToken(kind) {
20886             parseErrorAtCurrentToken(parsingContextErrors(kind));
20887             if (isInSomeParsingContext()) {
20888                 return true;
20889             }
20890             nextToken();
20891             return false;
20892         }
20893         function parsingContextErrors(context) {
20894             switch (context) {
20895                 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
20896                 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
20897                 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
20898                 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
20899                 case 18 /* RestProperties */: // fallthrough
20900                 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
20901                 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
20902                 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
20903                 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
20904                 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
20905                 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
20906                 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
20907                 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
20908                 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
20909                 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
20910                 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
20911                 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
20912                 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
20913                 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
20914                 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
20915                 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
20916                 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
20917                 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
20918                 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
20919                 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
20920             }
20921         }
20922         // Parses a comma-delimited list of elements
20923         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
20924             var saveParsingContext = parsingContext;
20925             parsingContext |= 1 << kind;
20926             var list = [];
20927             var listPos = getNodePos();
20928             var commaStart = -1; // Meaning the previous token was not a comma
20929             while (true) {
20930                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20931                     var startPos = scanner.getStartPos();
20932                     list.push(parseListElement(kind, parseElement));
20933                     commaStart = scanner.getTokenPos();
20934                     if (parseOptional(27 /* CommaToken */)) {
20935                         // No need to check for a zero length node since we know we parsed a comma
20936                         continue;
20937                     }
20938                     commaStart = -1; // Back to the state where the last token was not a comma
20939                     if (isListTerminator(kind)) {
20940                         break;
20941                     }
20942                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
20943                     // out a comma so we give a good error message.
20944                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
20945                     // If the token was a semicolon, and the caller allows that, then skip it and
20946                     // continue.  This ensures we get back on track and don't result in tons of
20947                     // parse errors.  For example, this can happen when people do things like use
20948                     // a semicolon to delimit object literal members.   Note: we'll have already
20949                     // reported an error when we called parseExpected above.
20950                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
20951                         nextToken();
20952                     }
20953                     if (startPos === scanner.getStartPos()) {
20954                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
20955                         // Consume a token to advance the parser in some way and avoid an infinite loop
20956                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
20957                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
20958                         nextToken();
20959                     }
20960                     continue;
20961                 }
20962                 if (isListTerminator(kind)) {
20963                     break;
20964                 }
20965                 if (abortParsingListOrMoveToNextToken(kind)) {
20966                     break;
20967                 }
20968             }
20969             parsingContext = saveParsingContext;
20970             var result = createNodeArray(list, listPos);
20971             // Recording the trailing comma is deliberately done after the previous
20972             // loop, and not just if we see a list terminator. This is because the list
20973             // may have ended incorrectly, but it is still important to know if there
20974             // was a trailing comma.
20975             // Check if the last token was a comma.
20976             if (commaStart >= 0) {
20977                 // Always preserve a trailing comma by marking it on the NodeArray
20978                 result.hasTrailingComma = true;
20979             }
20980             return result;
20981         }
20982         function getExpectedCommaDiagnostic(kind) {
20983             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
20984         }
20985         function createMissingList() {
20986             var list = createNodeArray([], getNodePos());
20987             list.isMissingList = true;
20988             return list;
20989         }
20990         function isMissingList(arr) {
20991             return !!arr.isMissingList;
20992         }
20993         function parseBracketedList(kind, parseElement, open, close) {
20994             if (parseExpected(open)) {
20995                 var result = parseDelimitedList(kind, parseElement);
20996                 parseExpected(close);
20997                 return result;
20998             }
20999             return createMissingList();
21000         }
21001         function parseEntityName(allowReservedWords, diagnosticMessage) {
21002             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
21003             var dotPos = scanner.getStartPos();
21004             while (parseOptional(24 /* DotToken */)) {
21005                 if (token() === 29 /* LessThanToken */) {
21006                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
21007                     entity.jsdocDotPos = dotPos;
21008                     break;
21009                 }
21010                 dotPos = scanner.getStartPos();
21011                 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
21012             }
21013             return entity;
21014         }
21015         function createQualifiedName(entity, name) {
21016             var node = createNode(153 /* QualifiedName */, entity.pos);
21017             node.left = entity;
21018             node.right = name;
21019             return finishNode(node);
21020         }
21021         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
21022             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
21023             // However, often we'll encounter this in error situations when the identifier or keyword
21024             // is actually starting another valid construct.
21025             //
21026             // So, we check for the following specific case:
21027             //
21028             //      name.
21029             //      identifierOrKeyword identifierNameOrKeyword
21030             //
21031             // Note: the newlines are important here.  For example, if that above code
21032             // were rewritten into:
21033             //
21034             //      name.identifierOrKeyword
21035             //      identifierNameOrKeyword
21036             //
21037             // Then we would consider it valid.  That's because ASI would take effect and
21038             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
21039             // In the first case though, ASI will not take effect because there is not a
21040             // line terminator after the identifier or keyword.
21041             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
21042                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
21043                 if (matchesPattern) {
21044                     // Report that we need an identifier.  However, report it right after the dot,
21045                     // and not on the next token.  This is because the next token might actually
21046                     // be an identifier and the error would be quite confusing.
21047                     return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
21048                 }
21049             }
21050             if (token() === 76 /* PrivateIdentifier */) {
21051                 var node = parsePrivateIdentifier();
21052                 return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
21053             }
21054             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
21055         }
21056         function parseTemplateExpression(isTaggedTemplate) {
21057             var template = createNode(211 /* TemplateExpression */);
21058             template.head = parseTemplateHead(isTaggedTemplate);
21059             ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
21060             var list = [];
21061             var listPos = getNodePos();
21062             do {
21063                 list.push(parseTemplateSpan(isTaggedTemplate));
21064             } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
21065             template.templateSpans = createNodeArray(list, listPos);
21066             return finishNode(template);
21067         }
21068         function parseTemplateSpan(isTaggedTemplate) {
21069             var span = createNode(221 /* TemplateSpan */);
21070             span.expression = allowInAnd(parseExpression);
21071             var literal;
21072             if (token() === 19 /* CloseBraceToken */) {
21073                 reScanTemplateToken(isTaggedTemplate);
21074                 literal = parseTemplateMiddleOrTemplateTail();
21075             }
21076             else {
21077                 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
21078             }
21079             span.literal = literal;
21080             return finishNode(span);
21081         }
21082         function parseLiteralNode() {
21083             return parseLiteralLikeNode(token());
21084         }
21085         function parseTemplateHead(isTaggedTemplate) {
21086             if (isTaggedTemplate) {
21087                 reScanTemplateHeadOrNoSubstitutionTemplate();
21088             }
21089             var fragment = parseLiteralLikeNode(token());
21090             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
21091             return fragment;
21092         }
21093         function parseTemplateMiddleOrTemplateTail() {
21094             var fragment = parseLiteralLikeNode(token());
21095             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
21096             return fragment;
21097         }
21098         function parseLiteralLikeNode(kind) {
21099             var node = createNode(kind);
21100             node.text = scanner.getTokenValue();
21101             switch (kind) {
21102                 case 14 /* NoSubstitutionTemplateLiteral */:
21103                 case 15 /* TemplateHead */:
21104                 case 16 /* TemplateMiddle */:
21105                 case 17 /* TemplateTail */:
21106                     var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
21107                     var tokenText = scanner.getTokenText();
21108                     node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
21109                     break;
21110             }
21111             if (scanner.hasExtendedUnicodeEscape()) {
21112                 node.hasExtendedUnicodeEscape = true;
21113             }
21114             if (scanner.isUnterminated()) {
21115                 node.isUnterminated = true;
21116             }
21117             // Octal literals are not allowed in strict mode or ES5
21118             // Note that theoretically the following condition would hold true literals like 009,
21119             // which is not octal.But because of how the scanner separates the tokens, we would
21120             // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
21121             // We also do not need to check for negatives because any prefix operator would be part of a
21122             // parent unary expression.
21123             if (node.kind === 8 /* NumericLiteral */) {
21124                 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
21125             }
21126             if (ts.isTemplateLiteralKind(node.kind)) {
21127                 node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
21128             }
21129             nextToken();
21130             finishNode(node);
21131             return node;
21132         }
21133         // TYPES
21134         function parseTypeReference() {
21135             var node = createNode(169 /* TypeReference */);
21136             node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21137             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21138                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21139             }
21140             return finishNode(node);
21141         }
21142         // If true, we should abort parsing an error function.
21143         function typeHasArrowFunctionBlockingParseError(node) {
21144             switch (node.kind) {
21145                 case 169 /* TypeReference */:
21146                     return ts.nodeIsMissing(node.typeName);
21147                 case 170 /* FunctionType */:
21148                 case 171 /* ConstructorType */: {
21149                     var _a = node, parameters = _a.parameters, type = _a.type;
21150                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
21151                 }
21152                 case 182 /* ParenthesizedType */:
21153                     return typeHasArrowFunctionBlockingParseError(node.type);
21154                 default:
21155                     return false;
21156             }
21157         }
21158         function parseThisTypePredicate(lhs) {
21159             nextToken();
21160             var node = createNode(168 /* TypePredicate */, lhs.pos);
21161             node.parameterName = lhs;
21162             node.type = parseType();
21163             return finishNode(node);
21164         }
21165         function parseThisTypeNode() {
21166             var node = createNode(183 /* ThisType */);
21167             nextToken();
21168             return finishNode(node);
21169         }
21170         function parseJSDocAllType(postFixEquals) {
21171             var result = createNode(295 /* JSDocAllType */);
21172             if (postFixEquals) {
21173                 return createPostfixType(299 /* JSDocOptionalType */, result);
21174             }
21175             else {
21176                 nextToken();
21177             }
21178             return finishNode(result);
21179         }
21180         function parseJSDocNonNullableType() {
21181             var result = createNode(298 /* JSDocNonNullableType */);
21182             nextToken();
21183             result.type = parseNonArrayType();
21184             return finishNode(result);
21185         }
21186         function parseJSDocUnknownOrNullableType() {
21187             var pos = scanner.getStartPos();
21188             // skip the ?
21189             nextToken();
21190             // Need to lookahead to decide if this is a nullable or unknown type.
21191             // Here are cases where we'll pick the unknown type:
21192             //
21193             //      Foo(?,
21194             //      { a: ? }
21195             //      Foo(?)
21196             //      Foo<?>
21197             //      Foo(?=
21198             //      (?|
21199             if (token() === 27 /* CommaToken */ ||
21200                 token() === 19 /* CloseBraceToken */ ||
21201                 token() === 21 /* CloseParenToken */ ||
21202                 token() === 31 /* GreaterThanToken */ ||
21203                 token() === 62 /* EqualsToken */ ||
21204                 token() === 51 /* BarToken */) {
21205                 var result = createNode(296 /* JSDocUnknownType */, pos);
21206                 return finishNode(result);
21207             }
21208             else {
21209                 var result = createNode(297 /* JSDocNullableType */, pos);
21210                 result.type = parseType();
21211                 return finishNode(result);
21212             }
21213         }
21214         function parseJSDocFunctionType() {
21215             if (lookAhead(nextTokenIsOpenParen)) {
21216                 var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
21217                 nextToken();
21218                 fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
21219                 return finishNode(result);
21220             }
21221             var node = createNode(169 /* TypeReference */);
21222             node.typeName = parseIdentifierName();
21223             return finishNode(node);
21224         }
21225         function parseJSDocParameter() {
21226             var parameter = createNode(156 /* Parameter */);
21227             if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
21228                 parameter.name = parseIdentifierName();
21229                 parseExpected(58 /* ColonToken */);
21230             }
21231             parameter.type = parseJSDocType();
21232             return finishNode(parameter);
21233         }
21234         function parseJSDocType() {
21235             scanner.setInJSDocType(true);
21236             var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
21237             if (moduleSpecifier) {
21238                 var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
21239                 terminate: while (true) {
21240                     switch (token()) {
21241                         case 19 /* CloseBraceToken */:
21242                         case 1 /* EndOfFileToken */:
21243                         case 27 /* CommaToken */:
21244                         case 5 /* WhitespaceTrivia */:
21245                             break terminate;
21246                         default:
21247                             nextTokenJSDoc();
21248                     }
21249                 }
21250                 scanner.setInJSDocType(false);
21251                 return finishNode(moduleTag);
21252             }
21253             var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
21254             var type = parseTypeOrTypePredicate();
21255             scanner.setInJSDocType(false);
21256             if (dotdotdot) {
21257                 var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
21258                 variadic.type = type;
21259                 type = finishNode(variadic);
21260             }
21261             if (token() === 62 /* EqualsToken */) {
21262                 return createPostfixType(299 /* JSDocOptionalType */, type);
21263             }
21264             return type;
21265         }
21266         function parseTypeQuery() {
21267             var node = createNode(172 /* TypeQuery */);
21268             parseExpected(108 /* TypeOfKeyword */);
21269             node.exprName = parseEntityName(/*allowReservedWords*/ true);
21270             return finishNode(node);
21271         }
21272         function parseTypeParameter() {
21273             var node = createNode(155 /* TypeParameter */);
21274             node.name = parseIdentifier();
21275             if (parseOptional(90 /* ExtendsKeyword */)) {
21276                 // It's not uncommon for people to write improper constraints to a generic.  If the
21277                 // user writes a constraint that is an expression and not an actual type, then parse
21278                 // it out as an expression (so we can recover well), but report that a type is needed
21279                 // instead.
21280                 if (isStartOfType() || !isStartOfExpression()) {
21281                     node.constraint = parseType();
21282                 }
21283                 else {
21284                     // It was not a type, and it looked like an expression.  Parse out an expression
21285                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
21286                     // and not parseExpression here.  If the user has:
21287                     //
21288                     //      <T extends "">
21289                     //
21290                     // We do *not* want to consume the `>` as we're consuming the expression for "".
21291                     node.expression = parseUnaryExpressionOrHigher();
21292                 }
21293             }
21294             if (parseOptional(62 /* EqualsToken */)) {
21295                 node.default = parseType();
21296             }
21297             return finishNode(node);
21298         }
21299         function parseTypeParameters() {
21300             if (token() === 29 /* LessThanToken */) {
21301                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21302             }
21303         }
21304         function parseParameterType() {
21305             if (parseOptional(58 /* ColonToken */)) {
21306                 return parseType();
21307             }
21308             return undefined;
21309         }
21310         function isStartOfParameter(isJSDocParameter) {
21311             return token() === 25 /* DotDotDotToken */ ||
21312                 isIdentifierOrPrivateIdentifierOrPattern() ||
21313                 ts.isModifierKind(token()) ||
21314                 token() === 59 /* AtToken */ ||
21315                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
21316         }
21317         function parseParameter() {
21318             var node = createNodeWithJSDoc(156 /* Parameter */);
21319             if (token() === 104 /* ThisKeyword */) {
21320                 node.name = createIdentifier(/*isIdentifier*/ true);
21321                 node.type = parseParameterType();
21322                 return finishNode(node);
21323             }
21324             node.decorators = parseDecorators();
21325             node.modifiers = parseModifiers();
21326             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21327             // FormalParameter [Yield,Await]:
21328             //      BindingElement[?Yield,?Await]
21329             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
21330             if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
21331                 // in cases like
21332                 // 'use strict'
21333                 // function foo(static)
21334                 // isParameter('static') === true, because of isModifier('static')
21335                 // however 'static' is not a legal identifier in a strict mode.
21336                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
21337                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
21338                 // to avoid this we'll advance cursor to the next token.
21339                 nextToken();
21340             }
21341             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21342             node.type = parseParameterType();
21343             node.initializer = parseInitializer();
21344             return finishNode(node);
21345         }
21346         /**
21347          * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
21348          * @returns If return type parsing succeeds
21349          */
21350         function fillSignature(returnToken, flags, signature) {
21351             if (!(flags & 32 /* JSDoc */)) {
21352                 signature.typeParameters = parseTypeParameters();
21353             }
21354             var parametersParsedSuccessfully = parseParameterList(signature, flags);
21355             if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
21356                 signature.type = parseTypeOrTypePredicate();
21357                 if (typeHasArrowFunctionBlockingParseError(signature.type))
21358                     return false;
21359             }
21360             return parametersParsedSuccessfully;
21361         }
21362         function shouldParseReturnType(returnToken, isType) {
21363             if (returnToken === 38 /* EqualsGreaterThanToken */) {
21364                 parseExpected(returnToken);
21365                 return true;
21366             }
21367             else if (parseOptional(58 /* ColonToken */)) {
21368                 return true;
21369             }
21370             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
21371                 // This is easy to get backward, especially in type contexts, so parse the type anyway
21372                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
21373                 nextToken();
21374                 return true;
21375             }
21376             return false;
21377         }
21378         // Returns true on success.
21379         function parseParameterList(signature, flags) {
21380             // FormalParameters [Yield,Await]: (modified)
21381             //      [empty]
21382             //      FormalParameterList[?Yield,Await]
21383             //
21384             // FormalParameter[Yield,Await]: (modified)
21385             //      BindingElement[?Yield,Await]
21386             //
21387             // BindingElement [Yield,Await]: (modified)
21388             //      SingleNameBinding[?Yield,?Await]
21389             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21390             //
21391             // SingleNameBinding [Yield,Await]:
21392             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21393             if (!parseExpected(20 /* OpenParenToken */)) {
21394                 signature.parameters = createMissingList();
21395                 return false;
21396             }
21397             var savedYieldContext = inYieldContext();
21398             var savedAwaitContext = inAwaitContext();
21399             setYieldContext(!!(flags & 1 /* Yield */));
21400             setAwaitContext(!!(flags & 2 /* Await */));
21401             signature.parameters = flags & 32 /* JSDoc */ ?
21402                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
21403                 parseDelimitedList(16 /* Parameters */, parseParameter);
21404             setYieldContext(savedYieldContext);
21405             setAwaitContext(savedAwaitContext);
21406             return parseExpected(21 /* CloseParenToken */);
21407         }
21408         function parseTypeMemberSemicolon() {
21409             // We allow type members to be separated by commas or (possibly ASI) semicolons.
21410             // First check if it was a comma.  If so, we're done with the member.
21411             if (parseOptional(27 /* CommaToken */)) {
21412                 return;
21413             }
21414             // Didn't have a comma.  We must have a (possible ASI) semicolon.
21415             parseSemicolon();
21416         }
21417         function parseSignatureMember(kind) {
21418             var node = createNodeWithJSDoc(kind);
21419             if (kind === 166 /* ConstructSignature */) {
21420                 parseExpected(99 /* NewKeyword */);
21421             }
21422             fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21423             parseTypeMemberSemicolon();
21424             return finishNode(node);
21425         }
21426         function isIndexSignature() {
21427             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
21428         }
21429         function isUnambiguouslyIndexSignature() {
21430             // The only allowed sequence is:
21431             //
21432             //   [id:
21433             //
21434             // However, for error recovery, we also check the following cases:
21435             //
21436             //   [...
21437             //   [id,
21438             //   [id?,
21439             //   [id?:
21440             //   [id?]
21441             //   [public id
21442             //   [private id
21443             //   [protected id
21444             //   []
21445             //
21446             nextToken();
21447             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
21448                 return true;
21449             }
21450             if (ts.isModifierKind(token())) {
21451                 nextToken();
21452                 if (isIdentifier()) {
21453                     return true;
21454                 }
21455             }
21456             else if (!isIdentifier()) {
21457                 return false;
21458             }
21459             else {
21460                 // Skip the identifier
21461                 nextToken();
21462             }
21463             // A colon signifies a well formed indexer
21464             // A comma should be a badly formed indexer because comma expressions are not allowed
21465             // in computed properties.
21466             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
21467                 return true;
21468             }
21469             // Question mark could be an indexer with an optional property,
21470             // or it could be a conditional expression in a computed property.
21471             if (token() !== 57 /* QuestionToken */) {
21472                 return false;
21473             }
21474             // If any of the following tokens are after the question mark, it cannot
21475             // be a conditional expression, so treat it as an indexer.
21476             nextToken();
21477             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
21478         }
21479         function parseIndexSignatureDeclaration(node) {
21480             node.kind = 167 /* IndexSignature */;
21481             node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21482             node.type = parseTypeAnnotation();
21483             parseTypeMemberSemicolon();
21484             return finishNode(node);
21485         }
21486         function parsePropertyOrMethodSignature(node) {
21487             node.name = parsePropertyName();
21488             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21489             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21490                 node.kind = 160 /* MethodSignature */;
21491                 // Method signatures don't exist in expression contexts.  So they have neither
21492                 // [Yield] nor [Await]
21493                 fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21494             }
21495             else {
21496                 node.kind = 158 /* PropertySignature */;
21497                 node.type = parseTypeAnnotation();
21498                 if (token() === 62 /* EqualsToken */) {
21499                     // Although type literal properties cannot not have initializers, we attempt
21500                     // to parse an initializer so we can report in the checker that an interface
21501                     // property or type literal property cannot have an initializer.
21502                     node.initializer = parseInitializer();
21503                 }
21504             }
21505             parseTypeMemberSemicolon();
21506             return finishNode(node);
21507         }
21508         function isTypeMemberStart() {
21509             // Return true if we have the start of a signature member
21510             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21511                 return true;
21512             }
21513             var idToken = false;
21514             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
21515             while (ts.isModifierKind(token())) {
21516                 idToken = true;
21517                 nextToken();
21518             }
21519             // Index signatures and computed property names are type members
21520             if (token() === 22 /* OpenBracketToken */) {
21521                 return true;
21522             }
21523             // Try to get the first property-like token following all modifiers
21524             if (isLiteralPropertyName()) {
21525                 idToken = true;
21526                 nextToken();
21527             }
21528             // If we were able to get any potential identifier, check that it is
21529             // the start of a member declaration
21530             if (idToken) {
21531                 return token() === 20 /* OpenParenToken */ ||
21532                     token() === 29 /* LessThanToken */ ||
21533                     token() === 57 /* QuestionToken */ ||
21534                     token() === 58 /* ColonToken */ ||
21535                     token() === 27 /* CommaToken */ ||
21536                     canParseSemicolon();
21537             }
21538             return false;
21539         }
21540         function parseTypeMember() {
21541             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21542                 return parseSignatureMember(165 /* CallSignature */);
21543             }
21544             if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
21545                 return parseSignatureMember(166 /* ConstructSignature */);
21546             }
21547             var node = createNodeWithJSDoc(0 /* Unknown */);
21548             node.modifiers = parseModifiers();
21549             if (isIndexSignature()) {
21550                 return parseIndexSignatureDeclaration(node);
21551             }
21552             return parsePropertyOrMethodSignature(node);
21553         }
21554         function nextTokenIsOpenParenOrLessThan() {
21555             nextToken();
21556             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
21557         }
21558         function nextTokenIsDot() {
21559             return nextToken() === 24 /* DotToken */;
21560         }
21561         function nextTokenIsOpenParenOrLessThanOrDot() {
21562             switch (nextToken()) {
21563                 case 20 /* OpenParenToken */:
21564                 case 29 /* LessThanToken */:
21565                 case 24 /* DotToken */:
21566                     return true;
21567             }
21568             return false;
21569         }
21570         function parseTypeLiteral() {
21571             var node = createNode(173 /* TypeLiteral */);
21572             node.members = parseObjectTypeMembers();
21573             return finishNode(node);
21574         }
21575         function parseObjectTypeMembers() {
21576             var members;
21577             if (parseExpected(18 /* OpenBraceToken */)) {
21578                 members = parseList(4 /* TypeMembers */, parseTypeMember);
21579                 parseExpected(19 /* CloseBraceToken */);
21580             }
21581             else {
21582                 members = createMissingList();
21583             }
21584             return members;
21585         }
21586         function isStartOfMappedType() {
21587             nextToken();
21588             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21589                 return nextToken() === 138 /* ReadonlyKeyword */;
21590             }
21591             if (token() === 138 /* ReadonlyKeyword */) {
21592                 nextToken();
21593             }
21594             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
21595         }
21596         function parseMappedTypeParameter() {
21597             var node = createNode(155 /* TypeParameter */);
21598             node.name = parseIdentifier();
21599             parseExpected(97 /* InKeyword */);
21600             node.constraint = parseType();
21601             return finishNode(node);
21602         }
21603         function parseMappedType() {
21604             var node = createNode(186 /* MappedType */);
21605             parseExpected(18 /* OpenBraceToken */);
21606             if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21607                 node.readonlyToken = parseTokenNode();
21608                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
21609                     parseExpectedToken(138 /* ReadonlyKeyword */);
21610                 }
21611             }
21612             parseExpected(22 /* OpenBracketToken */);
21613             node.typeParameter = parseMappedTypeParameter();
21614             parseExpected(23 /* CloseBracketToken */);
21615             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21616                 node.questionToken = parseTokenNode();
21617                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
21618                     parseExpectedToken(57 /* QuestionToken */);
21619                 }
21620             }
21621             node.type = parseTypeAnnotation();
21622             parseSemicolon();
21623             parseExpected(19 /* CloseBraceToken */);
21624             return finishNode(node);
21625         }
21626         function parseTupleElementType() {
21627             var pos = getNodePos();
21628             if (parseOptional(25 /* DotDotDotToken */)) {
21629                 var node = createNode(177 /* RestType */, pos);
21630                 node.type = parseType();
21631                 return finishNode(node);
21632             }
21633             var type = parseType();
21634             if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
21635                 type.kind = 176 /* OptionalType */;
21636             }
21637             return type;
21638         }
21639         function parseTupleType() {
21640             var node = createNode(175 /* TupleType */);
21641             node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21642             return finishNode(node);
21643         }
21644         function parseParenthesizedType() {
21645             var node = createNode(182 /* ParenthesizedType */);
21646             parseExpected(20 /* OpenParenToken */);
21647             node.type = parseType();
21648             parseExpected(21 /* CloseParenToken */);
21649             return finishNode(node);
21650         }
21651         function parseFunctionOrConstructorType() {
21652             var pos = getNodePos();
21653             var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
21654             var node = createNodeWithJSDoc(kind, pos);
21655             fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
21656             return finishNode(node);
21657         }
21658         function parseKeywordAndNoDot() {
21659             var node = parseTokenNode();
21660             return token() === 24 /* DotToken */ ? undefined : node;
21661         }
21662         function parseLiteralTypeNode(negative) {
21663             var node = createNode(187 /* LiteralType */);
21664             var unaryMinusExpression;
21665             if (negative) {
21666                 unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
21667                 unaryMinusExpression.operator = 40 /* MinusToken */;
21668                 nextToken();
21669             }
21670             var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
21671                 ? parseTokenNode()
21672                 : parseLiteralLikeNode(token());
21673             if (negative) {
21674                 unaryMinusExpression.operand = expression;
21675                 finishNode(unaryMinusExpression);
21676                 expression = unaryMinusExpression;
21677             }
21678             node.literal = expression;
21679             return finishNode(node);
21680         }
21681         function isStartOfTypeOfImportType() {
21682             nextToken();
21683             return token() === 96 /* ImportKeyword */;
21684         }
21685         function parseImportType() {
21686             sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
21687             var node = createNode(188 /* ImportType */);
21688             if (parseOptional(108 /* TypeOfKeyword */)) {
21689                 node.isTypeOf = true;
21690             }
21691             parseExpected(96 /* ImportKeyword */);
21692             parseExpected(20 /* OpenParenToken */);
21693             node.argument = parseType();
21694             parseExpected(21 /* CloseParenToken */);
21695             if (parseOptional(24 /* DotToken */)) {
21696                 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21697             }
21698             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21699                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21700             }
21701             return finishNode(node);
21702         }
21703         function nextTokenIsNumericOrBigIntLiteral() {
21704             nextToken();
21705             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
21706         }
21707         function parseNonArrayType() {
21708             switch (token()) {
21709                 case 125 /* AnyKeyword */:
21710                 case 148 /* UnknownKeyword */:
21711                 case 143 /* StringKeyword */:
21712                 case 140 /* NumberKeyword */:
21713                 case 151 /* BigIntKeyword */:
21714                 case 144 /* SymbolKeyword */:
21715                 case 128 /* BooleanKeyword */:
21716                 case 146 /* UndefinedKeyword */:
21717                 case 137 /* NeverKeyword */:
21718                 case 141 /* ObjectKeyword */:
21719                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
21720                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
21721                 case 41 /* AsteriskToken */:
21722                     return parseJSDocAllType(/*postfixEquals*/ false);
21723                 case 65 /* AsteriskEqualsToken */:
21724                     return parseJSDocAllType(/*postfixEquals*/ true);
21725                 case 60 /* QuestionQuestionToken */:
21726                     // If there is '??', consider that is prefix '?' in JSDoc type.
21727                     scanner.reScanQuestionToken();
21728                 // falls through
21729                 case 57 /* QuestionToken */:
21730                     return parseJSDocUnknownOrNullableType();
21731                 case 94 /* FunctionKeyword */:
21732                     return parseJSDocFunctionType();
21733                 case 53 /* ExclamationToken */:
21734                     return parseJSDocNonNullableType();
21735                 case 14 /* NoSubstitutionTemplateLiteral */:
21736                 case 10 /* StringLiteral */:
21737                 case 8 /* NumericLiteral */:
21738                 case 9 /* BigIntLiteral */:
21739                 case 106 /* TrueKeyword */:
21740                 case 91 /* FalseKeyword */:
21741                     return parseLiteralTypeNode();
21742                 case 40 /* MinusToken */:
21743                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
21744                 case 110 /* VoidKeyword */:
21745                 case 100 /* NullKeyword */:
21746                     return parseTokenNode();
21747                 case 104 /* ThisKeyword */: {
21748                     var thisKeyword = parseThisTypeNode();
21749                     if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21750                         return parseThisTypePredicate(thisKeyword);
21751                     }
21752                     else {
21753                         return thisKeyword;
21754                     }
21755                 }
21756                 case 108 /* TypeOfKeyword */:
21757                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
21758                 case 18 /* OpenBraceToken */:
21759                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
21760                 case 22 /* OpenBracketToken */:
21761                     return parseTupleType();
21762                 case 20 /* OpenParenToken */:
21763                     return parseParenthesizedType();
21764                 case 96 /* ImportKeyword */:
21765                     return parseImportType();
21766                 case 124 /* AssertsKeyword */:
21767                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
21768                 default:
21769                     return parseTypeReference();
21770             }
21771         }
21772         function isStartOfType(inStartOfParameter) {
21773             switch (token()) {
21774                 case 125 /* AnyKeyword */:
21775                 case 148 /* UnknownKeyword */:
21776                 case 143 /* StringKeyword */:
21777                 case 140 /* NumberKeyword */:
21778                 case 151 /* BigIntKeyword */:
21779                 case 128 /* BooleanKeyword */:
21780                 case 138 /* ReadonlyKeyword */:
21781                 case 144 /* SymbolKeyword */:
21782                 case 147 /* UniqueKeyword */:
21783                 case 110 /* VoidKeyword */:
21784                 case 146 /* UndefinedKeyword */:
21785                 case 100 /* NullKeyword */:
21786                 case 104 /* ThisKeyword */:
21787                 case 108 /* TypeOfKeyword */:
21788                 case 137 /* NeverKeyword */:
21789                 case 18 /* OpenBraceToken */:
21790                 case 22 /* OpenBracketToken */:
21791                 case 29 /* LessThanToken */:
21792                 case 51 /* BarToken */:
21793                 case 50 /* AmpersandToken */:
21794                 case 99 /* NewKeyword */:
21795                 case 10 /* StringLiteral */:
21796                 case 8 /* NumericLiteral */:
21797                 case 9 /* BigIntLiteral */:
21798                 case 106 /* TrueKeyword */:
21799                 case 91 /* FalseKeyword */:
21800                 case 141 /* ObjectKeyword */:
21801                 case 41 /* AsteriskToken */:
21802                 case 57 /* QuestionToken */:
21803                 case 53 /* ExclamationToken */:
21804                 case 25 /* DotDotDotToken */:
21805                 case 132 /* InferKeyword */:
21806                 case 96 /* ImportKeyword */:
21807                 case 124 /* AssertsKeyword */:
21808                     return true;
21809                 case 94 /* FunctionKeyword */:
21810                     return !inStartOfParameter;
21811                 case 40 /* MinusToken */:
21812                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
21813                 case 20 /* OpenParenToken */:
21814                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
21815                     // or something that starts a type. We don't want to consider things like '(1)' a type.
21816                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
21817                 default:
21818                     return isIdentifier();
21819             }
21820         }
21821         function isStartOfParenthesizedOrFunctionType() {
21822             nextToken();
21823             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
21824         }
21825         function parsePostfixTypeOrHigher() {
21826             var type = parseNonArrayType();
21827             while (!scanner.hasPrecedingLineBreak()) {
21828                 switch (token()) {
21829                     case 53 /* ExclamationToken */:
21830                         type = createPostfixType(298 /* JSDocNonNullableType */, type);
21831                         break;
21832                     case 57 /* QuestionToken */:
21833                         // If not in JSDoc and next token is start of a type we have a conditional type
21834                         if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
21835                             return type;
21836                         }
21837                         type = createPostfixType(297 /* JSDocNullableType */, type);
21838                         break;
21839                     case 22 /* OpenBracketToken */:
21840                         parseExpected(22 /* OpenBracketToken */);
21841                         if (isStartOfType()) {
21842                             var node = createNode(185 /* IndexedAccessType */, type.pos);
21843                             node.objectType = type;
21844                             node.indexType = parseType();
21845                             parseExpected(23 /* CloseBracketToken */);
21846                             type = finishNode(node);
21847                         }
21848                         else {
21849                             var node = createNode(174 /* ArrayType */, type.pos);
21850                             node.elementType = type;
21851                             parseExpected(23 /* CloseBracketToken */);
21852                             type = finishNode(node);
21853                         }
21854                         break;
21855                     default:
21856                         return type;
21857                 }
21858             }
21859             return type;
21860         }
21861         function createPostfixType(kind, type) {
21862             nextToken();
21863             var postfix = createNode(kind, type.pos);
21864             postfix.type = type;
21865             return finishNode(postfix);
21866         }
21867         function parseTypeOperator(operator) {
21868             var node = createNode(184 /* TypeOperator */);
21869             parseExpected(operator);
21870             node.operator = operator;
21871             node.type = parseTypeOperatorOrHigher();
21872             return finishNode(node);
21873         }
21874         function parseInferType() {
21875             var node = createNode(181 /* InferType */);
21876             parseExpected(132 /* InferKeyword */);
21877             var typeParameter = createNode(155 /* TypeParameter */);
21878             typeParameter.name = parseIdentifier();
21879             node.typeParameter = finishNode(typeParameter);
21880             return finishNode(node);
21881         }
21882         function parseTypeOperatorOrHigher() {
21883             var operator = token();
21884             switch (operator) {
21885                 case 134 /* KeyOfKeyword */:
21886                 case 147 /* UniqueKeyword */:
21887                 case 138 /* ReadonlyKeyword */:
21888                     return parseTypeOperator(operator);
21889                 case 132 /* InferKeyword */:
21890                     return parseInferType();
21891             }
21892             return parsePostfixTypeOrHigher();
21893         }
21894         function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
21895             var start = scanner.getStartPos();
21896             var hasLeadingOperator = parseOptional(operator);
21897             var type = parseConstituentType();
21898             if (token() === operator || hasLeadingOperator) {
21899                 var types = [type];
21900                 while (parseOptional(operator)) {
21901                     types.push(parseConstituentType());
21902                 }
21903                 var node = createNode(kind, start);
21904                 node.types = createNodeArray(types, start);
21905                 type = finishNode(node);
21906             }
21907             return type;
21908         }
21909         function parseIntersectionTypeOrHigher() {
21910             return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
21911         }
21912         function parseUnionTypeOrHigher() {
21913             return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
21914         }
21915         function isStartOfFunctionType() {
21916             if (token() === 29 /* LessThanToken */) {
21917                 return true;
21918             }
21919             return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
21920         }
21921         function skipParameterStart() {
21922             if (ts.isModifierKind(token())) {
21923                 // Skip modifiers
21924                 parseModifiers();
21925             }
21926             if (isIdentifier() || token() === 104 /* ThisKeyword */) {
21927                 nextToken();
21928                 return true;
21929             }
21930             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
21931                 // Return true if we can parse an array or object binding pattern with no errors
21932                 var previousErrorCount = parseDiagnostics.length;
21933                 parseIdentifierOrPattern();
21934                 return previousErrorCount === parseDiagnostics.length;
21935             }
21936             return false;
21937         }
21938         function isUnambiguouslyStartOfFunctionType() {
21939             nextToken();
21940             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
21941                 // ( )
21942                 // ( ...
21943                 return true;
21944             }
21945             if (skipParameterStart()) {
21946                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
21947                 // now see if we have something that indicates a parameter declaration
21948                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
21949                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
21950                     // ( xxx :
21951                     // ( xxx ,
21952                     // ( xxx ?
21953                     // ( xxx =
21954                     return true;
21955                 }
21956                 if (token() === 21 /* CloseParenToken */) {
21957                     nextToken();
21958                     if (token() === 38 /* EqualsGreaterThanToken */) {
21959                         // ( xxx ) =>
21960                         return true;
21961                     }
21962                 }
21963             }
21964             return false;
21965         }
21966         function parseTypeOrTypePredicate() {
21967             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
21968             var type = parseType();
21969             if (typePredicateVariable) {
21970                 var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
21971                 node.assertsModifier = undefined;
21972                 node.parameterName = typePredicateVariable;
21973                 node.type = type;
21974                 return finishNode(node);
21975             }
21976             else {
21977                 return type;
21978             }
21979         }
21980         function parseTypePredicatePrefix() {
21981             var id = parseIdentifier();
21982             if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21983                 nextToken();
21984                 return id;
21985             }
21986         }
21987         function parseAssertsTypePredicate() {
21988             var node = createNode(168 /* TypePredicate */);
21989             node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
21990             node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
21991             node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
21992             return finishNode(node);
21993         }
21994         function parseType() {
21995             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
21996             // apply to 'type' contexts.  So we disable these parameters here before moving on.
21997             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
21998         }
21999         function parseTypeWorker(noConditionalTypes) {
22000             if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
22001                 return parseFunctionOrConstructorType();
22002             }
22003             var type = parseUnionTypeOrHigher();
22004             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
22005                 var node = createNode(180 /* ConditionalType */, type.pos);
22006                 node.checkType = type;
22007                 // The type following 'extends' is not permitted to be another conditional type
22008                 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
22009                 parseExpected(57 /* QuestionToken */);
22010                 node.trueType = parseTypeWorker();
22011                 parseExpected(58 /* ColonToken */);
22012                 node.falseType = parseTypeWorker();
22013                 return finishNode(node);
22014             }
22015             return type;
22016         }
22017         function parseTypeAnnotation() {
22018             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
22019         }
22020         // EXPRESSIONS
22021         function isStartOfLeftHandSideExpression() {
22022             switch (token()) {
22023                 case 104 /* ThisKeyword */:
22024                 case 102 /* SuperKeyword */:
22025                 case 100 /* NullKeyword */:
22026                 case 106 /* TrueKeyword */:
22027                 case 91 /* FalseKeyword */:
22028                 case 8 /* NumericLiteral */:
22029                 case 9 /* BigIntLiteral */:
22030                 case 10 /* StringLiteral */:
22031                 case 14 /* NoSubstitutionTemplateLiteral */:
22032                 case 15 /* TemplateHead */:
22033                 case 20 /* OpenParenToken */:
22034                 case 22 /* OpenBracketToken */:
22035                 case 18 /* OpenBraceToken */:
22036                 case 94 /* FunctionKeyword */:
22037                 case 80 /* ClassKeyword */:
22038                 case 99 /* NewKeyword */:
22039                 case 43 /* SlashToken */:
22040                 case 67 /* SlashEqualsToken */:
22041                 case 75 /* Identifier */:
22042                     return true;
22043                 case 96 /* ImportKeyword */:
22044                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
22045                 default:
22046                     return isIdentifier();
22047             }
22048         }
22049         function isStartOfExpression() {
22050             if (isStartOfLeftHandSideExpression()) {
22051                 return true;
22052             }
22053             switch (token()) {
22054                 case 39 /* PlusToken */:
22055                 case 40 /* MinusToken */:
22056                 case 54 /* TildeToken */:
22057                 case 53 /* ExclamationToken */:
22058                 case 85 /* DeleteKeyword */:
22059                 case 108 /* TypeOfKeyword */:
22060                 case 110 /* VoidKeyword */:
22061                 case 45 /* PlusPlusToken */:
22062                 case 46 /* MinusMinusToken */:
22063                 case 29 /* LessThanToken */:
22064                 case 127 /* AwaitKeyword */:
22065                 case 121 /* YieldKeyword */:
22066                 case 76 /* PrivateIdentifier */:
22067                     // Yield/await always starts an expression.  Either it is an identifier (in which case
22068                     // it is definitely an expression).  Or it's a keyword (either because we're in
22069                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
22070                     return true;
22071                 default:
22072                     // Error tolerance.  If we see the start of some binary operator, we consider
22073                     // that the start of an expression.  That way we'll parse out a missing identifier,
22074                     // give a good message about an identifier being missing, and then consume the
22075                     // rest of the binary expression.
22076                     if (isBinaryOperator()) {
22077                         return true;
22078                     }
22079                     return isIdentifier();
22080             }
22081         }
22082         function isStartOfExpressionStatement() {
22083             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
22084             return token() !== 18 /* OpenBraceToken */ &&
22085                 token() !== 94 /* FunctionKeyword */ &&
22086                 token() !== 80 /* ClassKeyword */ &&
22087                 token() !== 59 /* AtToken */ &&
22088                 isStartOfExpression();
22089         }
22090         function parseExpression() {
22091             // Expression[in]:
22092             //      AssignmentExpression[in]
22093             //      Expression[in] , AssignmentExpression[in]
22094             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
22095             var saveDecoratorContext = inDecoratorContext();
22096             if (saveDecoratorContext) {
22097                 setDecoratorContext(/*val*/ false);
22098             }
22099             var expr = parseAssignmentExpressionOrHigher();
22100             var operatorToken;
22101             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
22102                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
22103             }
22104             if (saveDecoratorContext) {
22105                 setDecoratorContext(/*val*/ true);
22106             }
22107             return expr;
22108         }
22109         function parseInitializer() {
22110             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
22111         }
22112         function parseAssignmentExpressionOrHigher() {
22113             //  AssignmentExpression[in,yield]:
22114             //      1) ConditionalExpression[?in,?yield]
22115             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
22116             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
22117             //      4) ArrowFunctionExpression[?in,?yield]
22118             //      5) AsyncArrowFunctionExpression[in,yield,await]
22119             //      6) [+Yield] YieldExpression[?In]
22120             //
22121             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
22122             // (i.e. they're both BinaryExpressions with an assignment operator in it).
22123             // First, do the simple check if we have a YieldExpression (production '6').
22124             if (isYieldExpression()) {
22125                 return parseYieldExpression();
22126             }
22127             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
22128             // parameter list or is an async arrow function.
22129             // AsyncArrowFunctionExpression:
22130             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22131             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22132             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
22133             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
22134             //
22135             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
22136             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
22137             // with AssignmentExpression if we see one.
22138             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
22139             if (arrowExpression) {
22140                 return arrowExpression;
22141             }
22142             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
22143             // start with a LogicalOrExpression, while the assignment productions can only start with
22144             // LeftHandSideExpressions.
22145             //
22146             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
22147             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
22148             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
22149             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
22150             // and consumes anything.
22151             var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22152             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
22153             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
22154             // identifier and the current token is an arrow.
22155             if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22156                 return parseSimpleArrowFunctionExpression(expr);
22157             }
22158             // Now see if we might be in cases '2' or '3'.
22159             // If the expression was a LHS expression, and we have an assignment operator, then
22160             // we're in '2' or '3'. Consume the assignment and return.
22161             //
22162             // Note: we call reScanGreaterToken so that we get an appropriately merged token
22163             // for cases like `> > =` becoming `>>=`
22164             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
22165                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
22166             }
22167             // It wasn't an assignment or a lambda.  This is a conditional expression:
22168             return parseConditionalExpressionRest(expr);
22169         }
22170         function isYieldExpression() {
22171             if (token() === 121 /* YieldKeyword */) {
22172                 // If we have a 'yield' keyword, and this is a context where yield expressions are
22173                 // allowed, then definitely parse out a yield expression.
22174                 if (inYieldContext()) {
22175                     return true;
22176                 }
22177                 // We're in a context where 'yield expr' is not allowed.  However, if we can
22178                 // definitely tell that the user was trying to parse a 'yield expr' and not
22179                 // just a normal expr that start with a 'yield' identifier, then parse out
22180                 // a 'yield expr'.  We can then report an error later that they are only
22181                 // allowed in generator expressions.
22182                 //
22183                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
22184                 // invocation expression of something called 'yield'.  However, if we have
22185                 // 'yield foo' then that is not legal as a normal expression, so we can
22186                 // definitely recognize this as a yield expression.
22187                 //
22188                 // for now we just check if the next token is an identifier.  More heuristics
22189                 // can be added here later as necessary.  We just need to make sure that we
22190                 // don't accidentally consume something legal.
22191                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22192             }
22193             return false;
22194         }
22195         function nextTokenIsIdentifierOnSameLine() {
22196             nextToken();
22197             return !scanner.hasPrecedingLineBreak() && isIdentifier();
22198         }
22199         function parseYieldExpression() {
22200             var node = createNode(212 /* YieldExpression */);
22201             // YieldExpression[In] :
22202             //      yield
22203             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22204             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22205             nextToken();
22206             if (!scanner.hasPrecedingLineBreak() &&
22207                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
22208                 node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
22209                 node.expression = parseAssignmentExpressionOrHigher();
22210                 return finishNode(node);
22211             }
22212             else {
22213                 // if the next token is not on the same line as yield.  or we don't have an '*' or
22214                 // the start of an expression, then this is just a simple "yield" expression.
22215                 return finishNode(node);
22216             }
22217         }
22218         function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
22219             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
22220             var node;
22221             if (asyncModifier) {
22222                 node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
22223                 node.modifiers = asyncModifier;
22224             }
22225             else {
22226                 node = createNode(202 /* ArrowFunction */, identifier.pos);
22227             }
22228             var parameter = createNode(156 /* Parameter */, identifier.pos);
22229             parameter.name = identifier;
22230             finishNode(parameter);
22231             node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
22232             node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22233             node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
22234             return addJSDocComment(finishNode(node));
22235         }
22236         function tryParseParenthesizedArrowFunctionExpression() {
22237             var triState = isParenthesizedArrowFunctionExpression();
22238             if (triState === 0 /* False */) {
22239                 // It's definitely not a parenthesized arrow function expression.
22240                 return undefined;
22241             }
22242             // If we definitely have an arrow function, then we can just parse one, not requiring a
22243             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
22244             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
22245             // expression instead.
22246             var arrowFunction = triState === 1 /* True */
22247                 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
22248                 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
22249             if (!arrowFunction) {
22250                 // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
22251                 return undefined;
22252             }
22253             var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
22254             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
22255             // have an opening brace, just in case we're in an error state.
22256             var lastToken = token();
22257             arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22258             arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
22259                 ? parseArrowFunctionExpressionBody(isAsync)
22260                 : parseIdentifier();
22261             return finishNode(arrowFunction);
22262         }
22263         //  True        -> We definitely expect a parenthesized arrow function here.
22264         //  False       -> There *cannot* be a parenthesized arrow function here.
22265         //  Unknown     -> There *might* be a parenthesized arrow function here.
22266         //                 Speculatively look ahead to be sure, and rollback if not.
22267         function isParenthesizedArrowFunctionExpression() {
22268             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
22269                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
22270             }
22271             if (token() === 38 /* EqualsGreaterThanToken */) {
22272                 // ERROR RECOVERY TWEAK:
22273                 // If we see a standalone => try to parse it as an arrow function expression as that's
22274                 // likely what the user intended to write.
22275                 return 1 /* True */;
22276             }
22277             // Definitely not a parenthesized arrow function.
22278             return 0 /* False */;
22279         }
22280         function isParenthesizedArrowFunctionExpressionWorker() {
22281             if (token() === 126 /* AsyncKeyword */) {
22282                 nextToken();
22283                 if (scanner.hasPrecedingLineBreak()) {
22284                     return 0 /* False */;
22285                 }
22286                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
22287                     return 0 /* False */;
22288                 }
22289             }
22290             var first = token();
22291             var second = nextToken();
22292             if (first === 20 /* OpenParenToken */) {
22293                 if (second === 21 /* CloseParenToken */) {
22294                     // Simple cases: "() =>", "(): ", and "() {".
22295                     // This is an arrow function with no parameters.
22296                     // The last one is not actually an arrow function,
22297                     // but this is probably what the user intended.
22298                     var third = nextToken();
22299                     switch (third) {
22300                         case 38 /* EqualsGreaterThanToken */:
22301                         case 58 /* ColonToken */:
22302                         case 18 /* OpenBraceToken */:
22303                             return 1 /* True */;
22304                         default:
22305                             return 0 /* False */;
22306                     }
22307                 }
22308                 // If encounter "([" or "({", this could be the start of a binding pattern.
22309                 // Examples:
22310                 //      ([ x ]) => { }
22311                 //      ({ x }) => { }
22312                 //      ([ x ])
22313                 //      ({ x })
22314                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
22315                     return 2 /* Unknown */;
22316                 }
22317                 // Simple case: "(..."
22318                 // This is an arrow function with a rest parameter.
22319                 if (second === 25 /* DotDotDotToken */) {
22320                     return 1 /* True */;
22321                 }
22322                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
22323                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
22324                 // a good error message.
22325                 if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
22326                     return 1 /* True */;
22327                 }
22328                 // If we had "(" followed by something that's not an identifier,
22329                 // then this definitely doesn't look like a lambda.  "this" is not
22330                 // valid, but we want to parse it and then give a semantic error.
22331                 if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
22332                     return 0 /* False */;
22333                 }
22334                 switch (nextToken()) {
22335                     case 58 /* ColonToken */:
22336                         // If we have something like "(a:", then we must have a
22337                         // type-annotated parameter in an arrow function expression.
22338                         return 1 /* True */;
22339                     case 57 /* QuestionToken */:
22340                         nextToken();
22341                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
22342                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
22343                             return 1 /* True */;
22344                         }
22345                         // Otherwise it is definitely not a lambda.
22346                         return 0 /* False */;
22347                     case 27 /* CommaToken */:
22348                     case 62 /* EqualsToken */:
22349                     case 21 /* CloseParenToken */:
22350                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
22351                         return 2 /* Unknown */;
22352                 }
22353                 // It is definitely not an arrow function
22354                 return 0 /* False */;
22355             }
22356             else {
22357                 ts.Debug.assert(first === 29 /* LessThanToken */);
22358                 // If we have "<" not followed by an identifier,
22359                 // then this definitely is not an arrow function.
22360                 if (!isIdentifier()) {
22361                     return 0 /* False */;
22362                 }
22363                 // JSX overrides
22364                 if (sourceFile.languageVariant === 1 /* JSX */) {
22365                     var isArrowFunctionInJsx = lookAhead(function () {
22366                         var third = nextToken();
22367                         if (third === 90 /* ExtendsKeyword */) {
22368                             var fourth = nextToken();
22369                             switch (fourth) {
22370                                 case 62 /* EqualsToken */:
22371                                 case 31 /* GreaterThanToken */:
22372                                     return false;
22373                                 default:
22374                                     return true;
22375                             }
22376                         }
22377                         else if (third === 27 /* CommaToken */) {
22378                             return true;
22379                         }
22380                         return false;
22381                     });
22382                     if (isArrowFunctionInJsx) {
22383                         return 1 /* True */;
22384                     }
22385                     return 0 /* False */;
22386                 }
22387                 // This *could* be a parenthesized arrow function.
22388                 return 2 /* Unknown */;
22389             }
22390         }
22391         function parsePossibleParenthesizedArrowFunctionExpressionHead() {
22392             var tokenPos = scanner.getTokenPos();
22393             if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
22394                 return undefined;
22395             }
22396             var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
22397             if (!result) {
22398                 (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
22399             }
22400             return result;
22401         }
22402         function tryParseAsyncSimpleArrowFunctionExpression() {
22403             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
22404             if (token() === 126 /* AsyncKeyword */) {
22405                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
22406                     var asyncModifier = parseModifiersForArrowFunction();
22407                     var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22408                     return parseSimpleArrowFunctionExpression(expr, asyncModifier);
22409                 }
22410             }
22411             return undefined;
22412         }
22413         function isUnParenthesizedAsyncArrowFunctionWorker() {
22414             // AsyncArrowFunctionExpression:
22415             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22416             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22417             if (token() === 126 /* AsyncKeyword */) {
22418                 nextToken();
22419                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
22420                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
22421                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
22422                     return 0 /* False */;
22423                 }
22424                 // Check for un-parenthesized AsyncArrowFunction
22425                 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22426                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22427                     return 1 /* True */;
22428                 }
22429             }
22430             return 0 /* False */;
22431         }
22432         function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
22433             var node = createNodeWithJSDoc(202 /* ArrowFunction */);
22434             node.modifiers = parseModifiersForArrowFunction();
22435             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
22436             // Arrow functions are never generators.
22437             //
22438             // If we're speculatively parsing a signature for a parenthesized arrow function, then
22439             // we have to have a complete parameter list.  Otherwise we might see something like
22440             // a => (b => c)
22441             // And think that "(b =>" was actually a parenthesized arrow function with a missing
22442             // close paren.
22443             if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
22444                 return undefined;
22445             }
22446             // Parsing a signature isn't enough.
22447             // Parenthesized arrow signatures often look like other valid expressions.
22448             // For instance:
22449             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
22450             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
22451             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
22452             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
22453             //
22454             // So we need just a bit of lookahead to ensure that it can only be a signature.
22455             var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
22456             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
22457                 // Returning undefined here will cause our caller to rewind to where we started from.
22458                 return undefined;
22459             }
22460             return node;
22461         }
22462         function parseArrowFunctionExpressionBody(isAsync) {
22463             if (token() === 18 /* OpenBraceToken */) {
22464                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
22465             }
22466             if (token() !== 26 /* SemicolonToken */ &&
22467                 token() !== 94 /* FunctionKeyword */ &&
22468                 token() !== 80 /* ClassKeyword */ &&
22469                 isStartOfStatement() &&
22470                 !isStartOfExpressionStatement()) {
22471                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
22472                 //
22473                 // Here we try to recover from a potential error situation in the case where the
22474                 // user meant to supply a block. For example, if the user wrote:
22475                 //
22476                 //  a =>
22477                 //      let v = 0;
22478                 //  }
22479                 //
22480                 // they may be missing an open brace.  Check to see if that's the case so we can
22481                 // try to recover better.  If we don't do this, then the next close curly we see may end
22482                 // up preemptively closing the containing construct.
22483                 //
22484                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
22485                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
22486             }
22487             return isAsync
22488                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
22489                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
22490         }
22491         function parseConditionalExpressionRest(leftOperand) {
22492             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
22493             var questionToken = parseOptionalToken(57 /* QuestionToken */);
22494             if (!questionToken) {
22495                 return leftOperand;
22496             }
22497             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
22498             // we do not that for the 'whenFalse' part.
22499             var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
22500             node.condition = leftOperand;
22501             node.questionToken = questionToken;
22502             node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
22503             node.colonToken = parseExpectedToken(58 /* ColonToken */);
22504             node.whenFalse = ts.nodeIsPresent(node.colonToken)
22505                 ? parseAssignmentExpressionOrHigher()
22506                 : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
22507             return finishNode(node);
22508         }
22509         function parseBinaryExpressionOrHigher(precedence) {
22510             var leftOperand = parseUnaryExpressionOrHigher();
22511             return parseBinaryExpressionRest(precedence, leftOperand);
22512         }
22513         function isInOrOfKeyword(t) {
22514             return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
22515         }
22516         function parseBinaryExpressionRest(precedence, leftOperand) {
22517             while (true) {
22518                 // We either have a binary operator here, or we're finished.  We call
22519                 // reScanGreaterToken so that we merge token sequences like > and = into >=
22520                 reScanGreaterToken();
22521                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
22522                 // Check the precedence to see if we should "take" this operator
22523                 // - For left associative operator (all operator but **), consume the operator,
22524                 //   recursively call the function below, and parse binaryExpression as a rightOperand
22525                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
22526                 //   For example:
22527                 //      a - b - c;
22528                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22529                 //      a * b - c
22530                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22531                 //      a - b * c;
22532                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
22533                 // - For right associative operator (**), consume the operator, recursively call the function
22534                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
22535                 //   the operator is strictly grater than the current precedence
22536                 //   For example:
22537                 //      a ** b ** c;
22538                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22539                 //      a - b ** c;
22540                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22541                 //      a ** b - c
22542                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
22543                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
22544                     newPrecedence >= precedence :
22545                     newPrecedence > precedence;
22546                 if (!consumeCurrentOperator) {
22547                     break;
22548                 }
22549                 if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
22550                     break;
22551                 }
22552                 if (token() === 123 /* AsKeyword */) {
22553                     // Make sure we *do* perform ASI for constructs like this:
22554                     //    var x = foo
22555                     //    as (Bar)
22556                     // This should be parsed as an initialized variable, followed
22557                     // by a function call to 'as' with the argument 'Bar'
22558                     if (scanner.hasPrecedingLineBreak()) {
22559                         break;
22560                     }
22561                     else {
22562                         nextToken();
22563                         leftOperand = makeAsExpression(leftOperand, parseType());
22564                     }
22565                 }
22566                 else {
22567                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
22568                 }
22569             }
22570             return leftOperand;
22571         }
22572         function isBinaryOperator() {
22573             if (inDisallowInContext() && token() === 97 /* InKeyword */) {
22574                 return false;
22575             }
22576             return ts.getBinaryOperatorPrecedence(token()) > 0;
22577         }
22578         function makeBinaryExpression(left, operatorToken, right) {
22579             var node = createNode(209 /* BinaryExpression */, left.pos);
22580             node.left = left;
22581             node.operatorToken = operatorToken;
22582             node.right = right;
22583             return finishNode(node);
22584         }
22585         function makeAsExpression(left, right) {
22586             var node = createNode(217 /* AsExpression */, left.pos);
22587             node.expression = left;
22588             node.type = right;
22589             return finishNode(node);
22590         }
22591         function parsePrefixUnaryExpression() {
22592             var node = createNode(207 /* PrefixUnaryExpression */);
22593             node.operator = token();
22594             nextToken();
22595             node.operand = parseSimpleUnaryExpression();
22596             return finishNode(node);
22597         }
22598         function parseDeleteExpression() {
22599             var node = createNode(203 /* DeleteExpression */);
22600             nextToken();
22601             node.expression = parseSimpleUnaryExpression();
22602             return finishNode(node);
22603         }
22604         function parseTypeOfExpression() {
22605             var node = createNode(204 /* TypeOfExpression */);
22606             nextToken();
22607             node.expression = parseSimpleUnaryExpression();
22608             return finishNode(node);
22609         }
22610         function parseVoidExpression() {
22611             var node = createNode(205 /* VoidExpression */);
22612             nextToken();
22613             node.expression = parseSimpleUnaryExpression();
22614             return finishNode(node);
22615         }
22616         function isAwaitExpression() {
22617             if (token() === 127 /* AwaitKeyword */) {
22618                 if (inAwaitContext()) {
22619                     return true;
22620                 }
22621                 // here we are using similar heuristics as 'isYieldExpression'
22622                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22623             }
22624             return false;
22625         }
22626         function parseAwaitExpression() {
22627             var node = createNode(206 /* AwaitExpression */);
22628             nextToken();
22629             node.expression = parseSimpleUnaryExpression();
22630             return finishNode(node);
22631         }
22632         /**
22633          * Parse ES7 exponential expression and await expression
22634          *
22635          * ES7 ExponentiationExpression:
22636          *      1) UnaryExpression[?Yield]
22637          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
22638          *
22639          */
22640         function parseUnaryExpressionOrHigher() {
22641             /**
22642              * ES7 UpdateExpression:
22643              *      1) LeftHandSideExpression[?Yield]
22644              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
22645              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
22646              *      4) ++UnaryExpression[?Yield]
22647              *      5) --UnaryExpression[?Yield]
22648              */
22649             if (isUpdateExpression()) {
22650                 var updateExpression = parseUpdateExpression();
22651                 return token() === 42 /* AsteriskAsteriskToken */ ?
22652                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
22653                     updateExpression;
22654             }
22655             /**
22656              * ES7 UnaryExpression:
22657              *      1) UpdateExpression[?yield]
22658              *      2) delete UpdateExpression[?yield]
22659              *      3) void UpdateExpression[?yield]
22660              *      4) typeof UpdateExpression[?yield]
22661              *      5) + UpdateExpression[?yield]
22662              *      6) - UpdateExpression[?yield]
22663              *      7) ~ UpdateExpression[?yield]
22664              *      8) ! UpdateExpression[?yield]
22665              */
22666             var unaryOperator = token();
22667             var simpleUnaryExpression = parseSimpleUnaryExpression();
22668             if (token() === 42 /* AsteriskAsteriskToken */) {
22669                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
22670                 var end = simpleUnaryExpression.end;
22671                 if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
22672                     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);
22673                 }
22674                 else {
22675                     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));
22676                 }
22677             }
22678             return simpleUnaryExpression;
22679         }
22680         /**
22681          * Parse ES7 simple-unary expression or higher:
22682          *
22683          * ES7 UnaryExpression:
22684          *      1) UpdateExpression[?yield]
22685          *      2) delete UnaryExpression[?yield]
22686          *      3) void UnaryExpression[?yield]
22687          *      4) typeof UnaryExpression[?yield]
22688          *      5) + UnaryExpression[?yield]
22689          *      6) - UnaryExpression[?yield]
22690          *      7) ~ UnaryExpression[?yield]
22691          *      8) ! UnaryExpression[?yield]
22692          *      9) [+Await] await UnaryExpression[?yield]
22693          */
22694         function parseSimpleUnaryExpression() {
22695             switch (token()) {
22696                 case 39 /* PlusToken */:
22697                 case 40 /* MinusToken */:
22698                 case 54 /* TildeToken */:
22699                 case 53 /* ExclamationToken */:
22700                     return parsePrefixUnaryExpression();
22701                 case 85 /* DeleteKeyword */:
22702                     return parseDeleteExpression();
22703                 case 108 /* TypeOfKeyword */:
22704                     return parseTypeOfExpression();
22705                 case 110 /* VoidKeyword */:
22706                     return parseVoidExpression();
22707                 case 29 /* LessThanToken */:
22708                     // This is modified UnaryExpression grammar in TypeScript
22709                     //  UnaryExpression (modified):
22710                     //      < type > UnaryExpression
22711                     return parseTypeAssertion();
22712                 case 127 /* AwaitKeyword */:
22713                     if (isAwaitExpression()) {
22714                         return parseAwaitExpression();
22715                     }
22716                 // falls through
22717                 default:
22718                     return parseUpdateExpression();
22719             }
22720         }
22721         /**
22722          * Check if the current token can possibly be an ES7 increment expression.
22723          *
22724          * ES7 UpdateExpression:
22725          *      LeftHandSideExpression[?Yield]
22726          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
22727          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
22728          *      ++LeftHandSideExpression[?Yield]
22729          *      --LeftHandSideExpression[?Yield]
22730          */
22731         function isUpdateExpression() {
22732             // This function is called inside parseUnaryExpression to decide
22733             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
22734             switch (token()) {
22735                 case 39 /* PlusToken */:
22736                 case 40 /* MinusToken */:
22737                 case 54 /* TildeToken */:
22738                 case 53 /* ExclamationToken */:
22739                 case 85 /* DeleteKeyword */:
22740                 case 108 /* TypeOfKeyword */:
22741                 case 110 /* VoidKeyword */:
22742                 case 127 /* AwaitKeyword */:
22743                     return false;
22744                 case 29 /* LessThanToken */:
22745                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
22746                     if (sourceFile.languageVariant !== 1 /* JSX */) {
22747                         return false;
22748                     }
22749                 // We are in JSX context and the token is part of JSXElement.
22750                 // falls through
22751                 default:
22752                     return true;
22753             }
22754         }
22755         /**
22756          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
22757          *
22758          * ES7 UpdateExpression[yield]:
22759          *      1) LeftHandSideExpression[?yield]
22760          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
22761          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
22762          *      4) ++LeftHandSideExpression[?yield]
22763          *      5) --LeftHandSideExpression[?yield]
22764          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
22765          */
22766         function parseUpdateExpression() {
22767             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
22768                 var node = createNode(207 /* PrefixUnaryExpression */);
22769                 node.operator = token();
22770                 nextToken();
22771                 node.operand = parseLeftHandSideExpressionOrHigher();
22772                 return finishNode(node);
22773             }
22774             else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
22775                 // JSXElement is part of primaryExpression
22776                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
22777             }
22778             var expression = parseLeftHandSideExpressionOrHigher();
22779             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
22780             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
22781                 var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
22782                 node.operand = expression;
22783                 node.operator = token();
22784                 nextToken();
22785                 return finishNode(node);
22786             }
22787             return expression;
22788         }
22789         function parseLeftHandSideExpressionOrHigher() {
22790             // Original Ecma:
22791             // LeftHandSideExpression: See 11.2
22792             //      NewExpression
22793             //      CallExpression
22794             //
22795             // Our simplification:
22796             //
22797             // LeftHandSideExpression: See 11.2
22798             //      MemberExpression
22799             //      CallExpression
22800             //
22801             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
22802             // MemberExpression to make our lives easier.
22803             //
22804             // to best understand the below code, it's important to see how CallExpression expands
22805             // out into its own productions:
22806             //
22807             // CallExpression:
22808             //      MemberExpression Arguments
22809             //      CallExpression Arguments
22810             //      CallExpression[Expression]
22811             //      CallExpression.IdentifierName
22812             //      import (AssignmentExpression)
22813             //      super Arguments
22814             //      super.IdentifierName
22815             //
22816             // Because of the recursion in these calls, we need to bottom out first. There are three
22817             // bottom out states we can run into: 1) We see 'super' which must start either of
22818             // the last two CallExpression productions. 2) We see 'import' which must start import call.
22819             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
22820             // or starts the beginning of the first four CallExpression productions.
22821             var expression;
22822             if (token() === 96 /* ImportKeyword */) {
22823                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
22824                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
22825                     // For example:
22826                     //      var foo3 = require("subfolder
22827                     //      import * as foo1 from "module-from-node
22828                     // We want this import to be a statement rather than import call expression
22829                     sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
22830                     expression = parseTokenNode();
22831                 }
22832                 else if (lookAhead(nextTokenIsDot)) {
22833                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
22834                     var fullStart = scanner.getStartPos();
22835                     nextToken(); // advance past the 'import'
22836                     nextToken(); // advance past the dot
22837                     var node = createNode(219 /* MetaProperty */, fullStart);
22838                     node.keywordToken = 96 /* ImportKeyword */;
22839                     node.name = parseIdentifierName();
22840                     expression = finishNode(node);
22841                     sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
22842                 }
22843                 else {
22844                     expression = parseMemberExpressionOrHigher();
22845                 }
22846             }
22847             else {
22848                 expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
22849             }
22850             // Now, we *may* be complete.  However, we might have consumed the start of a
22851             // CallExpression or OptionalExpression.  As such, we need to consume the rest
22852             // of it here to be complete.
22853             return parseCallExpressionRest(expression);
22854         }
22855         function parseMemberExpressionOrHigher() {
22856             // Note: to make our lives simpler, we decompose the NewExpression productions and
22857             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
22858             // like so:
22859             //
22860             //   PrimaryExpression : See 11.1
22861             //      this
22862             //      Identifier
22863             //      Literal
22864             //      ArrayLiteral
22865             //      ObjectLiteral
22866             //      (Expression)
22867             //      FunctionExpression
22868             //      new MemberExpression Arguments?
22869             //
22870             //   MemberExpression : See 11.2
22871             //      PrimaryExpression
22872             //      MemberExpression[Expression]
22873             //      MemberExpression.IdentifierName
22874             //
22875             //   CallExpression : See 11.2
22876             //      MemberExpression
22877             //      CallExpression Arguments
22878             //      CallExpression[Expression]
22879             //      CallExpression.IdentifierName
22880             //
22881             // Technically this is ambiguous.  i.e. CallExpression defines:
22882             //
22883             //   CallExpression:
22884             //      CallExpression Arguments
22885             //
22886             // If you see: "new Foo()"
22887             //
22888             // Then that could be treated as a single ObjectCreationExpression, or it could be
22889             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
22890             // the original grammar) by making sure that if we see an ObjectCreationExpression
22891             // we always consume arguments if they are there. So we treat "new Foo()" as an
22892             // object creation only, and not at all as an invocation.  Another way to think
22893             // about this is that for every "new" that we see, we will consume an argument list if
22894             // it is there as part of the *associated* object creation node.  Any additional
22895             // argument lists we see, will become invocation expressions.
22896             //
22897             // Because there are no other places in the grammar now that refer to FunctionExpression
22898             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
22899             // production.
22900             //
22901             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
22902             // of the recursion immediately.  So we parse out a primary expression to start with.
22903             var expression = parsePrimaryExpression();
22904             return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
22905         }
22906         function parseSuperExpression() {
22907             var expression = parseTokenNode();
22908             if (token() === 29 /* LessThanToken */) {
22909                 var startPos = getNodePos();
22910                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
22911                 if (typeArguments !== undefined) {
22912                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
22913                 }
22914             }
22915             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
22916                 return expression;
22917             }
22918             // If we have seen "super" it must be followed by '(' or '.'.
22919             // If it wasn't then just try to parse out a '.' and report an error.
22920             var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
22921             node.expression = expression;
22922             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
22923             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
22924             node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
22925             return finishNode(node);
22926         }
22927         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
22928             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
22929             var result;
22930             if (opening.kind === 268 /* JsxOpeningElement */) {
22931                 var node = createNode(266 /* JsxElement */, opening.pos);
22932                 node.openingElement = opening;
22933                 node.children = parseJsxChildren(node.openingElement);
22934                 node.closingElement = parseJsxClosingElement(inExpressionContext);
22935                 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
22936                     parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
22937                 }
22938                 result = finishNode(node);
22939             }
22940             else if (opening.kind === 271 /* JsxOpeningFragment */) {
22941                 var node = createNode(270 /* JsxFragment */, opening.pos);
22942                 node.openingFragment = opening;
22943                 node.children = parseJsxChildren(node.openingFragment);
22944                 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
22945                 result = finishNode(node);
22946             }
22947             else {
22948                 ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
22949                 // Nothing else to do for self-closing elements
22950                 result = opening;
22951             }
22952             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
22953             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
22954             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
22955             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
22956             // does less damage and we can report a better error.
22957             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
22958             // of one sort or another.
22959             if (inExpressionContext && token() === 29 /* LessThanToken */) {
22960                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
22961                 if (invalidElement) {
22962                     parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
22963                     var badNode = createNode(209 /* BinaryExpression */, result.pos);
22964                     badNode.end = invalidElement.end;
22965                     badNode.left = result;
22966                     badNode.right = invalidElement;
22967                     badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
22968                     badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
22969                     return badNode;
22970                 }
22971             }
22972             return result;
22973         }
22974         function parseJsxText() {
22975             var node = createNode(11 /* JsxText */);
22976             node.text = scanner.getTokenValue();
22977             node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
22978             currentToken = scanner.scanJsxToken();
22979             return finishNode(node);
22980         }
22981         function parseJsxChild(openingTag, token) {
22982             switch (token) {
22983                 case 1 /* EndOfFileToken */:
22984                     // If we hit EOF, issue the error at the tag that lacks the closing element
22985                     // rather than at the end of the file (which is useless)
22986                     if (ts.isJsxOpeningFragment(openingTag)) {
22987                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
22988                     }
22989                     else {
22990                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
22991                         // or to cover only 'Foo' in < Foo >
22992                         var tag = openingTag.tagName;
22993                         var start = ts.skipTrivia(sourceText, tag.pos);
22994                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
22995                     }
22996                     return undefined;
22997                 case 30 /* LessThanSlashToken */:
22998                 case 7 /* ConflictMarkerTrivia */:
22999                     return undefined;
23000                 case 11 /* JsxText */:
23001                 case 12 /* JsxTextAllWhiteSpaces */:
23002                     return parseJsxText();
23003                 case 18 /* OpenBraceToken */:
23004                     return parseJsxExpression(/*inExpressionContext*/ false);
23005                 case 29 /* LessThanToken */:
23006                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
23007                 default:
23008                     return ts.Debug.assertNever(token);
23009             }
23010         }
23011         function parseJsxChildren(openingTag) {
23012             var list = [];
23013             var listPos = getNodePos();
23014             var saveParsingContext = parsingContext;
23015             parsingContext |= 1 << 14 /* JsxChildren */;
23016             while (true) {
23017                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
23018                 if (!child)
23019                     break;
23020                 list.push(child);
23021             }
23022             parsingContext = saveParsingContext;
23023             return createNodeArray(list, listPos);
23024         }
23025         function parseJsxAttributes() {
23026             var jsxAttributes = createNode(274 /* JsxAttributes */);
23027             jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
23028             return finishNode(jsxAttributes);
23029         }
23030         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
23031             var fullStart = scanner.getStartPos();
23032             parseExpected(29 /* LessThanToken */);
23033             if (token() === 31 /* GreaterThanToken */) {
23034                 // See below for explanation of scanJsxText
23035                 var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
23036                 scanJsxText();
23037                 return finishNode(node_1);
23038             }
23039             var tagName = parseJsxElementName();
23040             var typeArguments = tryParseTypeArguments();
23041             var attributes = parseJsxAttributes();
23042             var node;
23043             if (token() === 31 /* GreaterThanToken */) {
23044                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
23045                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
23046                 // scanning errors
23047                 node = createNode(268 /* JsxOpeningElement */, fullStart);
23048                 scanJsxText();
23049             }
23050             else {
23051                 parseExpected(43 /* SlashToken */);
23052                 if (inExpressionContext) {
23053                     parseExpected(31 /* GreaterThanToken */);
23054                 }
23055                 else {
23056                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
23057                     scanJsxText();
23058                 }
23059                 node = createNode(267 /* JsxSelfClosingElement */, fullStart);
23060             }
23061             node.tagName = tagName;
23062             node.typeArguments = typeArguments;
23063             node.attributes = attributes;
23064             return finishNode(node);
23065         }
23066         function parseJsxElementName() {
23067             scanJsxIdentifier();
23068             // JsxElement can have name in the form of
23069             //      propertyAccessExpression
23070             //      primaryExpression in the form of an identifier and "this" keyword
23071             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
23072             // We only want to consider "this" as a primaryExpression
23073             var expression = token() === 104 /* ThisKeyword */ ?
23074                 parseTokenNode() : parseIdentifierName();
23075             while (parseOptional(24 /* DotToken */)) {
23076                 var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23077                 propertyAccess.expression = expression;
23078                 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
23079                 expression = finishNode(propertyAccess);
23080             }
23081             return expression;
23082         }
23083         function parseJsxExpression(inExpressionContext) {
23084             var node = createNode(276 /* JsxExpression */);
23085             if (!parseExpected(18 /* OpenBraceToken */)) {
23086                 return undefined;
23087             }
23088             if (token() !== 19 /* CloseBraceToken */) {
23089                 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
23090                 // Only an AssignmentExpression is valid here per the JSX spec,
23091                 // but we can unambiguously parse a comma sequence and provide
23092                 // a better error message in grammar checking.
23093                 node.expression = parseExpression();
23094             }
23095             if (inExpressionContext) {
23096                 parseExpected(19 /* CloseBraceToken */);
23097             }
23098             else {
23099                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
23100                     scanJsxText();
23101                 }
23102             }
23103             return finishNode(node);
23104         }
23105         function parseJsxAttribute() {
23106             if (token() === 18 /* OpenBraceToken */) {
23107                 return parseJsxSpreadAttribute();
23108             }
23109             scanJsxIdentifier();
23110             var node = createNode(273 /* JsxAttribute */);
23111             node.name = parseIdentifierName();
23112             if (token() === 62 /* EqualsToken */) {
23113                 switch (scanJsxAttributeValue()) {
23114                     case 10 /* StringLiteral */:
23115                         node.initializer = parseLiteralNode();
23116                         break;
23117                     default:
23118                         node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
23119                         break;
23120                 }
23121             }
23122             return finishNode(node);
23123         }
23124         function parseJsxSpreadAttribute() {
23125             var node = createNode(275 /* JsxSpreadAttribute */);
23126             parseExpected(18 /* OpenBraceToken */);
23127             parseExpected(25 /* DotDotDotToken */);
23128             node.expression = parseExpression();
23129             parseExpected(19 /* CloseBraceToken */);
23130             return finishNode(node);
23131         }
23132         function parseJsxClosingElement(inExpressionContext) {
23133             var node = createNode(269 /* JsxClosingElement */);
23134             parseExpected(30 /* LessThanSlashToken */);
23135             node.tagName = parseJsxElementName();
23136             if (inExpressionContext) {
23137                 parseExpected(31 /* GreaterThanToken */);
23138             }
23139             else {
23140                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
23141                 scanJsxText();
23142             }
23143             return finishNode(node);
23144         }
23145         function parseJsxClosingFragment(inExpressionContext) {
23146             var node = createNode(272 /* JsxClosingFragment */);
23147             parseExpected(30 /* LessThanSlashToken */);
23148             if (ts.tokenIsIdentifierOrKeyword(token())) {
23149                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
23150             }
23151             if (inExpressionContext) {
23152                 parseExpected(31 /* GreaterThanToken */);
23153             }
23154             else {
23155                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
23156                 scanJsxText();
23157             }
23158             return finishNode(node);
23159         }
23160         function parseTypeAssertion() {
23161             var node = createNode(199 /* TypeAssertionExpression */);
23162             parseExpected(29 /* LessThanToken */);
23163             node.type = parseType();
23164             parseExpected(31 /* GreaterThanToken */);
23165             node.expression = parseSimpleUnaryExpression();
23166             return finishNode(node);
23167         }
23168         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
23169             nextToken();
23170             return ts.tokenIsIdentifierOrKeyword(token())
23171                 || token() === 22 /* OpenBracketToken */
23172                 || isTemplateStartOfTaggedTemplate();
23173         }
23174         function isStartOfOptionalPropertyOrElementAccessChain() {
23175             return token() === 28 /* QuestionDotToken */
23176                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
23177         }
23178         function tryReparseOptionalChain(node) {
23179             if (node.flags & 32 /* OptionalChain */) {
23180                 return true;
23181             }
23182             // check for an optional chain in a non-null expression
23183             if (ts.isNonNullExpression(node)) {
23184                 var expr = node.expression;
23185                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
23186                     expr = expr.expression;
23187                 }
23188                 if (expr.flags & 32 /* OptionalChain */) {
23189                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
23190                     while (ts.isNonNullExpression(node)) {
23191                         node.flags |= 32 /* OptionalChain */;
23192                         node = node.expression;
23193                     }
23194                     return true;
23195                 }
23196             }
23197             return false;
23198         }
23199         function parsePropertyAccessExpressionRest(expression, questionDotToken) {
23200             var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23201             propertyAccess.expression = expression;
23202             propertyAccess.questionDotToken = questionDotToken;
23203             propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
23204             if (questionDotToken || tryReparseOptionalChain(expression)) {
23205                 propertyAccess.flags |= 32 /* OptionalChain */;
23206                 if (ts.isPrivateIdentifier(propertyAccess.name)) {
23207                     parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
23208                 }
23209             }
23210             return finishNode(propertyAccess);
23211         }
23212         function parseElementAccessExpressionRest(expression, questionDotToken) {
23213             var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
23214             indexedAccess.expression = expression;
23215             indexedAccess.questionDotToken = questionDotToken;
23216             if (token() === 23 /* CloseBracketToken */) {
23217                 indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
23218             }
23219             else {
23220                 var argument = allowInAnd(parseExpression);
23221                 if (ts.isStringOrNumericLiteralLike(argument)) {
23222                     argument.text = internIdentifier(argument.text);
23223                 }
23224                 indexedAccess.argumentExpression = argument;
23225             }
23226             parseExpected(23 /* CloseBracketToken */);
23227             if (questionDotToken || tryReparseOptionalChain(expression)) {
23228                 indexedAccess.flags |= 32 /* OptionalChain */;
23229             }
23230             return finishNode(indexedAccess);
23231         }
23232         function parseMemberExpressionRest(expression, allowOptionalChain) {
23233             while (true) {
23234                 var questionDotToken = void 0;
23235                 var isPropertyAccess = false;
23236                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
23237                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
23238                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
23239                 }
23240                 else {
23241                     isPropertyAccess = parseOptional(24 /* DotToken */);
23242                 }
23243                 if (isPropertyAccess) {
23244                     expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
23245                     continue;
23246                 }
23247                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
23248                     nextToken();
23249                     var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
23250                     nonNullExpression.expression = expression;
23251                     expression = finishNode(nonNullExpression);
23252                     continue;
23253                 }
23254                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
23255                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
23256                     expression = parseElementAccessExpressionRest(expression, questionDotToken);
23257                     continue;
23258                 }
23259                 if (isTemplateStartOfTaggedTemplate()) {
23260                     expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
23261                     continue;
23262                 }
23263                 return expression;
23264             }
23265         }
23266         function isTemplateStartOfTaggedTemplate() {
23267             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
23268         }
23269         function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
23270             var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
23271             tagExpression.tag = tag;
23272             tagExpression.questionDotToken = questionDotToken;
23273             tagExpression.typeArguments = typeArguments;
23274             tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
23275                 ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
23276                 : parseTemplateExpression(/*isTaggedTemplate*/ true);
23277             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
23278                 tagExpression.flags |= 32 /* OptionalChain */;
23279             }
23280             return finishNode(tagExpression);
23281         }
23282         function parseCallExpressionRest(expression) {
23283             while (true) {
23284                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
23285                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
23286                 // handle 'foo<<T>()'
23287                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
23288                     // See if this is the start of a generic invocation.  If so, consume it and
23289                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
23290                     // part of an arithmetic expression.  Break out so we consume it higher in the
23291                     // stack.
23292                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
23293                     if (typeArguments) {
23294                         if (isTemplateStartOfTaggedTemplate()) {
23295                             expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
23296                             continue;
23297                         }
23298                         var callExpr = createNode(196 /* CallExpression */, expression.pos);
23299                         callExpr.expression = expression;
23300                         callExpr.questionDotToken = questionDotToken;
23301                         callExpr.typeArguments = typeArguments;
23302                         callExpr.arguments = parseArgumentList();
23303                         if (questionDotToken || tryReparseOptionalChain(expression)) {
23304                             callExpr.flags |= 32 /* OptionalChain */;
23305                         }
23306                         expression = finishNode(callExpr);
23307                         continue;
23308                     }
23309                 }
23310                 else if (token() === 20 /* OpenParenToken */) {
23311                     var callExpr = createNode(196 /* CallExpression */, expression.pos);
23312                     callExpr.expression = expression;
23313                     callExpr.questionDotToken = questionDotToken;
23314                     callExpr.arguments = parseArgumentList();
23315                     if (questionDotToken || tryReparseOptionalChain(expression)) {
23316                         callExpr.flags |= 32 /* OptionalChain */;
23317                     }
23318                     expression = finishNode(callExpr);
23319                     continue;
23320                 }
23321                 if (questionDotToken) {
23322                     // We failed to parse anything, so report a missing identifier here.
23323                     var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23324                     propertyAccess.expression = expression;
23325                     propertyAccess.questionDotToken = questionDotToken;
23326                     propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
23327                     propertyAccess.flags |= 32 /* OptionalChain */;
23328                     expression = finishNode(propertyAccess);
23329                 }
23330                 break;
23331             }
23332             return expression;
23333         }
23334         function parseArgumentList() {
23335             parseExpected(20 /* OpenParenToken */);
23336             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
23337             parseExpected(21 /* CloseParenToken */);
23338             return result;
23339         }
23340         function parseTypeArgumentsInExpression() {
23341             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
23342                 return undefined;
23343             }
23344             nextToken();
23345             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
23346             if (!parseExpected(31 /* GreaterThanToken */)) {
23347                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
23348                 return undefined;
23349             }
23350             // If we have a '<', then only parse this as a argument list if the type arguments
23351             // are complete and we have an open paren.  if we don't, rewind and return nothing.
23352             return typeArguments && canFollowTypeArgumentsInExpression()
23353                 ? typeArguments
23354                 : undefined;
23355         }
23356         function canFollowTypeArgumentsInExpression() {
23357             switch (token()) {
23358                 case 20 /* OpenParenToken */: // foo<x>(
23359                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
23360                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
23361                 // these are the only tokens can legally follow a type argument
23362                 // list. So we definitely want to treat them as type arg lists.
23363                 // falls through
23364                 case 24 /* DotToken */: // foo<x>.
23365                 case 21 /* CloseParenToken */: // foo<x>)
23366                 case 23 /* CloseBracketToken */: // foo<x>]
23367                 case 58 /* ColonToken */: // foo<x>:
23368                 case 26 /* SemicolonToken */: // foo<x>;
23369                 case 57 /* QuestionToken */: // foo<x>?
23370                 case 34 /* EqualsEqualsToken */: // foo<x> ==
23371                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
23372                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
23373                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
23374                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
23375                 case 56 /* BarBarToken */: // foo<x> ||
23376                 case 60 /* QuestionQuestionToken */: // foo<x> ??
23377                 case 52 /* CaretToken */: // foo<x> ^
23378                 case 50 /* AmpersandToken */: // foo<x> &
23379                 case 51 /* BarToken */: // foo<x> |
23380                 case 19 /* CloseBraceToken */: // foo<x> }
23381                 case 1 /* EndOfFileToken */: // foo<x>
23382                     // these cases can't legally follow a type arg list.  However, they're not legal
23383                     // expressions either.  The user is probably in the middle of a generic type. So
23384                     // treat it as such.
23385                     return true;
23386                 case 27 /* CommaToken */: // foo<x>,
23387                 case 18 /* OpenBraceToken */: // foo<x> {
23388                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
23389                 // as an invocation expression.  Instead, we want to parse out the expression
23390                 // in isolation from the type arguments.
23391                 // falls through
23392                 default:
23393                     // Anything else treat as an expression.
23394                     return false;
23395             }
23396         }
23397         function parsePrimaryExpression() {
23398             switch (token()) {
23399                 case 8 /* NumericLiteral */:
23400                 case 9 /* BigIntLiteral */:
23401                 case 10 /* StringLiteral */:
23402                 case 14 /* NoSubstitutionTemplateLiteral */:
23403                     return parseLiteralNode();
23404                 case 104 /* ThisKeyword */:
23405                 case 102 /* SuperKeyword */:
23406                 case 100 /* NullKeyword */:
23407                 case 106 /* TrueKeyword */:
23408                 case 91 /* FalseKeyword */:
23409                     return parseTokenNode();
23410                 case 20 /* OpenParenToken */:
23411                     return parseParenthesizedExpression();
23412                 case 22 /* OpenBracketToken */:
23413                     return parseArrayLiteralExpression();
23414                 case 18 /* OpenBraceToken */:
23415                     return parseObjectLiteralExpression();
23416                 case 126 /* AsyncKeyword */:
23417                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
23418                     // If we encounter `async [no LineTerminator here] function` then this is an async
23419                     // function; otherwise, its an identifier.
23420                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
23421                         break;
23422                     }
23423                     return parseFunctionExpression();
23424                 case 80 /* ClassKeyword */:
23425                     return parseClassExpression();
23426                 case 94 /* FunctionKeyword */:
23427                     return parseFunctionExpression();
23428                 case 99 /* NewKeyword */:
23429                     return parseNewExpressionOrNewDotTarget();
23430                 case 43 /* SlashToken */:
23431                 case 67 /* SlashEqualsToken */:
23432                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
23433                         return parseLiteralNode();
23434                     }
23435                     break;
23436                 case 15 /* TemplateHead */:
23437                     return parseTemplateExpression(/* isTaggedTemplate */ false);
23438             }
23439             return parseIdentifier(ts.Diagnostics.Expression_expected);
23440         }
23441         function parseParenthesizedExpression() {
23442             var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
23443             parseExpected(20 /* OpenParenToken */);
23444             node.expression = allowInAnd(parseExpression);
23445             parseExpected(21 /* CloseParenToken */);
23446             return finishNode(node);
23447         }
23448         function parseSpreadElement() {
23449             var node = createNode(213 /* SpreadElement */);
23450             parseExpected(25 /* DotDotDotToken */);
23451             node.expression = parseAssignmentExpressionOrHigher();
23452             return finishNode(node);
23453         }
23454         function parseArgumentOrArrayLiteralElement() {
23455             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
23456                 token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
23457                     parseAssignmentExpressionOrHigher();
23458         }
23459         function parseArgumentExpression() {
23460             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
23461         }
23462         function parseArrayLiteralExpression() {
23463             var node = createNode(192 /* ArrayLiteralExpression */);
23464             parseExpected(22 /* OpenBracketToken */);
23465             if (scanner.hasPrecedingLineBreak()) {
23466                 node.multiLine = true;
23467             }
23468             node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
23469             parseExpected(23 /* CloseBracketToken */);
23470             return finishNode(node);
23471         }
23472         function parseObjectLiteralElement() {
23473             var node = createNodeWithJSDoc(0 /* Unknown */);
23474             if (parseOptionalToken(25 /* DotDotDotToken */)) {
23475                 node.kind = 283 /* SpreadAssignment */;
23476                 node.expression = parseAssignmentExpressionOrHigher();
23477                 return finishNode(node);
23478             }
23479             node.decorators = parseDecorators();
23480             node.modifiers = parseModifiers();
23481             if (parseContextualModifier(131 /* GetKeyword */)) {
23482                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
23483             }
23484             if (parseContextualModifier(142 /* SetKeyword */)) {
23485                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
23486             }
23487             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23488             var tokenIsIdentifier = isIdentifier();
23489             node.name = parsePropertyName();
23490             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
23491             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
23492             node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
23493             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
23494                 return parseMethodDeclaration(node, asteriskToken);
23495             }
23496             // check if it is short-hand property assignment or normal property assignment
23497             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
23498             // CoverInitializedName[Yield] :
23499             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
23500             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
23501             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
23502             if (isShorthandPropertyAssignment) {
23503                 node.kind = 282 /* ShorthandPropertyAssignment */;
23504                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
23505                 if (equalsToken) {
23506                     node.equalsToken = equalsToken;
23507                     node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
23508                 }
23509             }
23510             else {
23511                 node.kind = 281 /* PropertyAssignment */;
23512                 parseExpected(58 /* ColonToken */);
23513                 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
23514             }
23515             return finishNode(node);
23516         }
23517         function parseObjectLiteralExpression() {
23518             var node = createNode(193 /* ObjectLiteralExpression */);
23519             var openBracePosition = scanner.getTokenPos();
23520             parseExpected(18 /* OpenBraceToken */);
23521             if (scanner.hasPrecedingLineBreak()) {
23522                 node.multiLine = true;
23523             }
23524             node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
23525             if (!parseExpected(19 /* CloseBraceToken */)) {
23526                 var lastError = ts.lastOrUndefined(parseDiagnostics);
23527                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23528                     ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23529                 }
23530             }
23531             return finishNode(node);
23532         }
23533         function parseFunctionExpression() {
23534             // GeneratorExpression:
23535             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
23536             //
23537             // FunctionExpression:
23538             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
23539             var saveDecoratorContext = inDecoratorContext();
23540             if (saveDecoratorContext) {
23541                 setDecoratorContext(/*val*/ false);
23542             }
23543             var node = createNodeWithJSDoc(201 /* FunctionExpression */);
23544             node.modifiers = parseModifiers();
23545             parseExpected(94 /* FunctionKeyword */);
23546             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23547             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
23548             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
23549             node.name =
23550                 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
23551                     isGenerator ? doInYieldContext(parseOptionalIdentifier) :
23552                         isAsync ? doInAwaitContext(parseOptionalIdentifier) :
23553                             parseOptionalIdentifier();
23554             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
23555             node.body = parseFunctionBlock(isGenerator | isAsync);
23556             if (saveDecoratorContext) {
23557                 setDecoratorContext(/*val*/ true);
23558             }
23559             return finishNode(node);
23560         }
23561         function parseOptionalIdentifier() {
23562             return isIdentifier() ? parseIdentifier() : undefined;
23563         }
23564         function parseNewExpressionOrNewDotTarget() {
23565             var fullStart = scanner.getStartPos();
23566             parseExpected(99 /* NewKeyword */);
23567             if (parseOptional(24 /* DotToken */)) {
23568                 var node_2 = createNode(219 /* MetaProperty */, fullStart);
23569                 node_2.keywordToken = 99 /* NewKeyword */;
23570                 node_2.name = parseIdentifierName();
23571                 return finishNode(node_2);
23572             }
23573             var expression = parsePrimaryExpression();
23574             var typeArguments;
23575             while (true) {
23576                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
23577                 typeArguments = tryParse(parseTypeArgumentsInExpression);
23578                 if (isTemplateStartOfTaggedTemplate()) {
23579                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
23580                     expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
23581                     typeArguments = undefined;
23582                 }
23583                 break;
23584             }
23585             var node = createNode(197 /* NewExpression */, fullStart);
23586             node.expression = expression;
23587             node.typeArguments = typeArguments;
23588             if (token() === 20 /* OpenParenToken */) {
23589                 node.arguments = parseArgumentList();
23590             }
23591             else if (node.typeArguments) {
23592                 parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
23593             }
23594             return finishNode(node);
23595         }
23596         // STATEMENTS
23597         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
23598             var node = createNode(223 /* Block */);
23599             var openBracePosition = scanner.getTokenPos();
23600             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
23601                 if (scanner.hasPrecedingLineBreak()) {
23602                     node.multiLine = true;
23603                 }
23604                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
23605                 if (!parseExpected(19 /* CloseBraceToken */)) {
23606                     var lastError = ts.lastOrUndefined(parseDiagnostics);
23607                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23608                         ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23609                     }
23610                 }
23611             }
23612             else {
23613                 node.statements = createMissingList();
23614             }
23615             return finishNode(node);
23616         }
23617         function parseFunctionBlock(flags, diagnosticMessage) {
23618             var savedYieldContext = inYieldContext();
23619             setYieldContext(!!(flags & 1 /* Yield */));
23620             var savedAwaitContext = inAwaitContext();
23621             setAwaitContext(!!(flags & 2 /* Await */));
23622             // We may be in a [Decorator] context when parsing a function expression or
23623             // arrow function. The body of the function is not in [Decorator] context.
23624             var saveDecoratorContext = inDecoratorContext();
23625             if (saveDecoratorContext) {
23626                 setDecoratorContext(/*val*/ false);
23627             }
23628             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
23629             if (saveDecoratorContext) {
23630                 setDecoratorContext(/*val*/ true);
23631             }
23632             setYieldContext(savedYieldContext);
23633             setAwaitContext(savedAwaitContext);
23634             return block;
23635         }
23636         function parseEmptyStatement() {
23637             var node = createNode(224 /* EmptyStatement */);
23638             parseExpected(26 /* SemicolonToken */);
23639             return finishNode(node);
23640         }
23641         function parseIfStatement() {
23642             var node = createNode(227 /* IfStatement */);
23643             parseExpected(95 /* IfKeyword */);
23644             parseExpected(20 /* OpenParenToken */);
23645             node.expression = allowInAnd(parseExpression);
23646             parseExpected(21 /* CloseParenToken */);
23647             node.thenStatement = parseStatement();
23648             node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
23649             return finishNode(node);
23650         }
23651         function parseDoStatement() {
23652             var node = createNode(228 /* DoStatement */);
23653             parseExpected(86 /* DoKeyword */);
23654             node.statement = parseStatement();
23655             parseExpected(111 /* WhileKeyword */);
23656             parseExpected(20 /* OpenParenToken */);
23657             node.expression = allowInAnd(parseExpression);
23658             parseExpected(21 /* CloseParenToken */);
23659             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
23660             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
23661             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
23662             //  do;while(0)x will have a semicolon inserted before x.
23663             parseOptional(26 /* SemicolonToken */);
23664             return finishNode(node);
23665         }
23666         function parseWhileStatement() {
23667             var node = createNode(229 /* WhileStatement */);
23668             parseExpected(111 /* WhileKeyword */);
23669             parseExpected(20 /* OpenParenToken */);
23670             node.expression = allowInAnd(parseExpression);
23671             parseExpected(21 /* CloseParenToken */);
23672             node.statement = parseStatement();
23673             return finishNode(node);
23674         }
23675         function parseForOrForInOrForOfStatement() {
23676             var pos = getNodePos();
23677             parseExpected(93 /* ForKeyword */);
23678             var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
23679             parseExpected(20 /* OpenParenToken */);
23680             var initializer;
23681             if (token() !== 26 /* SemicolonToken */) {
23682                 if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
23683                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
23684                 }
23685                 else {
23686                     initializer = disallowInAnd(parseExpression);
23687                 }
23688             }
23689             var forOrForInOrForOfStatement;
23690             if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
23691                 var forOfStatement = createNode(232 /* ForOfStatement */, pos);
23692                 forOfStatement.awaitModifier = awaitToken;
23693                 forOfStatement.initializer = initializer;
23694                 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
23695                 parseExpected(21 /* CloseParenToken */);
23696                 forOrForInOrForOfStatement = forOfStatement;
23697             }
23698             else if (parseOptional(97 /* InKeyword */)) {
23699                 var forInStatement = createNode(231 /* ForInStatement */, pos);
23700                 forInStatement.initializer = initializer;
23701                 forInStatement.expression = allowInAnd(parseExpression);
23702                 parseExpected(21 /* CloseParenToken */);
23703                 forOrForInOrForOfStatement = forInStatement;
23704             }
23705             else {
23706                 var forStatement = createNode(230 /* ForStatement */, pos);
23707                 forStatement.initializer = initializer;
23708                 parseExpected(26 /* SemicolonToken */);
23709                 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
23710                     forStatement.condition = allowInAnd(parseExpression);
23711                 }
23712                 parseExpected(26 /* SemicolonToken */);
23713                 if (token() !== 21 /* CloseParenToken */) {
23714                     forStatement.incrementor = allowInAnd(parseExpression);
23715                 }
23716                 parseExpected(21 /* CloseParenToken */);
23717                 forOrForInOrForOfStatement = forStatement;
23718             }
23719             forOrForInOrForOfStatement.statement = parseStatement();
23720             return finishNode(forOrForInOrForOfStatement);
23721         }
23722         function parseBreakOrContinueStatement(kind) {
23723             var node = createNode(kind);
23724             parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
23725             if (!canParseSemicolon()) {
23726                 node.label = parseIdentifier();
23727             }
23728             parseSemicolon();
23729             return finishNode(node);
23730         }
23731         function parseReturnStatement() {
23732             var node = createNode(235 /* ReturnStatement */);
23733             parseExpected(101 /* ReturnKeyword */);
23734             if (!canParseSemicolon()) {
23735                 node.expression = allowInAnd(parseExpression);
23736             }
23737             parseSemicolon();
23738             return finishNode(node);
23739         }
23740         function parseWithStatement() {
23741             var node = createNode(236 /* WithStatement */);
23742             parseExpected(112 /* WithKeyword */);
23743             parseExpected(20 /* OpenParenToken */);
23744             node.expression = allowInAnd(parseExpression);
23745             parseExpected(21 /* CloseParenToken */);
23746             node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
23747             return finishNode(node);
23748         }
23749         function parseCaseClause() {
23750             var node = createNode(277 /* CaseClause */);
23751             parseExpected(78 /* CaseKeyword */);
23752             node.expression = allowInAnd(parseExpression);
23753             parseExpected(58 /* ColonToken */);
23754             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23755             return finishNode(node);
23756         }
23757         function parseDefaultClause() {
23758             var node = createNode(278 /* DefaultClause */);
23759             parseExpected(84 /* DefaultKeyword */);
23760             parseExpected(58 /* ColonToken */);
23761             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23762             return finishNode(node);
23763         }
23764         function parseCaseOrDefaultClause() {
23765             return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
23766         }
23767         function parseSwitchStatement() {
23768             var node = createNode(237 /* SwitchStatement */);
23769             parseExpected(103 /* SwitchKeyword */);
23770             parseExpected(20 /* OpenParenToken */);
23771             node.expression = allowInAnd(parseExpression);
23772             parseExpected(21 /* CloseParenToken */);
23773             var caseBlock = createNode(251 /* CaseBlock */);
23774             parseExpected(18 /* OpenBraceToken */);
23775             caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
23776             parseExpected(19 /* CloseBraceToken */);
23777             node.caseBlock = finishNode(caseBlock);
23778             return finishNode(node);
23779         }
23780         function parseThrowStatement() {
23781             // ThrowStatement[Yield] :
23782             //      throw [no LineTerminator here]Expression[In, ?Yield];
23783             // Because of automatic semicolon insertion, we need to report error if this
23784             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
23785             // directly as that might consume an expression on the following line.
23786             // We just return 'undefined' in that case.  The actual error will be reported in the
23787             // grammar walker.
23788             var node = createNode(239 /* ThrowStatement */);
23789             parseExpected(105 /* ThrowKeyword */);
23790             node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
23791             parseSemicolon();
23792             return finishNode(node);
23793         }
23794         // TODO: Review for error recovery
23795         function parseTryStatement() {
23796             var node = createNode(240 /* TryStatement */);
23797             parseExpected(107 /* TryKeyword */);
23798             node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23799             node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
23800             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
23801             // one out no matter what.
23802             if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
23803                 parseExpected(92 /* FinallyKeyword */);
23804                 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23805             }
23806             return finishNode(node);
23807         }
23808         function parseCatchClause() {
23809             var result = createNode(280 /* CatchClause */);
23810             parseExpected(79 /* CatchKeyword */);
23811             if (parseOptional(20 /* OpenParenToken */)) {
23812                 result.variableDeclaration = parseVariableDeclaration();
23813                 parseExpected(21 /* CloseParenToken */);
23814             }
23815             else {
23816                 // Keep shape of node to avoid degrading performance.
23817                 result.variableDeclaration = undefined;
23818             }
23819             result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
23820             return finishNode(result);
23821         }
23822         function parseDebuggerStatement() {
23823             var node = createNode(241 /* DebuggerStatement */);
23824             parseExpected(83 /* DebuggerKeyword */);
23825             parseSemicolon();
23826             return finishNode(node);
23827         }
23828         function parseExpressionOrLabeledStatement() {
23829             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
23830             // out an expression, seeing if it is identifier and then seeing if it is followed by
23831             // a colon.
23832             var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
23833             var expression = allowInAnd(parseExpression);
23834             if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
23835                 node.kind = 238 /* LabeledStatement */;
23836                 node.label = expression;
23837                 node.statement = parseStatement();
23838             }
23839             else {
23840                 node.kind = 226 /* ExpressionStatement */;
23841                 node.expression = expression;
23842                 parseSemicolon();
23843             }
23844             return finishNode(node);
23845         }
23846         function nextTokenIsIdentifierOrKeywordOnSameLine() {
23847             nextToken();
23848             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
23849         }
23850         function nextTokenIsClassKeywordOnSameLine() {
23851             nextToken();
23852             return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
23853         }
23854         function nextTokenIsFunctionKeywordOnSameLine() {
23855             nextToken();
23856             return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
23857         }
23858         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
23859             nextToken();
23860             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
23861         }
23862         function isDeclaration() {
23863             while (true) {
23864                 switch (token()) {
23865                     case 109 /* VarKeyword */:
23866                     case 115 /* LetKeyword */:
23867                     case 81 /* ConstKeyword */:
23868                     case 94 /* FunctionKeyword */:
23869                     case 80 /* ClassKeyword */:
23870                     case 88 /* EnumKeyword */:
23871                         return true;
23872                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
23873                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
23874                     // count on to parse out the respective declarations. For instance, we exploit this to say that
23875                     //
23876                     //    namespace n
23877                     //
23878                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
23879                     //
23880                     //    namespace
23881                     //    n
23882                     //
23883                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
23884                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
23885                     //
23886                     // *Note*: 'interface' is actually a strict mode reserved word. So while
23887                     //
23888                     //   "use strict"
23889                     //   interface
23890                     //   I {}
23891                     //
23892                     // could be legal, it would add complexity for very little gain.
23893                     case 114 /* InterfaceKeyword */:
23894                     case 145 /* TypeKeyword */:
23895                         return nextTokenIsIdentifierOnSameLine();
23896                     case 135 /* ModuleKeyword */:
23897                     case 136 /* NamespaceKeyword */:
23898                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
23899                     case 122 /* AbstractKeyword */:
23900                     case 126 /* AsyncKeyword */:
23901                     case 130 /* DeclareKeyword */:
23902                     case 117 /* PrivateKeyword */:
23903                     case 118 /* ProtectedKeyword */:
23904                     case 119 /* PublicKeyword */:
23905                     case 138 /* ReadonlyKeyword */:
23906                         nextToken();
23907                         // ASI takes effect for this modifier.
23908                         if (scanner.hasPrecedingLineBreak()) {
23909                             return false;
23910                         }
23911                         continue;
23912                     case 150 /* GlobalKeyword */:
23913                         nextToken();
23914                         return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
23915                     case 96 /* ImportKeyword */:
23916                         nextToken();
23917                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
23918                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
23919                     case 89 /* ExportKeyword */:
23920                         var currentToken_1 = nextToken();
23921                         if (currentToken_1 === 145 /* TypeKeyword */) {
23922                             currentToken_1 = lookAhead(nextToken);
23923                         }
23924                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
23925                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
23926                             currentToken_1 === 123 /* AsKeyword */) {
23927                             return true;
23928                         }
23929                         continue;
23930                     case 120 /* StaticKeyword */:
23931                         nextToken();
23932                         continue;
23933                     default:
23934                         return false;
23935                 }
23936             }
23937         }
23938         function isStartOfDeclaration() {
23939             return lookAhead(isDeclaration);
23940         }
23941         function isStartOfStatement() {
23942             switch (token()) {
23943                 case 59 /* AtToken */:
23944                 case 26 /* SemicolonToken */:
23945                 case 18 /* OpenBraceToken */:
23946                 case 109 /* VarKeyword */:
23947                 case 115 /* LetKeyword */:
23948                 case 94 /* FunctionKeyword */:
23949                 case 80 /* ClassKeyword */:
23950                 case 88 /* EnumKeyword */:
23951                 case 95 /* IfKeyword */:
23952                 case 86 /* DoKeyword */:
23953                 case 111 /* WhileKeyword */:
23954                 case 93 /* ForKeyword */:
23955                 case 82 /* ContinueKeyword */:
23956                 case 77 /* BreakKeyword */:
23957                 case 101 /* ReturnKeyword */:
23958                 case 112 /* WithKeyword */:
23959                 case 103 /* SwitchKeyword */:
23960                 case 105 /* ThrowKeyword */:
23961                 case 107 /* TryKeyword */:
23962                 case 83 /* DebuggerKeyword */:
23963                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
23964                 // however, we say they are here so that we may gracefully parse them and error later.
23965                 // falls through
23966                 case 79 /* CatchKeyword */:
23967                 case 92 /* FinallyKeyword */:
23968                     return true;
23969                 case 96 /* ImportKeyword */:
23970                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
23971                 case 81 /* ConstKeyword */:
23972                 case 89 /* ExportKeyword */:
23973                     return isStartOfDeclaration();
23974                 case 126 /* AsyncKeyword */:
23975                 case 130 /* DeclareKeyword */:
23976                 case 114 /* InterfaceKeyword */:
23977                 case 135 /* ModuleKeyword */:
23978                 case 136 /* NamespaceKeyword */:
23979                 case 145 /* TypeKeyword */:
23980                 case 150 /* GlobalKeyword */:
23981                     // When these don't start a declaration, they're an identifier in an expression statement
23982                     return true;
23983                 case 119 /* PublicKeyword */:
23984                 case 117 /* PrivateKeyword */:
23985                 case 118 /* ProtectedKeyword */:
23986                 case 120 /* StaticKeyword */:
23987                 case 138 /* ReadonlyKeyword */:
23988                     // When these don't start a declaration, they may be the start of a class member if an identifier
23989                     // immediately follows. Otherwise they're an identifier in an expression statement.
23990                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
23991                 default:
23992                     return isStartOfExpression();
23993             }
23994         }
23995         function nextTokenIsIdentifierOrStartOfDestructuring() {
23996             nextToken();
23997             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
23998         }
23999         function isLetDeclaration() {
24000             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
24001             // or [.
24002             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
24003         }
24004         function parseStatement() {
24005             switch (token()) {
24006                 case 26 /* SemicolonToken */:
24007                     return parseEmptyStatement();
24008                 case 18 /* OpenBraceToken */:
24009                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
24010                 case 109 /* VarKeyword */:
24011                     return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
24012                 case 115 /* LetKeyword */:
24013                     if (isLetDeclaration()) {
24014                         return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
24015                     }
24016                     break;
24017                 case 94 /* FunctionKeyword */:
24018                     return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
24019                 case 80 /* ClassKeyword */:
24020                     return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
24021                 case 95 /* IfKeyword */:
24022                     return parseIfStatement();
24023                 case 86 /* DoKeyword */:
24024                     return parseDoStatement();
24025                 case 111 /* WhileKeyword */:
24026                     return parseWhileStatement();
24027                 case 93 /* ForKeyword */:
24028                     return parseForOrForInOrForOfStatement();
24029                 case 82 /* ContinueKeyword */:
24030                     return parseBreakOrContinueStatement(233 /* ContinueStatement */);
24031                 case 77 /* BreakKeyword */:
24032                     return parseBreakOrContinueStatement(234 /* BreakStatement */);
24033                 case 101 /* ReturnKeyword */:
24034                     return parseReturnStatement();
24035                 case 112 /* WithKeyword */:
24036                     return parseWithStatement();
24037                 case 103 /* SwitchKeyword */:
24038                     return parseSwitchStatement();
24039                 case 105 /* ThrowKeyword */:
24040                     return parseThrowStatement();
24041                 case 107 /* TryKeyword */:
24042                 // Include 'catch' and 'finally' for error recovery.
24043                 // falls through
24044                 case 79 /* CatchKeyword */:
24045                 case 92 /* FinallyKeyword */:
24046                     return parseTryStatement();
24047                 case 83 /* DebuggerKeyword */:
24048                     return parseDebuggerStatement();
24049                 case 59 /* AtToken */:
24050                     return parseDeclaration();
24051                 case 126 /* AsyncKeyword */:
24052                 case 114 /* InterfaceKeyword */:
24053                 case 145 /* TypeKeyword */:
24054                 case 135 /* ModuleKeyword */:
24055                 case 136 /* NamespaceKeyword */:
24056                 case 130 /* DeclareKeyword */:
24057                 case 81 /* ConstKeyword */:
24058                 case 88 /* EnumKeyword */:
24059                 case 89 /* ExportKeyword */:
24060                 case 96 /* ImportKeyword */:
24061                 case 117 /* PrivateKeyword */:
24062                 case 118 /* ProtectedKeyword */:
24063                 case 119 /* PublicKeyword */:
24064                 case 122 /* AbstractKeyword */:
24065                 case 120 /* StaticKeyword */:
24066                 case 138 /* ReadonlyKeyword */:
24067                 case 150 /* GlobalKeyword */:
24068                     if (isStartOfDeclaration()) {
24069                         return parseDeclaration();
24070                     }
24071                     break;
24072             }
24073             return parseExpressionOrLabeledStatement();
24074         }
24075         function isDeclareModifier(modifier) {
24076             return modifier.kind === 130 /* DeclareKeyword */;
24077         }
24078         function parseDeclaration() {
24079             var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
24080             // `parseListElement` attempted to get the reused node at this position,
24081             // but the ambient context flag was not yet set, so the node appeared
24082             // not reusable in that context.
24083             var isAmbient = ts.some(modifiers, isDeclareModifier);
24084             if (isAmbient) {
24085                 var node_3 = tryReuseAmbientDeclaration();
24086                 if (node_3) {
24087                     return node_3;
24088                 }
24089             }
24090             var node = createNodeWithJSDoc(0 /* Unknown */);
24091             node.decorators = parseDecorators();
24092             node.modifiers = parseModifiers();
24093             if (isAmbient) {
24094                 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24095                     var m = _a[_i];
24096                     m.flags |= 8388608 /* Ambient */;
24097                 }
24098                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
24099             }
24100             else {
24101                 return parseDeclarationWorker(node);
24102             }
24103         }
24104         function tryReuseAmbientDeclaration() {
24105             return doInsideOfContext(8388608 /* Ambient */, function () {
24106                 var node = currentNode(parsingContext);
24107                 if (node) {
24108                     return consumeNode(node);
24109                 }
24110             });
24111         }
24112         function parseDeclarationWorker(node) {
24113             switch (token()) {
24114                 case 109 /* VarKeyword */:
24115                 case 115 /* LetKeyword */:
24116                 case 81 /* ConstKeyword */:
24117                     return parseVariableStatement(node);
24118                 case 94 /* FunctionKeyword */:
24119                     return parseFunctionDeclaration(node);
24120                 case 80 /* ClassKeyword */:
24121                     return parseClassDeclaration(node);
24122                 case 114 /* InterfaceKeyword */:
24123                     return parseInterfaceDeclaration(node);
24124                 case 145 /* TypeKeyword */:
24125                     return parseTypeAliasDeclaration(node);
24126                 case 88 /* EnumKeyword */:
24127                     return parseEnumDeclaration(node);
24128                 case 150 /* GlobalKeyword */:
24129                 case 135 /* ModuleKeyword */:
24130                 case 136 /* NamespaceKeyword */:
24131                     return parseModuleDeclaration(node);
24132                 case 96 /* ImportKeyword */:
24133                     return parseImportDeclarationOrImportEqualsDeclaration(node);
24134                 case 89 /* ExportKeyword */:
24135                     nextToken();
24136                     switch (token()) {
24137                         case 84 /* DefaultKeyword */:
24138                         case 62 /* EqualsToken */:
24139                             return parseExportAssignment(node);
24140                         case 123 /* AsKeyword */:
24141                             return parseNamespaceExportDeclaration(node);
24142                         default:
24143                             return parseExportDeclaration(node);
24144                     }
24145                 default:
24146                     if (node.decorators || node.modifiers) {
24147                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
24148                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
24149                         var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24150                         missing.pos = node.pos;
24151                         missing.decorators = node.decorators;
24152                         missing.modifiers = node.modifiers;
24153                         return finishNode(missing);
24154                     }
24155                     return undefined; // TODO: GH#18217
24156             }
24157         }
24158         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
24159             nextToken();
24160             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
24161         }
24162         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
24163             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
24164                 parseSemicolon();
24165                 return;
24166             }
24167             return parseFunctionBlock(flags, diagnosticMessage);
24168         }
24169         // DECLARATIONS
24170         function parseArrayBindingElement() {
24171             if (token() === 27 /* CommaToken */) {
24172                 return createNode(215 /* OmittedExpression */);
24173             }
24174             var node = createNode(191 /* BindingElement */);
24175             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24176             node.name = parseIdentifierOrPattern();
24177             node.initializer = parseInitializer();
24178             return finishNode(node);
24179         }
24180         function parseObjectBindingElement() {
24181             var node = createNode(191 /* BindingElement */);
24182             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24183             var tokenIsIdentifier = isIdentifier();
24184             var propertyName = parsePropertyName();
24185             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
24186                 node.name = propertyName;
24187             }
24188             else {
24189                 parseExpected(58 /* ColonToken */);
24190                 node.propertyName = propertyName;
24191                 node.name = parseIdentifierOrPattern();
24192             }
24193             node.initializer = parseInitializer();
24194             return finishNode(node);
24195         }
24196         function parseObjectBindingPattern() {
24197             var node = createNode(189 /* ObjectBindingPattern */);
24198             parseExpected(18 /* OpenBraceToken */);
24199             node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
24200             parseExpected(19 /* CloseBraceToken */);
24201             return finishNode(node);
24202         }
24203         function parseArrayBindingPattern() {
24204             var node = createNode(190 /* ArrayBindingPattern */);
24205             parseExpected(22 /* OpenBracketToken */);
24206             node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
24207             parseExpected(23 /* CloseBracketToken */);
24208             return finishNode(node);
24209         }
24210         function isIdentifierOrPrivateIdentifierOrPattern() {
24211             return token() === 18 /* OpenBraceToken */
24212                 || token() === 22 /* OpenBracketToken */
24213                 || token() === 76 /* PrivateIdentifier */
24214                 || isIdentifier();
24215         }
24216         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
24217             if (token() === 22 /* OpenBracketToken */) {
24218                 return parseArrayBindingPattern();
24219             }
24220             if (token() === 18 /* OpenBraceToken */) {
24221                 return parseObjectBindingPattern();
24222             }
24223             return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
24224         }
24225         function parseVariableDeclarationAllowExclamation() {
24226             return parseVariableDeclaration(/*allowExclamation*/ true);
24227         }
24228         function parseVariableDeclaration(allowExclamation) {
24229             var node = createNode(242 /* VariableDeclaration */);
24230             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
24231             if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
24232                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24233                 node.exclamationToken = parseTokenNode();
24234             }
24235             node.type = parseTypeAnnotation();
24236             if (!isInOrOfKeyword(token())) {
24237                 node.initializer = parseInitializer();
24238             }
24239             return finishNode(node);
24240         }
24241         function parseVariableDeclarationList(inForStatementInitializer) {
24242             var node = createNode(243 /* VariableDeclarationList */);
24243             switch (token()) {
24244                 case 109 /* VarKeyword */:
24245                     break;
24246                 case 115 /* LetKeyword */:
24247                     node.flags |= 1 /* Let */;
24248                     break;
24249                 case 81 /* ConstKeyword */:
24250                     node.flags |= 2 /* Const */;
24251                     break;
24252                 default:
24253                     ts.Debug.fail();
24254             }
24255             nextToken();
24256             // The user may have written the following:
24257             //
24258             //    for (let of X) { }
24259             //
24260             // In this case, we want to parse an empty declaration list, and then parse 'of'
24261             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
24262             // So we need to look ahead to determine if 'of' should be treated as a keyword in
24263             // this context.
24264             // The checker will then give an error that there is an empty declaration list.
24265             if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
24266                 node.declarations = createMissingList();
24267             }
24268             else {
24269                 var savedDisallowIn = inDisallowInContext();
24270                 setDisallowInContext(inForStatementInitializer);
24271                 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
24272                 setDisallowInContext(savedDisallowIn);
24273             }
24274             return finishNode(node);
24275         }
24276         function canFollowContextualOfKeyword() {
24277             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
24278         }
24279         function parseVariableStatement(node) {
24280             node.kind = 225 /* VariableStatement */;
24281             node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
24282             parseSemicolon();
24283             return finishNode(node);
24284         }
24285         function parseFunctionDeclaration(node) {
24286             node.kind = 244 /* FunctionDeclaration */;
24287             parseExpected(94 /* FunctionKeyword */);
24288             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24289             node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
24290             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
24291             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24292             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24293             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
24294             return finishNode(node);
24295         }
24296         function parseConstructorName() {
24297             if (token() === 129 /* ConstructorKeyword */) {
24298                 return parseExpected(129 /* ConstructorKeyword */);
24299             }
24300             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
24301                 return tryParse(function () {
24302                     var literalNode = parseLiteralNode();
24303                     return literalNode.text === "constructor" ? literalNode : undefined;
24304                 });
24305             }
24306         }
24307         function tryParseConstructorDeclaration(node) {
24308             return tryParse(function () {
24309                 if (parseConstructorName()) {
24310                     node.kind = 162 /* Constructor */;
24311                     fillSignature(58 /* ColonToken */, 0 /* None */, node);
24312                     node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
24313                     return finishNode(node);
24314                 }
24315             });
24316         }
24317         function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
24318             node.kind = 161 /* MethodDeclaration */;
24319             node.asteriskToken = asteriskToken;
24320             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
24321             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24322             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24323             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
24324             return finishNode(node);
24325         }
24326         function parsePropertyDeclaration(node) {
24327             node.kind = 159 /* PropertyDeclaration */;
24328             if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24329                 node.exclamationToken = parseTokenNode();
24330             }
24331             node.type = parseTypeAnnotation();
24332             node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
24333             parseSemicolon();
24334             return finishNode(node);
24335         }
24336         function parsePropertyOrMethodDeclaration(node) {
24337             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24338             node.name = parsePropertyName();
24339             // Note: this is not legal as per the grammar.  But we allow it in the parser and
24340             // report an error in the grammar checker.
24341             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
24342             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
24343                 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
24344             }
24345             return parsePropertyDeclaration(node);
24346         }
24347         function parseAccessorDeclaration(node, kind) {
24348             node.kind = kind;
24349             node.name = parsePropertyName();
24350             fillSignature(58 /* ColonToken */, 0 /* None */, node);
24351             node.body = parseFunctionBlockOrSemicolon(0 /* None */);
24352             return finishNode(node);
24353         }
24354         function isClassMemberStart() {
24355             var idToken;
24356             if (token() === 59 /* AtToken */) {
24357                 return true;
24358             }
24359             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
24360             while (ts.isModifierKind(token())) {
24361                 idToken = token();
24362                 // If the idToken is a class modifier (protected, private, public, and static), it is
24363                 // certain that we are starting to parse class member. This allows better error recovery
24364                 // Example:
24365                 //      public foo() ...     // true
24366                 //      public @dec blah ... // true; we will then report an error later
24367                 //      export public ...    // true; we will then report an error later
24368                 if (ts.isClassMemberModifier(idToken)) {
24369                     return true;
24370                 }
24371                 nextToken();
24372             }
24373             if (token() === 41 /* AsteriskToken */) {
24374                 return true;
24375             }
24376             // Try to get the first property-like token following all modifiers.
24377             // This can either be an identifier or the 'get' or 'set' keywords.
24378             if (isLiteralPropertyName()) {
24379                 idToken = token();
24380                 nextToken();
24381             }
24382             // Index signatures and computed properties are class members; we can parse.
24383             if (token() === 22 /* OpenBracketToken */) {
24384                 return true;
24385             }
24386             // If we were able to get any potential identifier...
24387             if (idToken !== undefined) {
24388                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
24389                 if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
24390                     return true;
24391                 }
24392                 // If it *is* a keyword, but not an accessor, check a little farther along
24393                 // to see if it should actually be parsed as a class member.
24394                 switch (token()) {
24395                     case 20 /* OpenParenToken */: // Method declaration
24396                     case 29 /* LessThanToken */: // Generic Method declaration
24397                     case 53 /* ExclamationToken */: // Non-null assertion on property name
24398                     case 58 /* ColonToken */: // Type Annotation for declaration
24399                     case 62 /* EqualsToken */: // Initializer for declaration
24400                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
24401                         return true;
24402                     default:
24403                         // Covers
24404                         //  - Semicolons     (declaration termination)
24405                         //  - Closing braces (end-of-class, must be declaration)
24406                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
24407                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
24408                         return canParseSemicolon();
24409                 }
24410             }
24411             return false;
24412         }
24413         function parseDecorators() {
24414             var list;
24415             var listPos = getNodePos();
24416             while (true) {
24417                 var decoratorStart = getNodePos();
24418                 if (!parseOptional(59 /* AtToken */)) {
24419                     break;
24420                 }
24421                 var decorator = createNode(157 /* Decorator */, decoratorStart);
24422                 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
24423                 finishNode(decorator);
24424                 (list || (list = [])).push(decorator);
24425             }
24426             return list && createNodeArray(list, listPos);
24427         }
24428         /*
24429          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
24430          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
24431          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
24432          *
24433          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
24434          */
24435         function parseModifiers(permitInvalidConstAsModifier) {
24436             var list;
24437             var listPos = getNodePos();
24438             while (true) {
24439                 var modifierStart = scanner.getStartPos();
24440                 var modifierKind = token();
24441                 if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
24442                     // We need to ensure that any subsequent modifiers appear on the same line
24443                     // so that when 'const' is a standalone declaration, we don't issue an error.
24444                     if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
24445                         break;
24446                     }
24447                 }
24448                 else {
24449                     if (!parseAnyContextualModifier()) {
24450                         break;
24451                     }
24452                 }
24453                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24454                 (list || (list = [])).push(modifier);
24455             }
24456             return list && createNodeArray(list, listPos);
24457         }
24458         function parseModifiersForArrowFunction() {
24459             var modifiers;
24460             if (token() === 126 /* AsyncKeyword */) {
24461                 var modifierStart = scanner.getStartPos();
24462                 var modifierKind = token();
24463                 nextToken();
24464                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24465                 modifiers = createNodeArray([modifier], modifierStart);
24466             }
24467             return modifiers;
24468         }
24469         function parseClassElement() {
24470             if (token() === 26 /* SemicolonToken */) {
24471                 var result = createNode(222 /* SemicolonClassElement */);
24472                 nextToken();
24473                 return finishNode(result);
24474             }
24475             var node = createNodeWithJSDoc(0 /* Unknown */);
24476             node.decorators = parseDecorators();
24477             node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
24478             if (parseContextualModifier(131 /* GetKeyword */)) {
24479                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
24480             }
24481             if (parseContextualModifier(142 /* SetKeyword */)) {
24482                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
24483             }
24484             if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
24485                 var constructorDeclaration = tryParseConstructorDeclaration(node);
24486                 if (constructorDeclaration) {
24487                     return constructorDeclaration;
24488                 }
24489             }
24490             if (isIndexSignature()) {
24491                 return parseIndexSignatureDeclaration(node);
24492             }
24493             // It is very important that we check this *after* checking indexers because
24494             // the [ token can start an index signature or a computed property name
24495             if (ts.tokenIsIdentifierOrKeyword(token()) ||
24496                 token() === 10 /* StringLiteral */ ||
24497                 token() === 8 /* NumericLiteral */ ||
24498                 token() === 41 /* AsteriskToken */ ||
24499                 token() === 22 /* OpenBracketToken */) {
24500                 var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
24501                 if (isAmbient) {
24502                     for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24503                         var m = _a[_i];
24504                         m.flags |= 8388608 /* Ambient */;
24505                     }
24506                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
24507                 }
24508                 else {
24509                     return parsePropertyOrMethodDeclaration(node);
24510                 }
24511             }
24512             if (node.decorators || node.modifiers) {
24513                 // treat this as a property declaration with a missing name.
24514                 node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24515                 return parsePropertyDeclaration(node);
24516             }
24517             // 'isClassMemberStart' should have hinted not to attempt parsing.
24518             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
24519         }
24520         function parseClassExpression() {
24521             return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
24522         }
24523         function parseClassDeclaration(node) {
24524             return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
24525         }
24526         function parseClassDeclarationOrExpression(node, kind) {
24527             node.kind = kind;
24528             parseExpected(80 /* ClassKeyword */);
24529             node.name = parseNameOfClassDeclarationOrExpression();
24530             node.typeParameters = parseTypeParameters();
24531             node.heritageClauses = parseHeritageClauses();
24532             if (parseExpected(18 /* OpenBraceToken */)) {
24533                 // ClassTail[Yield,Await] : (Modified) See 14.5
24534                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24535                 node.members = parseClassMembers();
24536                 parseExpected(19 /* CloseBraceToken */);
24537             }
24538             else {
24539                 node.members = createMissingList();
24540             }
24541             return finishNode(node);
24542         }
24543         function parseNameOfClassDeclarationOrExpression() {
24544             // implements is a future reserved word so
24545             // 'class implements' might mean either
24546             // - class expression with omitted name, 'implements' starts heritage clause
24547             // - class with name 'implements'
24548             // 'isImplementsClause' helps to disambiguate between these two cases
24549             return isIdentifier() && !isImplementsClause()
24550                 ? parseIdentifier()
24551                 : undefined;
24552         }
24553         function isImplementsClause() {
24554             return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
24555         }
24556         function parseHeritageClauses() {
24557             // ClassTail[Yield,Await] : (Modified) See 14.5
24558             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24559             if (isHeritageClause()) {
24560                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
24561             }
24562             return undefined;
24563         }
24564         function parseHeritageClause() {
24565             var tok = token();
24566             ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
24567             var node = createNode(279 /* HeritageClause */);
24568             node.token = tok;
24569             nextToken();
24570             node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
24571             return finishNode(node);
24572         }
24573         function parseExpressionWithTypeArguments() {
24574             var node = createNode(216 /* ExpressionWithTypeArguments */);
24575             node.expression = parseLeftHandSideExpressionOrHigher();
24576             node.typeArguments = tryParseTypeArguments();
24577             return finishNode(node);
24578         }
24579         function tryParseTypeArguments() {
24580             return token() === 29 /* LessThanToken */ ?
24581                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
24582         }
24583         function isHeritageClause() {
24584             return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
24585         }
24586         function parseClassMembers() {
24587             return parseList(5 /* ClassMembers */, parseClassElement);
24588         }
24589         function parseInterfaceDeclaration(node) {
24590             node.kind = 246 /* InterfaceDeclaration */;
24591             parseExpected(114 /* InterfaceKeyword */);
24592             node.name = parseIdentifier();
24593             node.typeParameters = parseTypeParameters();
24594             node.heritageClauses = parseHeritageClauses();
24595             node.members = parseObjectTypeMembers();
24596             return finishNode(node);
24597         }
24598         function parseTypeAliasDeclaration(node) {
24599             node.kind = 247 /* TypeAliasDeclaration */;
24600             parseExpected(145 /* TypeKeyword */);
24601             node.name = parseIdentifier();
24602             node.typeParameters = parseTypeParameters();
24603             parseExpected(62 /* EqualsToken */);
24604             node.type = parseType();
24605             parseSemicolon();
24606             return finishNode(node);
24607         }
24608         // In an ambient declaration, the grammar only allows integer literals as initializers.
24609         // In a non-ambient declaration, the grammar allows uninitialized members only in a
24610         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
24611         // or any time an integer literal initializer is encountered.
24612         function parseEnumMember() {
24613             var node = createNodeWithJSDoc(284 /* EnumMember */);
24614             node.name = parsePropertyName();
24615             node.initializer = allowInAnd(parseInitializer);
24616             return finishNode(node);
24617         }
24618         function parseEnumDeclaration(node) {
24619             node.kind = 248 /* EnumDeclaration */;
24620             parseExpected(88 /* EnumKeyword */);
24621             node.name = parseIdentifier();
24622             if (parseExpected(18 /* OpenBraceToken */)) {
24623                 node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
24624                 parseExpected(19 /* CloseBraceToken */);
24625             }
24626             else {
24627                 node.members = createMissingList();
24628             }
24629             return finishNode(node);
24630         }
24631         function parseModuleBlock() {
24632             var node = createNode(250 /* ModuleBlock */);
24633             if (parseExpected(18 /* OpenBraceToken */)) {
24634                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
24635                 parseExpected(19 /* CloseBraceToken */);
24636             }
24637             else {
24638                 node.statements = createMissingList();
24639             }
24640             return finishNode(node);
24641         }
24642         function parseModuleOrNamespaceDeclaration(node, flags) {
24643             node.kind = 249 /* ModuleDeclaration */;
24644             // If we are parsing a dotted namespace name, we want to
24645             // propagate the 'Namespace' flag across the names if set.
24646             var namespaceFlag = flags & 16 /* Namespace */;
24647             node.flags |= flags;
24648             node.name = parseIdentifier();
24649             node.body = parseOptional(24 /* DotToken */)
24650                 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
24651                 : parseModuleBlock();
24652             return finishNode(node);
24653         }
24654         function parseAmbientExternalModuleDeclaration(node) {
24655             node.kind = 249 /* ModuleDeclaration */;
24656             if (token() === 150 /* GlobalKeyword */) {
24657                 // parse 'global' as name of global scope augmentation
24658                 node.name = parseIdentifier();
24659                 node.flags |= 1024 /* GlobalAugmentation */;
24660             }
24661             else {
24662                 node.name = parseLiteralNode();
24663                 node.name.text = internIdentifier(node.name.text);
24664             }
24665             if (token() === 18 /* OpenBraceToken */) {
24666                 node.body = parseModuleBlock();
24667             }
24668             else {
24669                 parseSemicolon();
24670             }
24671             return finishNode(node);
24672         }
24673         function parseModuleDeclaration(node) {
24674             var flags = 0;
24675             if (token() === 150 /* GlobalKeyword */) {
24676                 // global augmentation
24677                 return parseAmbientExternalModuleDeclaration(node);
24678             }
24679             else if (parseOptional(136 /* NamespaceKeyword */)) {
24680                 flags |= 16 /* Namespace */;
24681             }
24682             else {
24683                 parseExpected(135 /* ModuleKeyword */);
24684                 if (token() === 10 /* StringLiteral */) {
24685                     return parseAmbientExternalModuleDeclaration(node);
24686                 }
24687             }
24688             return parseModuleOrNamespaceDeclaration(node, flags);
24689         }
24690         function isExternalModuleReference() {
24691             return token() === 139 /* RequireKeyword */ &&
24692                 lookAhead(nextTokenIsOpenParen);
24693         }
24694         function nextTokenIsOpenParen() {
24695             return nextToken() === 20 /* OpenParenToken */;
24696         }
24697         function nextTokenIsSlash() {
24698             return nextToken() === 43 /* SlashToken */;
24699         }
24700         function parseNamespaceExportDeclaration(node) {
24701             node.kind = 252 /* NamespaceExportDeclaration */;
24702             parseExpected(123 /* AsKeyword */);
24703             parseExpected(136 /* NamespaceKeyword */);
24704             node.name = parseIdentifier();
24705             parseSemicolon();
24706             return finishNode(node);
24707         }
24708         function parseImportDeclarationOrImportEqualsDeclaration(node) {
24709             parseExpected(96 /* ImportKeyword */);
24710             var afterImportPos = scanner.getStartPos();
24711             var identifier;
24712             if (isIdentifier()) {
24713                 identifier = parseIdentifier();
24714             }
24715             var isTypeOnly = false;
24716             if (token() !== 149 /* FromKeyword */ &&
24717                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
24718                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
24719                 isTypeOnly = true;
24720                 identifier = isIdentifier() ? parseIdentifier() : undefined;
24721             }
24722             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
24723                 return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
24724             }
24725             // Import statement
24726             node.kind = 254 /* ImportDeclaration */;
24727             // ImportDeclaration:
24728             //  import ImportClause from ModuleSpecifier ;
24729             //  import ModuleSpecifier;
24730             if (identifier || // import id
24731                 token() === 41 /* AsteriskToken */ || // import *
24732                 token() === 18 /* OpenBraceToken */ // import {
24733             ) {
24734                 node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
24735                 parseExpected(149 /* FromKeyword */);
24736             }
24737             node.moduleSpecifier = parseModuleSpecifier();
24738             parseSemicolon();
24739             return finishNode(node);
24740         }
24741         function tokenAfterImportDefinitelyProducesImportDeclaration() {
24742             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
24743         }
24744         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
24745             // In `import id ___`, the current token decides whether to produce
24746             // an ImportDeclaration or ImportEqualsDeclaration.
24747             return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
24748         }
24749         function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
24750             node.kind = 253 /* ImportEqualsDeclaration */;
24751             node.name = identifier;
24752             parseExpected(62 /* EqualsToken */);
24753             node.moduleReference = parseModuleReference();
24754             parseSemicolon();
24755             var finished = finishNode(node);
24756             if (isTypeOnly) {
24757                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
24758             }
24759             return finished;
24760         }
24761         function parseImportClause(identifier, fullStart, isTypeOnly) {
24762             // ImportClause:
24763             //  ImportedDefaultBinding
24764             //  NameSpaceImport
24765             //  NamedImports
24766             //  ImportedDefaultBinding, NameSpaceImport
24767             //  ImportedDefaultBinding, NamedImports
24768             var importClause = createNode(255 /* ImportClause */, fullStart);
24769             importClause.isTypeOnly = isTypeOnly;
24770             if (identifier) {
24771                 // ImportedDefaultBinding:
24772                 //  ImportedBinding
24773                 importClause.name = identifier;
24774             }
24775             // If there was no default import or if there is comma token after default import
24776             // parse namespace or named imports
24777             if (!importClause.name ||
24778                 parseOptional(27 /* CommaToken */)) {
24779                 importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
24780             }
24781             return finishNode(importClause);
24782         }
24783         function parseModuleReference() {
24784             return isExternalModuleReference()
24785                 ? parseExternalModuleReference()
24786                 : parseEntityName(/*allowReservedWords*/ false);
24787         }
24788         function parseExternalModuleReference() {
24789             var node = createNode(265 /* ExternalModuleReference */);
24790             parseExpected(139 /* RequireKeyword */);
24791             parseExpected(20 /* OpenParenToken */);
24792             node.expression = parseModuleSpecifier();
24793             parseExpected(21 /* CloseParenToken */);
24794             return finishNode(node);
24795         }
24796         function parseModuleSpecifier() {
24797             if (token() === 10 /* StringLiteral */) {
24798                 var result = parseLiteralNode();
24799                 result.text = internIdentifier(result.text);
24800                 return result;
24801             }
24802             else {
24803                 // We allow arbitrary expressions here, even though the grammar only allows string
24804                 // literals.  We check to ensure that it is only a string literal later in the grammar
24805                 // check pass.
24806                 return parseExpression();
24807             }
24808         }
24809         function parseNamespaceImport() {
24810             // NameSpaceImport:
24811             //  * as ImportedBinding
24812             var namespaceImport = createNode(256 /* NamespaceImport */);
24813             parseExpected(41 /* AsteriskToken */);
24814             parseExpected(123 /* AsKeyword */);
24815             namespaceImport.name = parseIdentifier();
24816             return finishNode(namespaceImport);
24817         }
24818         function parseNamedImportsOrExports(kind) {
24819             var node = createNode(kind);
24820             // NamedImports:
24821             //  { }
24822             //  { ImportsList }
24823             //  { ImportsList, }
24824             // ImportsList:
24825             //  ImportSpecifier
24826             //  ImportsList, ImportSpecifier
24827             node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
24828             return finishNode(node);
24829         }
24830         function parseExportSpecifier() {
24831             return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
24832         }
24833         function parseImportSpecifier() {
24834             return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
24835         }
24836         function parseImportOrExportSpecifier(kind) {
24837             var node = createNode(kind);
24838             // ImportSpecifier:
24839             //   BindingIdentifier
24840             //   IdentifierName as BindingIdentifier
24841             // ExportSpecifier:
24842             //   IdentifierName
24843             //   IdentifierName as IdentifierName
24844             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24845             var checkIdentifierStart = scanner.getTokenPos();
24846             var checkIdentifierEnd = scanner.getTextPos();
24847             var identifierName = parseIdentifierName();
24848             if (token() === 123 /* AsKeyword */) {
24849                 node.propertyName = identifierName;
24850                 parseExpected(123 /* AsKeyword */);
24851                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24852                 checkIdentifierStart = scanner.getTokenPos();
24853                 checkIdentifierEnd = scanner.getTextPos();
24854                 node.name = parseIdentifierName();
24855             }
24856             else {
24857                 node.name = identifierName;
24858             }
24859             if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
24860                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
24861             }
24862             return finishNode(node);
24863         }
24864         function parseNamespaceExport(pos) {
24865             var node = createNode(262 /* NamespaceExport */, pos);
24866             node.name = parseIdentifier();
24867             return finishNode(node);
24868         }
24869         function parseExportDeclaration(node) {
24870             node.kind = 260 /* ExportDeclaration */;
24871             node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
24872             var namespaceExportPos = scanner.getStartPos();
24873             if (parseOptional(41 /* AsteriskToken */)) {
24874                 if (parseOptional(123 /* AsKeyword */)) {
24875                     node.exportClause = parseNamespaceExport(namespaceExportPos);
24876                 }
24877                 parseExpected(149 /* FromKeyword */);
24878                 node.moduleSpecifier = parseModuleSpecifier();
24879             }
24880             else {
24881                 node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
24882                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
24883                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
24884                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
24885                 if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
24886                     parseExpected(149 /* FromKeyword */);
24887                     node.moduleSpecifier = parseModuleSpecifier();
24888                 }
24889             }
24890             parseSemicolon();
24891             return finishNode(node);
24892         }
24893         function parseExportAssignment(node) {
24894             node.kind = 259 /* ExportAssignment */;
24895             if (parseOptional(62 /* EqualsToken */)) {
24896                 node.isExportEquals = true;
24897             }
24898             else {
24899                 parseExpected(84 /* DefaultKeyword */);
24900             }
24901             node.expression = parseAssignmentExpressionOrHigher();
24902             parseSemicolon();
24903             return finishNode(node);
24904         }
24905         function setExternalModuleIndicator(sourceFile) {
24906             // Try to use the first top-level import/export when available, then
24907             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
24908             sourceFile.externalModuleIndicator =
24909                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
24910                     getImportMetaIfNecessary(sourceFile);
24911         }
24912         function isAnExternalModuleIndicatorNode(node) {
24913             return hasModifierOfKind(node, 89 /* ExportKeyword */)
24914                 || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
24915                 || node.kind === 254 /* ImportDeclaration */
24916                 || node.kind === 259 /* ExportAssignment */
24917                 || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
24918         }
24919         function getImportMetaIfNecessary(sourceFile) {
24920             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
24921                 walkTreeForExternalModuleIndicators(sourceFile) :
24922                 undefined;
24923         }
24924         function walkTreeForExternalModuleIndicators(node) {
24925             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
24926         }
24927         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
24928         function hasModifierOfKind(node, kind) {
24929             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
24930         }
24931         function isImportMeta(node) {
24932             return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
24933         }
24934         var ParsingContext;
24935         (function (ParsingContext) {
24936             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
24937             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
24938             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
24939             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
24940             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
24941             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
24942             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
24943             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
24944             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
24945             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
24946             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
24947             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
24948             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
24949             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
24950             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
24951             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
24952             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
24953             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
24954             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
24955             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
24956             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
24957             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
24958             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
24959             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
24960             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
24961         })(ParsingContext || (ParsingContext = {}));
24962         var Tristate;
24963         (function (Tristate) {
24964             Tristate[Tristate["False"] = 0] = "False";
24965             Tristate[Tristate["True"] = 1] = "True";
24966             Tristate[Tristate["Unknown"] = 2] = "Unknown";
24967         })(Tristate || (Tristate = {}));
24968         var JSDocParser;
24969         (function (JSDocParser) {
24970             function parseJSDocTypeExpressionForTests(content, start, length) {
24971                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24972                 sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
24973                 scanner.setText(content, start, length);
24974                 currentToken = scanner.scan();
24975                 var jsDocTypeExpression = parseJSDocTypeExpression();
24976                 var diagnostics = parseDiagnostics;
24977                 clearState();
24978                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
24979             }
24980             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
24981             // Parses out a JSDoc type expression.
24982             function parseJSDocTypeExpression(mayOmitBraces) {
24983                 var result = createNode(294 /* JSDocTypeExpression */);
24984                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
24985                 result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
24986                 if (!mayOmitBraces || hasBrace) {
24987                     parseExpectedJSDoc(19 /* CloseBraceToken */);
24988                 }
24989                 fixupParentReferences(result);
24990                 return finishNode(result);
24991             }
24992             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
24993             function parseIsolatedJSDocComment(content, start, length) {
24994                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24995                 sourceFile = { languageVariant: 0 /* Standard */, text: content };
24996                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24997                 var diagnostics = parseDiagnostics;
24998                 clearState();
24999                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
25000             }
25001             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
25002             function parseJSDocComment(parent, start, length) {
25003                 var _a;
25004                 var saveToken = currentToken;
25005                 var saveParseDiagnosticsLength = parseDiagnostics.length;
25006                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
25007                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
25008                 if (comment) {
25009                     comment.parent = parent;
25010                 }
25011                 if (contextFlags & 131072 /* JavaScriptFile */) {
25012                     if (!sourceFile.jsDocDiagnostics) {
25013                         sourceFile.jsDocDiagnostics = [];
25014                     }
25015                     (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
25016                 }
25017                 currentToken = saveToken;
25018                 parseDiagnostics.length = saveParseDiagnosticsLength;
25019                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
25020                 return comment;
25021             }
25022             JSDocParser.parseJSDocComment = parseJSDocComment;
25023             var JSDocState;
25024             (function (JSDocState) {
25025                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
25026                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
25027                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
25028                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
25029             })(JSDocState || (JSDocState = {}));
25030             var PropertyLikeParse;
25031             (function (PropertyLikeParse) {
25032                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
25033                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
25034                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
25035             })(PropertyLikeParse || (PropertyLikeParse = {}));
25036             function parseJSDocCommentWorker(start, length) {
25037                 if (start === void 0) { start = 0; }
25038                 var content = sourceText;
25039                 var end = length === undefined ? content.length : start + length;
25040                 length = end - start;
25041                 ts.Debug.assert(start >= 0);
25042                 ts.Debug.assert(start <= end);
25043                 ts.Debug.assert(end <= content.length);
25044                 // Check for /** (JSDoc opening part)
25045                 if (!isJSDocLikeText(content, start)) {
25046                     return undefined;
25047                 }
25048                 var tags;
25049                 var tagsPos;
25050                 var tagsEnd;
25051                 var comments = [];
25052                 // + 3 for leading /**, - 5 in total for /** */
25053                 return scanner.scanRange(start + 3, length - 5, function () {
25054                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
25055                     // This is so that /** * @type */ doesn't parse.
25056                     var state = 1 /* SawAsterisk */;
25057                     var margin;
25058                     // + 4 for leading '/** '
25059                     var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
25060                     function pushComment(text) {
25061                         if (!margin) {
25062                             margin = indent;
25063                         }
25064                         comments.push(text);
25065                         indent += text.length;
25066                     }
25067                     nextTokenJSDoc();
25068                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
25069                         ;
25070                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
25071                         state = 0 /* BeginningOfLine */;
25072                         indent = 0;
25073                     }
25074                     loop: while (true) {
25075                         switch (token()) {
25076                             case 59 /* AtToken */:
25077                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
25078                                     removeTrailingWhitespace(comments);
25079                                     addTag(parseTag(indent));
25080                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
25081                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
25082                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
25083                                     state = 0 /* BeginningOfLine */;
25084                                     margin = undefined;
25085                                 }
25086                                 else {
25087                                     pushComment(scanner.getTokenText());
25088                                 }
25089                                 break;
25090                             case 4 /* NewLineTrivia */:
25091                                 comments.push(scanner.getTokenText());
25092                                 state = 0 /* BeginningOfLine */;
25093                                 indent = 0;
25094                                 break;
25095                             case 41 /* AsteriskToken */:
25096                                 var asterisk = scanner.getTokenText();
25097                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
25098                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
25099                                     state = 2 /* SavingComments */;
25100                                     pushComment(asterisk);
25101                                 }
25102                                 else {
25103                                     // Ignore the first asterisk on a line
25104                                     state = 1 /* SawAsterisk */;
25105                                     indent += asterisk.length;
25106                                 }
25107                                 break;
25108                             case 5 /* WhitespaceTrivia */:
25109                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
25110                                 var whitespace = scanner.getTokenText();
25111                                 if (state === 2 /* SavingComments */) {
25112                                     comments.push(whitespace);
25113                                 }
25114                                 else if (margin !== undefined && indent + whitespace.length > margin) {
25115                                     comments.push(whitespace.slice(margin - indent - 1));
25116                                 }
25117                                 indent += whitespace.length;
25118                                 break;
25119                             case 1 /* EndOfFileToken */:
25120                                 break loop;
25121                             default:
25122                                 // Anything else is doc comment text. We just save it. Because it
25123                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
25124                                 // line break.
25125                                 state = 2 /* SavingComments */;
25126                                 pushComment(scanner.getTokenText());
25127                                 break;
25128                         }
25129                         nextTokenJSDoc();
25130                     }
25131                     removeLeadingNewlines(comments);
25132                     removeTrailingWhitespace(comments);
25133                     return createJSDocComment();
25134                 });
25135                 function removeLeadingNewlines(comments) {
25136                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
25137                         comments.shift();
25138                     }
25139                 }
25140                 function removeTrailingWhitespace(comments) {
25141                     while (comments.length && comments[comments.length - 1].trim() === "") {
25142                         comments.pop();
25143                     }
25144                 }
25145                 function createJSDocComment() {
25146                     var result = createNode(303 /* JSDocComment */, start);
25147                     result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
25148                     result.comment = comments.length ? comments.join("") : undefined;
25149                     return finishNode(result, end);
25150                 }
25151                 function isNextNonwhitespaceTokenEndOfFile() {
25152                     // We must use infinite lookahead, as there could be any number of newlines :(
25153                     while (true) {
25154                         nextTokenJSDoc();
25155                         if (token() === 1 /* EndOfFileToken */) {
25156                             return true;
25157                         }
25158                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
25159                             return false;
25160                         }
25161                     }
25162                 }
25163                 function skipWhitespace() {
25164                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25165                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25166                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25167                         }
25168                     }
25169                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25170                         nextTokenJSDoc();
25171                     }
25172                 }
25173                 function skipWhitespaceOrAsterisk() {
25174                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25175                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25176                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25177                         }
25178                     }
25179                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
25180                     var seenLineBreak = false;
25181                     var indentText = "";
25182                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25183                         indentText += scanner.getTokenText();
25184                         if (token() === 4 /* NewLineTrivia */) {
25185                             precedingLineBreak = true;
25186                             seenLineBreak = true;
25187                             indentText = "";
25188                         }
25189                         else if (token() === 41 /* AsteriskToken */) {
25190                             precedingLineBreak = false;
25191                         }
25192                         nextTokenJSDoc();
25193                     }
25194                     return seenLineBreak ? indentText : "";
25195                 }
25196                 function parseTag(margin) {
25197                     ts.Debug.assert(token() === 59 /* AtToken */);
25198                     var start = scanner.getTokenPos();
25199                     nextTokenJSDoc();
25200                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
25201                     var indentText = skipWhitespaceOrAsterisk();
25202                     var tag;
25203                     switch (tagName.escapedText) {
25204                         case "author":
25205                             tag = parseAuthorTag(start, tagName, margin);
25206                             break;
25207                         case "implements":
25208                             tag = parseImplementsTag(start, tagName);
25209                             break;
25210                         case "augments":
25211                         case "extends":
25212                             tag = parseAugmentsTag(start, tagName);
25213                             break;
25214                         case "class":
25215                         case "constructor":
25216                             tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
25217                             break;
25218                         case "public":
25219                             tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
25220                             break;
25221                         case "private":
25222                             tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
25223                             break;
25224                         case "protected":
25225                             tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
25226                             break;
25227                         case "readonly":
25228                             tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
25229                             break;
25230                         case "this":
25231                             tag = parseThisTag(start, tagName);
25232                             break;
25233                         case "enum":
25234                             tag = parseEnumTag(start, tagName);
25235                             break;
25236                         case "arg":
25237                         case "argument":
25238                         case "param":
25239                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
25240                         case "return":
25241                         case "returns":
25242                             tag = parseReturnTag(start, tagName);
25243                             break;
25244                         case "template":
25245                             tag = parseTemplateTag(start, tagName);
25246                             break;
25247                         case "type":
25248                             tag = parseTypeTag(start, tagName);
25249                             break;
25250                         case "typedef":
25251                             tag = parseTypedefTag(start, tagName, margin);
25252                             break;
25253                         case "callback":
25254                             tag = parseCallbackTag(start, tagName, margin);
25255                             break;
25256                         default:
25257                             tag = parseUnknownTag(start, tagName);
25258                             break;
25259                     }
25260                     if (!tag.comment) {
25261                         // some tags, like typedef and callback, have already parsed their comments earlier
25262                         if (!indentText) {
25263                             margin += tag.end - tag.pos;
25264                         }
25265                         tag.comment = parseTagComments(margin, indentText.slice(margin));
25266                     }
25267                     return tag;
25268                 }
25269                 function parseTagComments(indent, initialMargin) {
25270                     var comments = [];
25271                     var state = 0 /* BeginningOfLine */;
25272                     var margin;
25273                     function pushComment(text) {
25274                         if (!margin) {
25275                             margin = indent;
25276                         }
25277                         comments.push(text);
25278                         indent += text.length;
25279                     }
25280                     if (initialMargin !== undefined) {
25281                         // jump straight to saving comments if there is some initial indentation
25282                         if (initialMargin !== "") {
25283                             pushComment(initialMargin);
25284                         }
25285                         state = 1 /* SawAsterisk */;
25286                     }
25287                     var tok = token();
25288                     loop: while (true) {
25289                         switch (tok) {
25290                             case 4 /* NewLineTrivia */:
25291                                 if (state >= 1 /* SawAsterisk */) {
25292                                     state = 0 /* BeginningOfLine */;
25293                                     // don't use pushComment here because we want to keep the margin unchanged
25294                                     comments.push(scanner.getTokenText());
25295                                 }
25296                                 indent = 0;
25297                                 break;
25298                             case 59 /* AtToken */:
25299                                 if (state === 3 /* SavingBackticks */) {
25300                                     comments.push(scanner.getTokenText());
25301                                     break;
25302                                 }
25303                                 scanner.setTextPos(scanner.getTextPos() - 1);
25304                             // falls through
25305                             case 1 /* EndOfFileToken */:
25306                                 // Done
25307                                 break loop;
25308                             case 5 /* WhitespaceTrivia */:
25309                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
25310                                     pushComment(scanner.getTokenText());
25311                                 }
25312                                 else {
25313                                     var whitespace = scanner.getTokenText();
25314                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
25315                                     if (margin !== undefined && indent + whitespace.length > margin) {
25316                                         comments.push(whitespace.slice(margin - indent));
25317                                     }
25318                                     indent += whitespace.length;
25319                                 }
25320                                 break;
25321                             case 18 /* OpenBraceToken */:
25322                                 state = 2 /* SavingComments */;
25323                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
25324                                     pushComment(scanner.getTokenText());
25325                                     nextTokenJSDoc();
25326                                     pushComment(scanner.getTokenText());
25327                                     nextTokenJSDoc();
25328                                 }
25329                                 pushComment(scanner.getTokenText());
25330                                 break;
25331                             case 61 /* BacktickToken */:
25332                                 if (state === 3 /* SavingBackticks */) {
25333                                     state = 2 /* SavingComments */;
25334                                 }
25335                                 else {
25336                                     state = 3 /* SavingBackticks */;
25337                                 }
25338                                 pushComment(scanner.getTokenText());
25339                                 break;
25340                             case 41 /* AsteriskToken */:
25341                                 if (state === 0 /* BeginningOfLine */) {
25342                                     // leading asterisks start recording on the *next* (non-whitespace) token
25343                                     state = 1 /* SawAsterisk */;
25344                                     indent += 1;
25345                                     break;
25346                                 }
25347                             // record the * as a comment
25348                             // falls through
25349                             default:
25350                                 if (state !== 3 /* SavingBackticks */) {
25351                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
25352                                 }
25353                                 pushComment(scanner.getTokenText());
25354                                 break;
25355                         }
25356                         tok = nextTokenJSDoc();
25357                     }
25358                     removeLeadingNewlines(comments);
25359                     removeTrailingWhitespace(comments);
25360                     return comments.length === 0 ? undefined : comments.join("");
25361                 }
25362                 function parseUnknownTag(start, tagName) {
25363                     var result = createNode(306 /* JSDocTag */, start);
25364                     result.tagName = tagName;
25365                     return finishNode(result);
25366                 }
25367                 function addTag(tag) {
25368                     if (!tag) {
25369                         return;
25370                     }
25371                     if (!tags) {
25372                         tags = [tag];
25373                         tagsPos = tag.pos;
25374                     }
25375                     else {
25376                         tags.push(tag);
25377                     }
25378                     tagsEnd = tag.end;
25379                 }
25380                 function tryParseTypeExpression() {
25381                     skipWhitespaceOrAsterisk();
25382                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
25383                 }
25384                 function parseBracketNameInPropertyAndParamTag() {
25385                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
25386                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
25387                     if (isBracketed) {
25388                         skipWhitespace();
25389                     }
25390                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
25391                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
25392                     var name = parseJSDocEntityName();
25393                     if (isBackquoted) {
25394                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
25395                     }
25396                     if (isBracketed) {
25397                         skipWhitespace();
25398                         // May have an optional default, e.g. '[foo = 42]'
25399                         if (parseOptionalToken(62 /* EqualsToken */)) {
25400                             parseExpression();
25401                         }
25402                         parseExpected(23 /* CloseBracketToken */);
25403                     }
25404                     return { name: name, isBracketed: isBracketed };
25405                 }
25406                 function isObjectOrObjectArrayTypeReference(node) {
25407                     switch (node.kind) {
25408                         case 141 /* ObjectKeyword */:
25409                             return true;
25410                         case 174 /* ArrayType */:
25411                             return isObjectOrObjectArrayTypeReference(node.elementType);
25412                         default:
25413                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
25414                     }
25415                 }
25416                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
25417                     var typeExpression = tryParseTypeExpression();
25418                     var isNameFirst = !typeExpression;
25419                     skipWhitespaceOrAsterisk();
25420                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
25421                     skipWhitespace();
25422                     if (isNameFirst) {
25423                         typeExpression = tryParseTypeExpression();
25424                     }
25425                     var result = target === 1 /* Property */ ?
25426                         createNode(323 /* JSDocPropertyTag */, start) :
25427                         createNode(317 /* JSDocParameterTag */, start);
25428                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
25429                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
25430                     if (nestedTypeLiteral) {
25431                         typeExpression = nestedTypeLiteral;
25432                         isNameFirst = true;
25433                     }
25434                     result.tagName = tagName;
25435                     result.typeExpression = typeExpression;
25436                     result.name = name;
25437                     result.isNameFirst = isNameFirst;
25438                     result.isBracketed = isBracketed;
25439                     result.comment = comment;
25440                     return finishNode(result);
25441                 }
25442                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
25443                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25444                         var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
25445                         var child = void 0;
25446                         var jsdocTypeLiteral = void 0;
25447                         var start_3 = scanner.getStartPos();
25448                         var children = void 0;
25449                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
25450                             if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
25451                                 children = ts.append(children, child);
25452                             }
25453                         }
25454                         if (children) {
25455                             jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
25456                             jsdocTypeLiteral.jsDocPropertyTags = children;
25457                             if (typeExpression.type.kind === 174 /* ArrayType */) {
25458                                 jsdocTypeLiteral.isArrayType = true;
25459                             }
25460                             typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
25461                             return finishNode(typeLiteralExpression);
25462                         }
25463                     }
25464                 }
25465                 function parseReturnTag(start, tagName) {
25466                     if (ts.some(tags, ts.isJSDocReturnTag)) {
25467                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25468                     }
25469                     var result = createNode(318 /* JSDocReturnTag */, start);
25470                     result.tagName = tagName;
25471                     result.typeExpression = tryParseTypeExpression();
25472                     return finishNode(result);
25473                 }
25474                 function parseTypeTag(start, tagName) {
25475                     if (ts.some(tags, ts.isJSDocTypeTag)) {
25476                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25477                     }
25478                     var result = createNode(320 /* JSDocTypeTag */, start);
25479                     result.tagName = tagName;
25480                     result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25481                     return finishNode(result);
25482                 }
25483                 function parseAuthorTag(start, tagName, indent) {
25484                     var result = createNode(309 /* JSDocAuthorTag */, start);
25485                     result.tagName = tagName;
25486                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
25487                     if (!authorInfoWithEmail) {
25488                         return finishNode(result);
25489                     }
25490                     result.comment = authorInfoWithEmail;
25491                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
25492                         var comment = parseTagComments(indent);
25493                         if (comment) {
25494                             result.comment += comment;
25495                         }
25496                     }
25497                     return finishNode(result);
25498                 }
25499                 function tryParseAuthorNameAndEmail() {
25500                     var comments = [];
25501                     var seenLessThan = false;
25502                     var seenGreaterThan = false;
25503                     var token = scanner.getToken();
25504                     loop: while (true) {
25505                         switch (token) {
25506                             case 75 /* Identifier */:
25507                             case 5 /* WhitespaceTrivia */:
25508                             case 24 /* DotToken */:
25509                             case 59 /* AtToken */:
25510                                 comments.push(scanner.getTokenText());
25511                                 break;
25512                             case 29 /* LessThanToken */:
25513                                 if (seenLessThan || seenGreaterThan) {
25514                                     return;
25515                                 }
25516                                 seenLessThan = true;
25517                                 comments.push(scanner.getTokenText());
25518                                 break;
25519                             case 31 /* GreaterThanToken */:
25520                                 if (!seenLessThan || seenGreaterThan) {
25521                                     return;
25522                                 }
25523                                 seenGreaterThan = true;
25524                                 comments.push(scanner.getTokenText());
25525                                 scanner.setTextPos(scanner.getTokenPos() + 1);
25526                                 break loop;
25527                             case 4 /* NewLineTrivia */:
25528                             case 1 /* EndOfFileToken */:
25529                                 break loop;
25530                         }
25531                         token = nextTokenJSDoc();
25532                     }
25533                     if (seenLessThan && seenGreaterThan) {
25534                         return comments.length === 0 ? undefined : comments.join("");
25535                     }
25536                 }
25537                 function parseImplementsTag(start, tagName) {
25538                     var result = createNode(308 /* JSDocImplementsTag */, start);
25539                     result.tagName = tagName;
25540                     result.class = parseExpressionWithTypeArgumentsForAugments();
25541                     return finishNode(result);
25542                 }
25543                 function parseAugmentsTag(start, tagName) {
25544                     var result = createNode(307 /* JSDocAugmentsTag */, start);
25545                     result.tagName = tagName;
25546                     result.class = parseExpressionWithTypeArgumentsForAugments();
25547                     return finishNode(result);
25548                 }
25549                 function parseExpressionWithTypeArgumentsForAugments() {
25550                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
25551                     var node = createNode(216 /* ExpressionWithTypeArguments */);
25552                     node.expression = parsePropertyAccessEntityNameExpression();
25553                     node.typeArguments = tryParseTypeArguments();
25554                     var res = finishNode(node);
25555                     if (usedBrace) {
25556                         parseExpected(19 /* CloseBraceToken */);
25557                     }
25558                     return res;
25559                 }
25560                 function parsePropertyAccessEntityNameExpression() {
25561                     var node = parseJSDocIdentifierName();
25562                     while (parseOptional(24 /* DotToken */)) {
25563                         var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
25564                         prop.expression = node;
25565                         prop.name = parseJSDocIdentifierName();
25566                         node = finishNode(prop);
25567                     }
25568                     return node;
25569                 }
25570                 function parseSimpleTag(start, kind, tagName) {
25571                     var tag = createNode(kind, start);
25572                     tag.tagName = tagName;
25573                     return finishNode(tag);
25574                 }
25575                 function parseThisTag(start, tagName) {
25576                     var tag = createNode(319 /* JSDocThisTag */, start);
25577                     tag.tagName = tagName;
25578                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25579                     skipWhitespace();
25580                     return finishNode(tag);
25581                 }
25582                 function parseEnumTag(start, tagName) {
25583                     var tag = createNode(316 /* JSDocEnumTag */, start);
25584                     tag.tagName = tagName;
25585                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25586                     skipWhitespace();
25587                     return finishNode(tag);
25588                 }
25589                 function parseTypedefTag(start, tagName, indent) {
25590                     var typeExpression = tryParseTypeExpression();
25591                     skipWhitespaceOrAsterisk();
25592                     var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
25593                     typedefTag.tagName = tagName;
25594                     typedefTag.fullName = parseJSDocTypeNameWithNamespace();
25595                     typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
25596                     skipWhitespace();
25597                     typedefTag.comment = parseTagComments(indent);
25598                     typedefTag.typeExpression = typeExpression;
25599                     var end;
25600                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25601                         var child = void 0;
25602                         var jsdocTypeLiteral = void 0;
25603                         var childTypeTag = void 0;
25604                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
25605                             if (!jsdocTypeLiteral) {
25606                                 jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
25607                             }
25608                             if (child.kind === 320 /* JSDocTypeTag */) {
25609                                 if (childTypeTag) {
25610                                     break;
25611                                 }
25612                                 else {
25613                                     childTypeTag = child;
25614                                 }
25615                             }
25616                             else {
25617                                 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
25618                             }
25619                         }
25620                         if (jsdocTypeLiteral) {
25621                             if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
25622                                 jsdocTypeLiteral.isArrayType = true;
25623                             }
25624                             typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
25625                                 childTypeTag.typeExpression :
25626                                 finishNode(jsdocTypeLiteral);
25627                             end = typedefTag.typeExpression.end;
25628                         }
25629                     }
25630                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
25631                     return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
25632                 }
25633                 function parseJSDocTypeNameWithNamespace(nested) {
25634                     var pos = scanner.getTokenPos();
25635                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25636                         return undefined;
25637                     }
25638                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
25639                     if (parseOptional(24 /* DotToken */)) {
25640                         var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
25641                         if (nested) {
25642                             jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
25643                         }
25644                         jsDocNamespaceNode.name = typeNameOrNamespaceName;
25645                         jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
25646                         return finishNode(jsDocNamespaceNode);
25647                     }
25648                     if (nested) {
25649                         typeNameOrNamespaceName.isInJSDocNamespace = true;
25650                     }
25651                     return typeNameOrNamespaceName;
25652                 }
25653                 function parseCallbackTag(start, tagName, indent) {
25654                     var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
25655                     callbackTag.tagName = tagName;
25656                     callbackTag.fullName = parseJSDocTypeNameWithNamespace();
25657                     callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
25658                     skipWhitespace();
25659                     callbackTag.comment = parseTagComments(indent);
25660                     var child;
25661                     var jsdocSignature = createNode(305 /* JSDocSignature */, start);
25662                     jsdocSignature.parameters = [];
25663                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
25664                         jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
25665                     }
25666                     var returnTag = tryParse(function () {
25667                         if (parseOptionalJsdoc(59 /* AtToken */)) {
25668                             var tag = parseTag(indent);
25669                             if (tag && tag.kind === 318 /* JSDocReturnTag */) {
25670                                 return tag;
25671                             }
25672                         }
25673                     });
25674                     if (returnTag) {
25675                         jsdocSignature.type = returnTag;
25676                     }
25677                     callbackTag.typeExpression = finishNode(jsdocSignature);
25678                     return finishNode(callbackTag);
25679                 }
25680                 function getJSDocTypeAliasName(fullName) {
25681                     if (fullName) {
25682                         var rightNode = fullName;
25683                         while (true) {
25684                             if (ts.isIdentifier(rightNode) || !rightNode.body) {
25685                                 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
25686                             }
25687                             rightNode = rightNode.body;
25688                         }
25689                     }
25690                 }
25691                 function escapedTextsEqual(a, b) {
25692                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
25693                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
25694                             a = a.left;
25695                             b = b.left;
25696                         }
25697                         else {
25698                             return false;
25699                         }
25700                     }
25701                     return a.escapedText === b.escapedText;
25702                 }
25703                 function parseChildPropertyTag(indent) {
25704                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
25705                 }
25706                 function parseChildParameterOrPropertyTag(target, indent, name) {
25707                     var canParseTag = true;
25708                     var seenAsterisk = false;
25709                     while (true) {
25710                         switch (nextTokenJSDoc()) {
25711                             case 59 /* AtToken */:
25712                                 if (canParseTag) {
25713                                     var child = tryParseChildTag(target, indent);
25714                                     if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
25715                                         target !== 4 /* CallbackParameter */ &&
25716                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
25717                                         return false;
25718                                     }
25719                                     return child;
25720                                 }
25721                                 seenAsterisk = false;
25722                                 break;
25723                             case 4 /* NewLineTrivia */:
25724                                 canParseTag = true;
25725                                 seenAsterisk = false;
25726                                 break;
25727                             case 41 /* AsteriskToken */:
25728                                 if (seenAsterisk) {
25729                                     canParseTag = false;
25730                                 }
25731                                 seenAsterisk = true;
25732                                 break;
25733                             case 75 /* Identifier */:
25734                                 canParseTag = false;
25735                                 break;
25736                             case 1 /* EndOfFileToken */:
25737                                 return false;
25738                         }
25739                     }
25740                 }
25741                 function tryParseChildTag(target, indent) {
25742                     ts.Debug.assert(token() === 59 /* AtToken */);
25743                     var start = scanner.getStartPos();
25744                     nextTokenJSDoc();
25745                     var tagName = parseJSDocIdentifierName();
25746                     skipWhitespace();
25747                     var t;
25748                     switch (tagName.escapedText) {
25749                         case "type":
25750                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
25751                         case "prop":
25752                         case "property":
25753                             t = 1 /* Property */;
25754                             break;
25755                         case "arg":
25756                         case "argument":
25757                         case "param":
25758                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
25759                             break;
25760                         default:
25761                             return false;
25762                     }
25763                     if (!(target & t)) {
25764                         return false;
25765                     }
25766                     return parseParameterOrPropertyTag(start, tagName, target, indent);
25767                 }
25768                 function parseTemplateTag(start, tagName) {
25769                     // the template tag looks like '@template {Constraint} T,U,V'
25770                     var constraint;
25771                     if (token() === 18 /* OpenBraceToken */) {
25772                         constraint = parseJSDocTypeExpression();
25773                     }
25774                     var typeParameters = [];
25775                     var typeParametersPos = getNodePos();
25776                     do {
25777                         skipWhitespace();
25778                         var typeParameter = createNode(155 /* TypeParameter */);
25779                         typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
25780                         finishNode(typeParameter);
25781                         skipWhitespaceOrAsterisk();
25782                         typeParameters.push(typeParameter);
25783                     } while (parseOptionalJsdoc(27 /* CommaToken */));
25784                     var result = createNode(321 /* JSDocTemplateTag */, start);
25785                     result.tagName = tagName;
25786                     result.constraint = constraint;
25787                     result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
25788                     finishNode(result);
25789                     return result;
25790                 }
25791                 function parseOptionalJsdoc(t) {
25792                     if (token() === t) {
25793                         nextTokenJSDoc();
25794                         return true;
25795                     }
25796                     return false;
25797                 }
25798                 function parseJSDocEntityName() {
25799                     var entity = parseJSDocIdentifierName();
25800                     if (parseOptional(22 /* OpenBracketToken */)) {
25801                         parseExpected(23 /* CloseBracketToken */);
25802                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
25803                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
25804                         // but it's not worth it to enforce that restriction.
25805                     }
25806                     while (parseOptional(24 /* DotToken */)) {
25807                         var name = parseJSDocIdentifierName();
25808                         if (parseOptional(22 /* OpenBracketToken */)) {
25809                             parseExpected(23 /* CloseBracketToken */);
25810                         }
25811                         entity = createQualifiedName(entity, name);
25812                     }
25813                     return entity;
25814                 }
25815                 function parseJSDocIdentifierName(message) {
25816                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25817                         return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
25818                     }
25819                     identifierCount++;
25820                     var pos = scanner.getTokenPos();
25821                     var end = scanner.getTextPos();
25822                     var result = createNode(75 /* Identifier */, pos);
25823                     if (token() !== 75 /* Identifier */) {
25824                         result.originalKeywordKind = token();
25825                     }
25826                     result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
25827                     finishNode(result, end);
25828                     nextTokenJSDoc();
25829                     return result;
25830                 }
25831             }
25832         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
25833     })(Parser || (Parser = {}));
25834     var IncrementalParser;
25835     (function (IncrementalParser) {
25836         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
25837             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
25838             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
25839             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
25840                 // if the text didn't change, then we can just return our current source file as-is.
25841                 return sourceFile;
25842             }
25843             if (sourceFile.statements.length === 0) {
25844                 // If we don't have any statements in the current source file, then there's no real
25845                 // way to incrementally parse.  So just do a full parse instead.
25846                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
25847             }
25848             // Make sure we're not trying to incrementally update a source file more than once.  Once
25849             // we do an update the original source file is considered unusable from that point onwards.
25850             //
25851             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
25852             // tree and give them new positions and parents.  From that point on, trusting the old
25853             // tree at all is not possible as far too much of it may violate invariants.
25854             var incrementalSourceFile = sourceFile;
25855             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
25856             incrementalSourceFile.hasBeenIncrementallyParsed = true;
25857             var oldText = sourceFile.text;
25858             var syntaxCursor = createSyntaxCursor(sourceFile);
25859             // Make the actual change larger so that we know to reparse anything whose lookahead
25860             // might have intersected the change.
25861             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
25862             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
25863             // Ensure that extending the affected range only moved the start of the change range
25864             // earlier in the file.
25865             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
25866             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
25867             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
25868             // The is the amount the nodes after the edit range need to be adjusted.  It can be
25869             // positive (if the edit added characters), negative (if the edit deleted characters)
25870             // or zero (if this was a pure overwrite with nothing added/removed).
25871             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
25872             // If we added or removed characters during the edit, then we need to go and adjust all
25873             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
25874             // may move backward (if we deleted chars).
25875             //
25876             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
25877             // to reuse are already at the appropriate position in the new text.  That way when we
25878             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
25879             // it very easy to determine if we can reuse a node.  If the node's position is at where
25880             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
25881             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
25882             // us, then we'll need to skip it or crumble it as appropriate
25883             //
25884             // We will also adjust the positions of nodes that intersect the change range as well.
25885             // By doing this, we ensure that all the positions in the old tree are consistent, not
25886             // just the positions of nodes entirely before/after the change range.  By being
25887             // consistent, we can then easily map from positions to nodes in the old tree easily.
25888             //
25889             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
25890             // that we cannot reuse these elements.
25891             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
25892             // Now that we've set up our internal incremental state just proceed and parse the
25893             // source file in the normal fashion.  When possible the parser will retrieve and
25894             // reuse nodes from the old tree.
25895             //
25896             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
25897             // parsing, we will be reusing nodes from the old tree, and placing it into new
25898             // parents.  If we don't set the parents now, we'll end up with an observably
25899             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
25900             // will immediately bail out of walking any subtrees when we can see that their parents
25901             // are already correct.
25902             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
25903             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
25904             return result;
25905         }
25906         IncrementalParser.updateSourceFile = updateSourceFile;
25907         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
25908             if (!oldDirectives)
25909                 return newDirectives;
25910             var commentDirectives;
25911             var addedNewlyScannedDirectives = false;
25912             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
25913                 var directive = oldDirectives_1[_i];
25914                 var range = directive.range, type = directive.type;
25915                 // Range before the change
25916                 if (range.end < changeStart) {
25917                     commentDirectives = ts.append(commentDirectives, directive);
25918                 }
25919                 else if (range.pos > changeRangeOldEnd) {
25920                     addNewlyScannedDirectives();
25921                     // Node is entirely past the change range.  We need to move both its pos and
25922                     // end, forward or backward appropriately.
25923                     var updatedDirective = {
25924                         range: { pos: range.pos + delta, end: range.end + delta },
25925                         type: type
25926                     };
25927                     commentDirectives = ts.append(commentDirectives, updatedDirective);
25928                     if (aggressiveChecks) {
25929                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
25930                     }
25931                 }
25932                 // Ignore ranges that fall in change range
25933             }
25934             addNewlyScannedDirectives();
25935             return commentDirectives;
25936             function addNewlyScannedDirectives() {
25937                 if (addedNewlyScannedDirectives)
25938                     return;
25939                 addedNewlyScannedDirectives = true;
25940                 if (!commentDirectives) {
25941                     commentDirectives = newDirectives;
25942                 }
25943                 else if (newDirectives) {
25944                     commentDirectives.push.apply(commentDirectives, newDirectives);
25945                 }
25946             }
25947         }
25948         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
25949             if (isArray) {
25950                 visitArray(element);
25951             }
25952             else {
25953                 visitNode(element);
25954             }
25955             return;
25956             function visitNode(node) {
25957                 var text = "";
25958                 if (aggressiveChecks && shouldCheckNode(node)) {
25959                     text = oldText.substring(node.pos, node.end);
25960                 }
25961                 // Ditch any existing LS children we may have created.  This way we can avoid
25962                 // moving them forward.
25963                 if (node._children) {
25964                     node._children = undefined;
25965                 }
25966                 node.pos += delta;
25967                 node.end += delta;
25968                 if (aggressiveChecks && shouldCheckNode(node)) {
25969                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
25970                 }
25971                 forEachChild(node, visitNode, visitArray);
25972                 if (ts.hasJSDocNodes(node)) {
25973                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25974                         var jsDocComment = _a[_i];
25975                         visitNode(jsDocComment);
25976                     }
25977                 }
25978                 checkNodePositions(node, aggressiveChecks);
25979             }
25980             function visitArray(array) {
25981                 array._children = undefined;
25982                 array.pos += delta;
25983                 array.end += delta;
25984                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
25985                     var node = array_8[_i];
25986                     visitNode(node);
25987                 }
25988             }
25989         }
25990         function shouldCheckNode(node) {
25991             switch (node.kind) {
25992                 case 10 /* StringLiteral */:
25993                 case 8 /* NumericLiteral */:
25994                 case 75 /* Identifier */:
25995                     return true;
25996             }
25997             return false;
25998         }
25999         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
26000             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
26001             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
26002             ts.Debug.assert(element.pos <= element.end);
26003             // We have an element that intersects the change range in some way.  It may have its
26004             // start, or its end (or both) in the changed range.  We want to adjust any part
26005             // that intersects such that the final tree is in a consistent state.  i.e. all
26006             // children have spans within the span of their parent, and all siblings are ordered
26007             // properly.
26008             // We may need to update both the 'pos' and the 'end' of the element.
26009             // If the 'pos' is before the start of the change, then we don't need to touch it.
26010             // If it isn't, then the 'pos' must be inside the change.  How we update it will
26011             // depend if delta is positive or negative. If delta is positive then we have
26012             // something like:
26013             //
26014             //  -------------------AAA-----------------
26015             //  -------------------BBBCCCCCCC-----------------
26016             //
26017             // In this case, we consider any node that started in the change range to still be
26018             // starting at the same position.
26019             //
26020             // however, if the delta is negative, then we instead have something like this:
26021             //
26022             //  -------------------XXXYYYYYYY-----------------
26023             //  -------------------ZZZ-----------------
26024             //
26025             // In this case, any element that started in the 'X' range will keep its position.
26026             // However any element that started after that will have their pos adjusted to be
26027             // at the end of the new range.  i.e. any node that started in the 'Y' range will
26028             // be adjusted to have their start at the end of the 'Z' range.
26029             //
26030             // The element will keep its position if possible.  Or Move backward to the new-end
26031             // if it's in the 'Y' range.
26032             element.pos = Math.min(element.pos, changeRangeNewEnd);
26033             // If the 'end' is after the change range, then we always adjust it by the delta
26034             // amount.  However, if the end is in the change range, then how we adjust it
26035             // will depend on if delta is positive or negative.  If delta is positive then we
26036             // have something like:
26037             //
26038             //  -------------------AAA-----------------
26039             //  -------------------BBBCCCCCCC-----------------
26040             //
26041             // In this case, we consider any node that ended inside the change range to keep its
26042             // end position.
26043             //
26044             // however, if the delta is negative, then we instead have something like this:
26045             //
26046             //  -------------------XXXYYYYYYY-----------------
26047             //  -------------------ZZZ-----------------
26048             //
26049             // In this case, any element that ended in the 'X' range will keep its position.
26050             // However any element that ended after that will have their pos adjusted to be
26051             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
26052             // be adjusted to have their end at the end of the 'Z' range.
26053             if (element.end >= changeRangeOldEnd) {
26054                 // Element ends after the change range.  Always adjust the end pos.
26055                 element.end += delta;
26056             }
26057             else {
26058                 // Element ends in the change range.  The element will keep its position if
26059                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
26060                 element.end = Math.min(element.end, changeRangeNewEnd);
26061             }
26062             ts.Debug.assert(element.pos <= element.end);
26063             if (element.parent) {
26064                 ts.Debug.assert(element.pos >= element.parent.pos);
26065                 ts.Debug.assert(element.end <= element.parent.end);
26066             }
26067         }
26068         function checkNodePositions(node, aggressiveChecks) {
26069             if (aggressiveChecks) {
26070                 var pos_2 = node.pos;
26071                 var visitNode_1 = function (child) {
26072                     ts.Debug.assert(child.pos >= pos_2);
26073                     pos_2 = child.end;
26074                 };
26075                 if (ts.hasJSDocNodes(node)) {
26076                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
26077                         var jsDocComment = _a[_i];
26078                         visitNode_1(jsDocComment);
26079                     }
26080                 }
26081                 forEachChild(node, visitNode_1);
26082                 ts.Debug.assert(pos_2 <= node.end);
26083             }
26084         }
26085         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
26086             visitNode(sourceFile);
26087             return;
26088             function visitNode(child) {
26089                 ts.Debug.assert(child.pos <= child.end);
26090                 if (child.pos > changeRangeOldEnd) {
26091                     // Node is entirely past the change range.  We need to move both its pos and
26092                     // end, forward or backward appropriately.
26093                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
26094                     return;
26095                 }
26096                 // Check if the element intersects the change range.  If it does, then it is not
26097                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
26098                 // be able to use.
26099                 var fullEnd = child.end;
26100                 if (fullEnd >= changeStart) {
26101                     child.intersectsChange = true;
26102                     child._children = undefined;
26103                     // Adjust the pos or end (or both) of the intersecting element accordingly.
26104                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
26105                     forEachChild(child, visitNode, visitArray);
26106                     if (ts.hasJSDocNodes(child)) {
26107                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
26108                             var jsDocComment = _a[_i];
26109                             visitNode(jsDocComment);
26110                         }
26111                     }
26112                     checkNodePositions(child, aggressiveChecks);
26113                     return;
26114                 }
26115                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
26116                 ts.Debug.assert(fullEnd < changeStart);
26117             }
26118             function visitArray(array) {
26119                 ts.Debug.assert(array.pos <= array.end);
26120                 if (array.pos > changeRangeOldEnd) {
26121                     // Array is entirely after the change range.  We need to move it, and move any of
26122                     // its children.
26123                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
26124                     return;
26125                 }
26126                 // Check if the element intersects the change range.  If it does, then it is not
26127                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
26128                 // be able to use.
26129                 var fullEnd = array.end;
26130                 if (fullEnd >= changeStart) {
26131                     array.intersectsChange = true;
26132                     array._children = undefined;
26133                     // Adjust the pos or end (or both) of the intersecting array accordingly.
26134                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
26135                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
26136                         var node = array_9[_i];
26137                         visitNode(node);
26138                     }
26139                     return;
26140                 }
26141                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
26142                 ts.Debug.assert(fullEnd < changeStart);
26143             }
26144         }
26145         function extendToAffectedRange(sourceFile, changeRange) {
26146             // Consider the following code:
26147             //      void foo() { /; }
26148             //
26149             // If the text changes with an insertion of / just before the semicolon then we end up with:
26150             //      void foo() { //; }
26151             //
26152             // If we were to just use the changeRange a is, then we would not rescan the { token
26153             // (as it does not intersect the actual original change range).  Because an edit may
26154             // change the token touching it, we actually need to look back *at least* one token so
26155             // that the prior token sees that change.
26156             var maxLookahead = 1;
26157             var start = changeRange.span.start;
26158             // the first iteration aligns us with the change start. subsequent iteration move us to
26159             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
26160             // start of the tree.
26161             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
26162                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
26163                 ts.Debug.assert(nearestNode.pos <= start);
26164                 var position = nearestNode.pos;
26165                 start = Math.max(0, position - 1);
26166             }
26167             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
26168             var finalLength = changeRange.newLength + (changeRange.span.start - start);
26169             return ts.createTextChangeRange(finalSpan, finalLength);
26170         }
26171         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
26172             var bestResult = sourceFile;
26173             var lastNodeEntirelyBeforePosition;
26174             forEachChild(sourceFile, visit);
26175             if (lastNodeEntirelyBeforePosition) {
26176                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
26177                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
26178                     bestResult = lastChildOfLastEntireNodeBeforePosition;
26179                 }
26180             }
26181             return bestResult;
26182             function getLastDescendant(node) {
26183                 while (true) {
26184                     var lastChild = ts.getLastChild(node);
26185                     if (lastChild) {
26186                         node = lastChild;
26187                     }
26188                     else {
26189                         return node;
26190                     }
26191                 }
26192             }
26193             function visit(child) {
26194                 if (ts.nodeIsMissing(child)) {
26195                     // Missing nodes are effectively invisible to us.  We never even consider them
26196                     // When trying to find the nearest node before us.
26197                     return;
26198                 }
26199                 // If the child intersects this position, then this node is currently the nearest
26200                 // node that starts before the position.
26201                 if (child.pos <= position) {
26202                     if (child.pos >= bestResult.pos) {
26203                         // This node starts before the position, and is closer to the position than
26204                         // the previous best node we found.  It is now the new best node.
26205                         bestResult = child;
26206                     }
26207                     // Now, the node may overlap the position, or it may end entirely before the
26208                     // position.  If it overlaps with the position, then either it, or one of its
26209                     // children must be the nearest node before the position.  So we can just
26210                     // recurse into this child to see if we can find something better.
26211                     if (position < child.end) {
26212                         // The nearest node is either this child, or one of the children inside
26213                         // of it.  We've already marked this child as the best so far.  Recurse
26214                         // in case one of the children is better.
26215                         forEachChild(child, visit);
26216                         // Once we look at the children of this node, then there's no need to
26217                         // continue any further.
26218                         return true;
26219                     }
26220                     else {
26221                         ts.Debug.assert(child.end <= position);
26222                         // The child ends entirely before this position.  Say you have the following
26223                         // (where $ is the position)
26224                         //
26225                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
26226                         //
26227                         // We would want to find the nearest preceding node in "complex expr 2".
26228                         // To support that, we keep track of this node, and once we're done searching
26229                         // for a best node, we recurse down this node to see if we can find a good
26230                         // result in it.
26231                         //
26232                         // This approach allows us to quickly skip over nodes that are entirely
26233                         // before the position, while still allowing us to find any nodes in the
26234                         // last one that might be what we want.
26235                         lastNodeEntirelyBeforePosition = child;
26236                     }
26237                 }
26238                 else {
26239                     ts.Debug.assert(child.pos > position);
26240                     // We're now at a node that is entirely past the position we're searching for.
26241                     // This node (and all following nodes) could never contribute to the result,
26242                     // so just skip them by returning 'true' here.
26243                     return true;
26244                 }
26245             }
26246         }
26247         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
26248             var oldText = sourceFile.text;
26249             if (textChangeRange) {
26250                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
26251                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
26252                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
26253                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
26254                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
26255                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
26256                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
26257                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
26258                 }
26259             }
26260         }
26261         function createSyntaxCursor(sourceFile) {
26262             var currentArray = sourceFile.statements;
26263             var currentArrayIndex = 0;
26264             ts.Debug.assert(currentArrayIndex < currentArray.length);
26265             var current = currentArray[currentArrayIndex];
26266             var lastQueriedPosition = -1 /* Value */;
26267             return {
26268                 currentNode: function (position) {
26269                     // Only compute the current node if the position is different than the last time
26270                     // we were asked.  The parser commonly asks for the node at the same position
26271                     // twice.  Once to know if can read an appropriate list element at a certain point,
26272                     // and then to actually read and consume the node.
26273                     if (position !== lastQueriedPosition) {
26274                         // Much of the time the parser will need the very next node in the array that
26275                         // we just returned a node from.So just simply check for that case and move
26276                         // forward in the array instead of searching for the node again.
26277                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
26278                             currentArrayIndex++;
26279                             current = currentArray[currentArrayIndex];
26280                         }
26281                         // If we don't have a node, or the node we have isn't in the right position,
26282                         // then try to find a viable node at the position requested.
26283                         if (!current || current.pos !== position) {
26284                             findHighestListElementThatStartsAtPosition(position);
26285                         }
26286                     }
26287                     // Cache this query so that we don't do any extra work if the parser calls back
26288                     // into us.  Note: this is very common as the parser will make pairs of calls like
26289                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
26290                     // called with 'isListElement', we don't want to redo the work when parseListElement
26291                     // is called immediately after.
26292                     lastQueriedPosition = position;
26293                     // Either we don'd have a node, or we have a node at the position being asked for.
26294                     ts.Debug.assert(!current || current.pos === position);
26295                     return current;
26296                 }
26297             };
26298             // Finds the highest element in the tree we can find that starts at the provided position.
26299             // The element must be a direct child of some node list in the tree.  This way after we
26300             // return it, we can easily return its next sibling in the list.
26301             function findHighestListElementThatStartsAtPosition(position) {
26302                 // Clear out any cached state about the last node we found.
26303                 currentArray = undefined;
26304                 currentArrayIndex = -1 /* Value */;
26305                 current = undefined;
26306                 // Recurse into the source file to find the highest node at this position.
26307                 forEachChild(sourceFile, visitNode, visitArray);
26308                 return;
26309                 function visitNode(node) {
26310                     if (position >= node.pos && position < node.end) {
26311                         // Position was within this node.  Keep searching deeper to find the node.
26312                         forEachChild(node, visitNode, visitArray);
26313                         // don't proceed any further in the search.
26314                         return true;
26315                     }
26316                     // position wasn't in this node, have to keep searching.
26317                     return false;
26318                 }
26319                 function visitArray(array) {
26320                     if (position >= array.pos && position < array.end) {
26321                         // position was in this array.  Search through this array to see if we find a
26322                         // viable element.
26323                         for (var i = 0; i < array.length; i++) {
26324                             var child = array[i];
26325                             if (child) {
26326                                 if (child.pos === position) {
26327                                     // Found the right node.  We're done.
26328                                     currentArray = array;
26329                                     currentArrayIndex = i;
26330                                     current = child;
26331                                     return true;
26332                                 }
26333                                 else {
26334                                     if (child.pos < position && position < child.end) {
26335                                         // Position in somewhere within this child.  Search in it and
26336                                         // stop searching in this array.
26337                                         forEachChild(child, visitNode, visitArray);
26338                                         return true;
26339                                     }
26340                                 }
26341                             }
26342                         }
26343                     }
26344                     // position wasn't in this array, have to keep searching.
26345                     return false;
26346                 }
26347             }
26348         }
26349         var InvalidPosition;
26350         (function (InvalidPosition) {
26351             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
26352         })(InvalidPosition || (InvalidPosition = {}));
26353     })(IncrementalParser || (IncrementalParser = {}));
26354     /** @internal */
26355     function isDeclarationFileName(fileName) {
26356         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
26357     }
26358     ts.isDeclarationFileName = isDeclarationFileName;
26359     /*@internal*/
26360     function processCommentPragmas(context, sourceText) {
26361         var pragmas = [];
26362         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
26363             var range = _a[_i];
26364             var comment = sourceText.substring(range.pos, range.end);
26365             extractPragmas(pragmas, range, comment);
26366         }
26367         context.pragmas = ts.createMap();
26368         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
26369             var pragma = pragmas_1[_b];
26370             if (context.pragmas.has(pragma.name)) {
26371                 var currentValue = context.pragmas.get(pragma.name);
26372                 if (currentValue instanceof Array) {
26373                     currentValue.push(pragma.args);
26374                 }
26375                 else {
26376                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
26377                 }
26378                 continue;
26379             }
26380             context.pragmas.set(pragma.name, pragma.args);
26381         }
26382     }
26383     ts.processCommentPragmas = processCommentPragmas;
26384     /*@internal*/
26385     function processPragmasIntoFields(context, reportDiagnostic) {
26386         context.checkJsDirective = undefined;
26387         context.referencedFiles = [];
26388         context.typeReferenceDirectives = [];
26389         context.libReferenceDirectives = [];
26390         context.amdDependencies = [];
26391         context.hasNoDefaultLib = false;
26392         context.pragmas.forEach(function (entryOrList, key) {
26393             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
26394             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
26395             switch (key) {
26396                 case "reference": {
26397                     var referencedFiles_1 = context.referencedFiles;
26398                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
26399                     var libReferenceDirectives_1 = context.libReferenceDirectives;
26400                     ts.forEach(ts.toArray(entryOrList), function (arg) {
26401                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
26402                         if (arg.arguments["no-default-lib"]) {
26403                             context.hasNoDefaultLib = true;
26404                         }
26405                         else if (types) {
26406                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
26407                         }
26408                         else if (lib) {
26409                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
26410                         }
26411                         else if (path) {
26412                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
26413                         }
26414                         else {
26415                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
26416                         }
26417                     });
26418                     break;
26419                 }
26420                 case "amd-dependency": {
26421                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
26422                     break;
26423                 }
26424                 case "amd-module": {
26425                     if (entryOrList instanceof Array) {
26426                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
26427                             var entry = entryOrList_1[_i];
26428                             if (context.moduleName) {
26429                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
26430                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
26431                             }
26432                             context.moduleName = entry.arguments.name;
26433                         }
26434                     }
26435                     else {
26436                         context.moduleName = entryOrList.arguments.name;
26437                     }
26438                     break;
26439                 }
26440                 case "ts-nocheck":
26441                 case "ts-check": {
26442                     // _last_ of either nocheck or check in a file is the "winner"
26443                     ts.forEach(ts.toArray(entryOrList), function (entry) {
26444                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
26445                             context.checkJsDirective = {
26446                                 enabled: key === "ts-check",
26447                                 end: entry.range.end,
26448                                 pos: entry.range.pos
26449                             };
26450                         }
26451                     });
26452                     break;
26453                 }
26454                 case "jsx": return; // Accessed directly
26455                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
26456             }
26457         });
26458     }
26459     ts.processPragmasIntoFields = processPragmasIntoFields;
26460     var namedArgRegExCache = ts.createMap();
26461     function getNamedArgRegEx(name) {
26462         if (namedArgRegExCache.has(name)) {
26463             return namedArgRegExCache.get(name);
26464         }
26465         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
26466         namedArgRegExCache.set(name, result);
26467         return result;
26468     }
26469     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
26470     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
26471     function extractPragmas(pragmas, range, text) {
26472         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
26473         if (tripleSlash) {
26474             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
26475             var pragma = ts.commentPragmas[name];
26476             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
26477                 return;
26478             }
26479             if (pragma.args) {
26480                 var argument = {};
26481                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
26482                     var arg = _a[_i];
26483                     var matcher = getNamedArgRegEx(arg.name);
26484                     var matchResult = matcher.exec(text);
26485                     if (!matchResult && !arg.optional) {
26486                         return; // Missing required argument, don't parse
26487                     }
26488                     else if (matchResult) {
26489                         if (arg.captureSpan) {
26490                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
26491                             argument[arg.name] = {
26492                                 value: matchResult[3],
26493                                 pos: startPos,
26494                                 end: startPos + matchResult[3].length
26495                             };
26496                         }
26497                         else {
26498                             argument[arg.name] = matchResult[3];
26499                         }
26500                     }
26501                 }
26502                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
26503             }
26504             else {
26505                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
26506             }
26507             return;
26508         }
26509         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
26510         if (singleLine) {
26511             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
26512         }
26513         if (range.kind === 3 /* MultiLineCommentTrivia */) {
26514             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
26515             var multiLineMatch = void 0;
26516             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
26517                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
26518             }
26519         }
26520     }
26521     function addPragmaForMatch(pragmas, range, kind, match) {
26522         if (!match)
26523             return;
26524         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
26525         var pragma = ts.commentPragmas[name];
26526         if (!pragma || !(pragma.kind & kind)) {
26527             return;
26528         }
26529         var args = match[2]; // Split on spaces and match up positionally with definition
26530         var argument = getNamedPragmaArguments(pragma, args);
26531         if (argument === "fail")
26532             return; // Missing required argument, fail to parse it
26533         pragmas.push({ name: name, args: { arguments: argument, range: range } });
26534         return;
26535     }
26536     function getNamedPragmaArguments(pragma, text) {
26537         if (!text)
26538             return {};
26539         if (!pragma.args)
26540             return {};
26541         var args = text.split(/\s+/);
26542         var argMap = {};
26543         for (var i = 0; i < pragma.args.length; i++) {
26544             var argument = pragma.args[i];
26545             if (!args[i] && !argument.optional) {
26546                 return "fail";
26547             }
26548             if (argument.captureSpan) {
26549                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
26550             }
26551             argMap[argument.name] = args[i];
26552         }
26553         return argMap;
26554     }
26555     /** @internal */
26556     function tagNamesAreEquivalent(lhs, rhs) {
26557         if (lhs.kind !== rhs.kind) {
26558             return false;
26559         }
26560         if (lhs.kind === 75 /* Identifier */) {
26561             return lhs.escapedText === rhs.escapedText;
26562         }
26563         if (lhs.kind === 104 /* ThisKeyword */) {
26564             return true;
26565         }
26566         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
26567         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
26568         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
26569         return lhs.name.escapedText === rhs.name.escapedText &&
26570             tagNamesAreEquivalent(lhs.expression, rhs.expression);
26571     }
26572     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
26573 })(ts || (ts = {}));
26574 var ts;
26575 (function (ts) {
26576     /* @internal */
26577     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
26578     // NOTE: The order here is important to default lib ordering as entries will have the same
26579     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
26580     //       order also affects overload resolution when a type declared in one lib is
26581     //       augmented in another lib.
26582     var libEntries = [
26583         // JavaScript only
26584         ["es5", "lib.es5.d.ts"],
26585         ["es6", "lib.es2015.d.ts"],
26586         ["es2015", "lib.es2015.d.ts"],
26587         ["es7", "lib.es2016.d.ts"],
26588         ["es2016", "lib.es2016.d.ts"],
26589         ["es2017", "lib.es2017.d.ts"],
26590         ["es2018", "lib.es2018.d.ts"],
26591         ["es2019", "lib.es2019.d.ts"],
26592         ["es2020", "lib.es2020.d.ts"],
26593         ["esnext", "lib.esnext.d.ts"],
26594         // Host only
26595         ["dom", "lib.dom.d.ts"],
26596         ["dom.iterable", "lib.dom.iterable.d.ts"],
26597         ["webworker", "lib.webworker.d.ts"],
26598         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
26599         ["scripthost", "lib.scripthost.d.ts"],
26600         // ES2015 Or ESNext By-feature options
26601         ["es2015.core", "lib.es2015.core.d.ts"],
26602         ["es2015.collection", "lib.es2015.collection.d.ts"],
26603         ["es2015.generator", "lib.es2015.generator.d.ts"],
26604         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
26605         ["es2015.promise", "lib.es2015.promise.d.ts"],
26606         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
26607         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
26608         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
26609         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
26610         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
26611         ["es2017.object", "lib.es2017.object.d.ts"],
26612         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
26613         ["es2017.string", "lib.es2017.string.d.ts"],
26614         ["es2017.intl", "lib.es2017.intl.d.ts"],
26615         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
26616         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
26617         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
26618         ["es2018.intl", "lib.es2018.intl.d.ts"],
26619         ["es2018.promise", "lib.es2018.promise.d.ts"],
26620         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
26621         ["es2019.array", "lib.es2019.array.d.ts"],
26622         ["es2019.object", "lib.es2019.object.d.ts"],
26623         ["es2019.string", "lib.es2019.string.d.ts"],
26624         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
26625         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
26626         ["es2020.promise", "lib.es2020.promise.d.ts"],
26627         ["es2020.string", "lib.es2020.string.d.ts"],
26628         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
26629         ["esnext.array", "lib.es2019.array.d.ts"],
26630         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
26631         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
26632         ["esnext.intl", "lib.esnext.intl.d.ts"],
26633         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
26634         ["esnext.string", "lib.esnext.string.d.ts"],
26635         ["esnext.promise", "lib.esnext.promise.d.ts"]
26636     ];
26637     /**
26638      * An array of supported "lib" reference file names used to determine the order for inclusion
26639      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
26640      * overload resolution when a type declared in one lib is extended by another.
26641      */
26642     /* @internal */
26643     ts.libs = libEntries.map(function (entry) { return entry[0]; });
26644     /**
26645      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
26646      * option as well as for resolving lib reference directives.
26647      */
26648     /* @internal */
26649     ts.libMap = ts.createMapFromEntries(libEntries);
26650     // Watch related options
26651     /* @internal */
26652     ts.optionsForWatch = [
26653         {
26654             name: "watchFile",
26655             type: ts.createMapFromTemplate({
26656                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
26657                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
26658                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
26659                 usefsevents: ts.WatchFileKind.UseFsEvents,
26660                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
26661             }),
26662             category: ts.Diagnostics.Advanced_Options,
26663             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
26664         },
26665         {
26666             name: "watchDirectory",
26667             type: ts.createMapFromTemplate({
26668                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
26669                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
26670                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
26671             }),
26672             category: ts.Diagnostics.Advanced_Options,
26673             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
26674         },
26675         {
26676             name: "fallbackPolling",
26677             type: ts.createMapFromTemplate({
26678                 fixedinterval: ts.PollingWatchKind.FixedInterval,
26679                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
26680                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
26681             }),
26682             category: ts.Diagnostics.Advanced_Options,
26683             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
26684         },
26685         {
26686             name: "synchronousWatchDirectory",
26687             type: "boolean",
26688             category: ts.Diagnostics.Advanced_Options,
26689             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
26690         },
26691     ];
26692     /* @internal */
26693     ts.commonOptionsWithBuild = [
26694         {
26695             name: "help",
26696             shortName: "h",
26697             type: "boolean",
26698             showInSimplifiedHelpView: true,
26699             category: ts.Diagnostics.Command_line_Options,
26700             description: ts.Diagnostics.Print_this_message,
26701         },
26702         {
26703             name: "help",
26704             shortName: "?",
26705             type: "boolean"
26706         },
26707         {
26708             name: "watch",
26709             shortName: "w",
26710             type: "boolean",
26711             showInSimplifiedHelpView: true,
26712             category: ts.Diagnostics.Command_line_Options,
26713             description: ts.Diagnostics.Watch_input_files,
26714         },
26715         {
26716             name: "preserveWatchOutput",
26717             type: "boolean",
26718             showInSimplifiedHelpView: false,
26719             category: ts.Diagnostics.Command_line_Options,
26720             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
26721         },
26722         {
26723             name: "listFiles",
26724             type: "boolean",
26725             category: ts.Diagnostics.Advanced_Options,
26726             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
26727         },
26728         {
26729             name: "listEmittedFiles",
26730             type: "boolean",
26731             category: ts.Diagnostics.Advanced_Options,
26732             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
26733         },
26734         {
26735             name: "pretty",
26736             type: "boolean",
26737             showInSimplifiedHelpView: true,
26738             category: ts.Diagnostics.Command_line_Options,
26739             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
26740         },
26741         {
26742             name: "traceResolution",
26743             type: "boolean",
26744             category: ts.Diagnostics.Advanced_Options,
26745             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
26746         },
26747         {
26748             name: "diagnostics",
26749             type: "boolean",
26750             category: ts.Diagnostics.Advanced_Options,
26751             description: ts.Diagnostics.Show_diagnostic_information
26752         },
26753         {
26754             name: "extendedDiagnostics",
26755             type: "boolean",
26756             category: ts.Diagnostics.Advanced_Options,
26757             description: ts.Diagnostics.Show_verbose_diagnostic_information
26758         },
26759         {
26760             name: "generateCpuProfile",
26761             type: "string",
26762             isFilePath: true,
26763             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26764             category: ts.Diagnostics.Advanced_Options,
26765             description: ts.Diagnostics.Generates_a_CPU_profile
26766         },
26767         {
26768             name: "incremental",
26769             shortName: "i",
26770             type: "boolean",
26771             category: ts.Diagnostics.Basic_Options,
26772             description: ts.Diagnostics.Enable_incremental_compilation,
26773             transpileOptionValue: undefined
26774         },
26775         {
26776             name: "assumeChangesOnlyAffectDirectDependencies",
26777             type: "boolean",
26778             affectsSemanticDiagnostics: true,
26779             affectsEmit: true,
26780             category: ts.Diagnostics.Advanced_Options,
26781             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
26782         },
26783         {
26784             name: "locale",
26785             type: "string",
26786             category: ts.Diagnostics.Advanced_Options,
26787             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
26788         },
26789     ];
26790     /* @internal */
26791     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
26792         {
26793             name: "all",
26794             type: "boolean",
26795             showInSimplifiedHelpView: true,
26796             category: ts.Diagnostics.Command_line_Options,
26797             description: ts.Diagnostics.Show_all_compiler_options,
26798         },
26799         {
26800             name: "version",
26801             shortName: "v",
26802             type: "boolean",
26803             showInSimplifiedHelpView: true,
26804             category: ts.Diagnostics.Command_line_Options,
26805             description: ts.Diagnostics.Print_the_compiler_s_version,
26806         },
26807         {
26808             name: "init",
26809             type: "boolean",
26810             showInSimplifiedHelpView: true,
26811             category: ts.Diagnostics.Command_line_Options,
26812             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
26813         },
26814         {
26815             name: "project",
26816             shortName: "p",
26817             type: "string",
26818             isFilePath: true,
26819             showInSimplifiedHelpView: true,
26820             category: ts.Diagnostics.Command_line_Options,
26821             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26822             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
26823         },
26824         {
26825             name: "build",
26826             type: "boolean",
26827             shortName: "b",
26828             showInSimplifiedHelpView: true,
26829             category: ts.Diagnostics.Command_line_Options,
26830             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
26831         },
26832         {
26833             name: "showConfig",
26834             type: "boolean",
26835             category: ts.Diagnostics.Command_line_Options,
26836             isCommandLineOnly: true,
26837             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
26838         },
26839         {
26840             name: "listFilesOnly",
26841             type: "boolean",
26842             category: ts.Diagnostics.Command_line_Options,
26843             affectsSemanticDiagnostics: true,
26844             affectsEmit: true,
26845             isCommandLineOnly: true,
26846             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
26847         },
26848         // Basic
26849         {
26850             name: "target",
26851             shortName: "t",
26852             type: ts.createMapFromTemplate({
26853                 es3: 0 /* ES3 */,
26854                 es5: 1 /* ES5 */,
26855                 es6: 2 /* ES2015 */,
26856                 es2015: 2 /* ES2015 */,
26857                 es2016: 3 /* ES2016 */,
26858                 es2017: 4 /* ES2017 */,
26859                 es2018: 5 /* ES2018 */,
26860                 es2019: 6 /* ES2019 */,
26861                 es2020: 7 /* ES2020 */,
26862                 esnext: 99 /* ESNext */,
26863             }),
26864             affectsSourceFile: true,
26865             affectsModuleResolution: true,
26866             affectsEmit: true,
26867             paramType: ts.Diagnostics.VERSION,
26868             showInSimplifiedHelpView: true,
26869             category: ts.Diagnostics.Basic_Options,
26870             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
26871         },
26872         {
26873             name: "module",
26874             shortName: "m",
26875             type: ts.createMapFromTemplate({
26876                 none: ts.ModuleKind.None,
26877                 commonjs: ts.ModuleKind.CommonJS,
26878                 amd: ts.ModuleKind.AMD,
26879                 system: ts.ModuleKind.System,
26880                 umd: ts.ModuleKind.UMD,
26881                 es6: ts.ModuleKind.ES2015,
26882                 es2015: ts.ModuleKind.ES2015,
26883                 es2020: ts.ModuleKind.ES2020,
26884                 esnext: ts.ModuleKind.ESNext
26885             }),
26886             affectsModuleResolution: true,
26887             affectsEmit: true,
26888             paramType: ts.Diagnostics.KIND,
26889             showInSimplifiedHelpView: true,
26890             category: ts.Diagnostics.Basic_Options,
26891             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
26892         },
26893         {
26894             name: "lib",
26895             type: "list",
26896             element: {
26897                 name: "lib",
26898                 type: ts.libMap
26899             },
26900             affectsModuleResolution: true,
26901             showInSimplifiedHelpView: true,
26902             category: ts.Diagnostics.Basic_Options,
26903             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
26904             transpileOptionValue: undefined
26905         },
26906         {
26907             name: "allowJs",
26908             type: "boolean",
26909             affectsModuleResolution: true,
26910             showInSimplifiedHelpView: true,
26911             category: ts.Diagnostics.Basic_Options,
26912             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
26913         },
26914         {
26915             name: "checkJs",
26916             type: "boolean",
26917             category: ts.Diagnostics.Basic_Options,
26918             description: ts.Diagnostics.Report_errors_in_js_files
26919         },
26920         {
26921             name: "jsx",
26922             type: ts.createMapFromTemplate({
26923                 "preserve": 1 /* Preserve */,
26924                 "react-native": 3 /* ReactNative */,
26925                 "react": 2 /* React */
26926             }),
26927             affectsSourceFile: true,
26928             paramType: ts.Diagnostics.KIND,
26929             showInSimplifiedHelpView: true,
26930             category: ts.Diagnostics.Basic_Options,
26931             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
26932         },
26933         {
26934             name: "declaration",
26935             shortName: "d",
26936             type: "boolean",
26937             affectsEmit: true,
26938             showInSimplifiedHelpView: true,
26939             category: ts.Diagnostics.Basic_Options,
26940             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
26941             transpileOptionValue: undefined
26942         },
26943         {
26944             name: "declarationMap",
26945             type: "boolean",
26946             affectsEmit: true,
26947             showInSimplifiedHelpView: true,
26948             category: ts.Diagnostics.Basic_Options,
26949             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
26950             transpileOptionValue: undefined
26951         },
26952         {
26953             name: "emitDeclarationOnly",
26954             type: "boolean",
26955             affectsEmit: true,
26956             category: ts.Diagnostics.Advanced_Options,
26957             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
26958             transpileOptionValue: undefined
26959         },
26960         {
26961             name: "sourceMap",
26962             type: "boolean",
26963             affectsEmit: true,
26964             showInSimplifiedHelpView: true,
26965             category: ts.Diagnostics.Basic_Options,
26966             description: ts.Diagnostics.Generates_corresponding_map_file,
26967         },
26968         {
26969             name: "outFile",
26970             type: "string",
26971             affectsEmit: true,
26972             isFilePath: true,
26973             paramType: ts.Diagnostics.FILE,
26974             showInSimplifiedHelpView: true,
26975             category: ts.Diagnostics.Basic_Options,
26976             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
26977             transpileOptionValue: undefined
26978         },
26979         {
26980             name: "outDir",
26981             type: "string",
26982             affectsEmit: true,
26983             isFilePath: true,
26984             paramType: ts.Diagnostics.DIRECTORY,
26985             showInSimplifiedHelpView: true,
26986             category: ts.Diagnostics.Basic_Options,
26987             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
26988         },
26989         {
26990             name: "rootDir",
26991             type: "string",
26992             affectsEmit: true,
26993             isFilePath: true,
26994             paramType: ts.Diagnostics.LOCATION,
26995             category: ts.Diagnostics.Basic_Options,
26996             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
26997         },
26998         {
26999             name: "composite",
27000             type: "boolean",
27001             affectsEmit: true,
27002             isTSConfigOnly: true,
27003             category: ts.Diagnostics.Basic_Options,
27004             description: ts.Diagnostics.Enable_project_compilation,
27005             transpileOptionValue: undefined
27006         },
27007         {
27008             name: "tsBuildInfoFile",
27009             type: "string",
27010             affectsEmit: true,
27011             isFilePath: true,
27012             paramType: ts.Diagnostics.FILE,
27013             category: ts.Diagnostics.Basic_Options,
27014             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
27015             transpileOptionValue: undefined
27016         },
27017         {
27018             name: "removeComments",
27019             type: "boolean",
27020             affectsEmit: true,
27021             showInSimplifiedHelpView: true,
27022             category: ts.Diagnostics.Basic_Options,
27023             description: ts.Diagnostics.Do_not_emit_comments_to_output,
27024         },
27025         {
27026             name: "noEmit",
27027             type: "boolean",
27028             affectsEmit: true,
27029             showInSimplifiedHelpView: true,
27030             category: ts.Diagnostics.Basic_Options,
27031             description: ts.Diagnostics.Do_not_emit_outputs,
27032             transpileOptionValue: undefined
27033         },
27034         {
27035             name: "importHelpers",
27036             type: "boolean",
27037             affectsEmit: true,
27038             category: ts.Diagnostics.Basic_Options,
27039             description: ts.Diagnostics.Import_emit_helpers_from_tslib
27040         },
27041         {
27042             name: "importsNotUsedAsValues",
27043             type: ts.createMapFromTemplate({
27044                 remove: 0 /* Remove */,
27045                 preserve: 1 /* Preserve */,
27046                 error: 2 /* Error */
27047             }),
27048             affectsEmit: true,
27049             affectsSemanticDiagnostics: true,
27050             category: ts.Diagnostics.Advanced_Options,
27051             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
27052         },
27053         {
27054             name: "downlevelIteration",
27055             type: "boolean",
27056             affectsEmit: true,
27057             category: ts.Diagnostics.Basic_Options,
27058             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
27059         },
27060         {
27061             name: "isolatedModules",
27062             type: "boolean",
27063             category: ts.Diagnostics.Basic_Options,
27064             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
27065             transpileOptionValue: true
27066         },
27067         // Strict Type Checks
27068         {
27069             name: "strict",
27070             type: "boolean",
27071             showInSimplifiedHelpView: true,
27072             category: ts.Diagnostics.Strict_Type_Checking_Options,
27073             description: ts.Diagnostics.Enable_all_strict_type_checking_options
27074         },
27075         {
27076             name: "noImplicitAny",
27077             type: "boolean",
27078             affectsSemanticDiagnostics: true,
27079             strictFlag: true,
27080             showInSimplifiedHelpView: true,
27081             category: ts.Diagnostics.Strict_Type_Checking_Options,
27082             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
27083         },
27084         {
27085             name: "strictNullChecks",
27086             type: "boolean",
27087             affectsSemanticDiagnostics: true,
27088             strictFlag: true,
27089             showInSimplifiedHelpView: true,
27090             category: ts.Diagnostics.Strict_Type_Checking_Options,
27091             description: ts.Diagnostics.Enable_strict_null_checks
27092         },
27093         {
27094             name: "strictFunctionTypes",
27095             type: "boolean",
27096             affectsSemanticDiagnostics: true,
27097             strictFlag: true,
27098             showInSimplifiedHelpView: true,
27099             category: ts.Diagnostics.Strict_Type_Checking_Options,
27100             description: ts.Diagnostics.Enable_strict_checking_of_function_types
27101         },
27102         {
27103             name: "strictBindCallApply",
27104             type: "boolean",
27105             strictFlag: true,
27106             showInSimplifiedHelpView: true,
27107             category: ts.Diagnostics.Strict_Type_Checking_Options,
27108             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
27109         },
27110         {
27111             name: "strictPropertyInitialization",
27112             type: "boolean",
27113             affectsSemanticDiagnostics: true,
27114             strictFlag: true,
27115             showInSimplifiedHelpView: true,
27116             category: ts.Diagnostics.Strict_Type_Checking_Options,
27117             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
27118         },
27119         {
27120             name: "noImplicitThis",
27121             type: "boolean",
27122             affectsSemanticDiagnostics: true,
27123             strictFlag: true,
27124             showInSimplifiedHelpView: true,
27125             category: ts.Diagnostics.Strict_Type_Checking_Options,
27126             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
27127         },
27128         {
27129             name: "alwaysStrict",
27130             type: "boolean",
27131             affectsSourceFile: true,
27132             strictFlag: true,
27133             showInSimplifiedHelpView: true,
27134             category: ts.Diagnostics.Strict_Type_Checking_Options,
27135             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
27136         },
27137         // Additional Checks
27138         {
27139             name: "noUnusedLocals",
27140             type: "boolean",
27141             affectsSemanticDiagnostics: true,
27142             showInSimplifiedHelpView: true,
27143             category: ts.Diagnostics.Additional_Checks,
27144             description: ts.Diagnostics.Report_errors_on_unused_locals,
27145         },
27146         {
27147             name: "noUnusedParameters",
27148             type: "boolean",
27149             affectsSemanticDiagnostics: true,
27150             showInSimplifiedHelpView: true,
27151             category: ts.Diagnostics.Additional_Checks,
27152             description: ts.Diagnostics.Report_errors_on_unused_parameters,
27153         },
27154         {
27155             name: "noImplicitReturns",
27156             type: "boolean",
27157             affectsSemanticDiagnostics: true,
27158             showInSimplifiedHelpView: true,
27159             category: ts.Diagnostics.Additional_Checks,
27160             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
27161         },
27162         {
27163             name: "noFallthroughCasesInSwitch",
27164             type: "boolean",
27165             affectsBindDiagnostics: true,
27166             affectsSemanticDiagnostics: true,
27167             showInSimplifiedHelpView: true,
27168             category: ts.Diagnostics.Additional_Checks,
27169             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
27170         },
27171         // Module Resolution
27172         {
27173             name: "moduleResolution",
27174             type: ts.createMapFromTemplate({
27175                 node: ts.ModuleResolutionKind.NodeJs,
27176                 classic: ts.ModuleResolutionKind.Classic,
27177             }),
27178             affectsModuleResolution: true,
27179             paramType: ts.Diagnostics.STRATEGY,
27180             category: ts.Diagnostics.Module_Resolution_Options,
27181             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
27182         },
27183         {
27184             name: "baseUrl",
27185             type: "string",
27186             affectsModuleResolution: true,
27187             isFilePath: true,
27188             category: ts.Diagnostics.Module_Resolution_Options,
27189             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
27190         },
27191         {
27192             // this option can only be specified in tsconfig.json
27193             // use type = object to copy the value as-is
27194             name: "paths",
27195             type: "object",
27196             affectsModuleResolution: true,
27197             isTSConfigOnly: true,
27198             category: ts.Diagnostics.Module_Resolution_Options,
27199             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
27200             transpileOptionValue: undefined
27201         },
27202         {
27203             // this option can only be specified in tsconfig.json
27204             // use type = object to copy the value as-is
27205             name: "rootDirs",
27206             type: "list",
27207             isTSConfigOnly: true,
27208             element: {
27209                 name: "rootDirs",
27210                 type: "string",
27211                 isFilePath: true
27212             },
27213             affectsModuleResolution: true,
27214             category: ts.Diagnostics.Module_Resolution_Options,
27215             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
27216             transpileOptionValue: undefined
27217         },
27218         {
27219             name: "typeRoots",
27220             type: "list",
27221             element: {
27222                 name: "typeRoots",
27223                 type: "string",
27224                 isFilePath: true
27225             },
27226             affectsModuleResolution: true,
27227             category: ts.Diagnostics.Module_Resolution_Options,
27228             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
27229         },
27230         {
27231             name: "types",
27232             type: "list",
27233             element: {
27234                 name: "types",
27235                 type: "string"
27236             },
27237             affectsModuleResolution: true,
27238             showInSimplifiedHelpView: true,
27239             category: ts.Diagnostics.Module_Resolution_Options,
27240             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
27241             transpileOptionValue: undefined
27242         },
27243         {
27244             name: "allowSyntheticDefaultImports",
27245             type: "boolean",
27246             affectsSemanticDiagnostics: true,
27247             category: ts.Diagnostics.Module_Resolution_Options,
27248             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
27249         },
27250         {
27251             name: "esModuleInterop",
27252             type: "boolean",
27253             affectsSemanticDiagnostics: true,
27254             affectsEmit: true,
27255             showInSimplifiedHelpView: true,
27256             category: ts.Diagnostics.Module_Resolution_Options,
27257             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
27258         },
27259         {
27260             name: "preserveSymlinks",
27261             type: "boolean",
27262             category: ts.Diagnostics.Module_Resolution_Options,
27263             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
27264         },
27265         {
27266             name: "allowUmdGlobalAccess",
27267             type: "boolean",
27268             affectsSemanticDiagnostics: true,
27269             category: ts.Diagnostics.Module_Resolution_Options,
27270             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
27271         },
27272         // Source Maps
27273         {
27274             name: "sourceRoot",
27275             type: "string",
27276             affectsEmit: true,
27277             paramType: ts.Diagnostics.LOCATION,
27278             category: ts.Diagnostics.Source_Map_Options,
27279             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
27280         },
27281         {
27282             name: "mapRoot",
27283             type: "string",
27284             affectsEmit: true,
27285             paramType: ts.Diagnostics.LOCATION,
27286             category: ts.Diagnostics.Source_Map_Options,
27287             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
27288         },
27289         {
27290             name: "inlineSourceMap",
27291             type: "boolean",
27292             affectsEmit: true,
27293             category: ts.Diagnostics.Source_Map_Options,
27294             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
27295         },
27296         {
27297             name: "inlineSources",
27298             type: "boolean",
27299             affectsEmit: true,
27300             category: ts.Diagnostics.Source_Map_Options,
27301             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
27302         },
27303         // Experimental
27304         {
27305             name: "experimentalDecorators",
27306             type: "boolean",
27307             affectsSemanticDiagnostics: true,
27308             category: ts.Diagnostics.Experimental_Options,
27309             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
27310         },
27311         {
27312             name: "emitDecoratorMetadata",
27313             type: "boolean",
27314             affectsSemanticDiagnostics: true,
27315             affectsEmit: true,
27316             category: ts.Diagnostics.Experimental_Options,
27317             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
27318         },
27319         // Advanced
27320         {
27321             name: "jsxFactory",
27322             type: "string",
27323             category: ts.Diagnostics.Advanced_Options,
27324             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
27325         },
27326         {
27327             name: "resolveJsonModule",
27328             type: "boolean",
27329             affectsModuleResolution: true,
27330             category: ts.Diagnostics.Advanced_Options,
27331             description: ts.Diagnostics.Include_modules_imported_with_json_extension
27332         },
27333         {
27334             name: "out",
27335             type: "string",
27336             affectsEmit: true,
27337             isFilePath: false,
27338             // for correct behaviour, please use outFile
27339             category: ts.Diagnostics.Advanced_Options,
27340             paramType: ts.Diagnostics.FILE,
27341             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
27342             transpileOptionValue: undefined
27343         },
27344         {
27345             name: "reactNamespace",
27346             type: "string",
27347             affectsEmit: true,
27348             category: ts.Diagnostics.Advanced_Options,
27349             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
27350         },
27351         {
27352             name: "skipDefaultLibCheck",
27353             type: "boolean",
27354             category: ts.Diagnostics.Advanced_Options,
27355             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
27356         },
27357         {
27358             name: "charset",
27359             type: "string",
27360             category: ts.Diagnostics.Advanced_Options,
27361             description: ts.Diagnostics.The_character_set_of_the_input_files
27362         },
27363         {
27364             name: "emitBOM",
27365             type: "boolean",
27366             affectsEmit: true,
27367             category: ts.Diagnostics.Advanced_Options,
27368             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
27369         },
27370         {
27371             name: "newLine",
27372             type: ts.createMapFromTemplate({
27373                 crlf: 0 /* CarriageReturnLineFeed */,
27374                 lf: 1 /* LineFeed */
27375             }),
27376             affectsEmit: true,
27377             paramType: ts.Diagnostics.NEWLINE,
27378             category: ts.Diagnostics.Advanced_Options,
27379             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
27380         },
27381         {
27382             name: "noErrorTruncation",
27383             type: "boolean",
27384             affectsSemanticDiagnostics: true,
27385             category: ts.Diagnostics.Advanced_Options,
27386             description: ts.Diagnostics.Do_not_truncate_error_messages
27387         },
27388         {
27389             name: "noLib",
27390             type: "boolean",
27391             affectsModuleResolution: true,
27392             category: ts.Diagnostics.Advanced_Options,
27393             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
27394             // We are not returning a sourceFile for lib file when asked by the program,
27395             // so pass --noLib to avoid reporting a file not found error.
27396             transpileOptionValue: true
27397         },
27398         {
27399             name: "noResolve",
27400             type: "boolean",
27401             affectsModuleResolution: true,
27402             category: ts.Diagnostics.Advanced_Options,
27403             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
27404             // We are not doing a full typecheck, we are not resolving the whole context,
27405             // so pass --noResolve to avoid reporting missing file errors.
27406             transpileOptionValue: true
27407         },
27408         {
27409             name: "stripInternal",
27410             type: "boolean",
27411             affectsEmit: true,
27412             category: ts.Diagnostics.Advanced_Options,
27413             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
27414         },
27415         {
27416             name: "disableSizeLimit",
27417             type: "boolean",
27418             affectsSourceFile: true,
27419             category: ts.Diagnostics.Advanced_Options,
27420             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
27421         },
27422         {
27423             name: "disableSourceOfProjectReferenceRedirect",
27424             type: "boolean",
27425             isTSConfigOnly: true,
27426             category: ts.Diagnostics.Advanced_Options,
27427             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
27428         },
27429         {
27430             name: "disableSolutionSearching",
27431             type: "boolean",
27432             isTSConfigOnly: true,
27433             category: ts.Diagnostics.Advanced_Options,
27434             description: ts.Diagnostics.Disable_solution_searching_for_this_project
27435         },
27436         {
27437             name: "noImplicitUseStrict",
27438             type: "boolean",
27439             affectsSemanticDiagnostics: true,
27440             category: ts.Diagnostics.Advanced_Options,
27441             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
27442         },
27443         {
27444             name: "noEmitHelpers",
27445             type: "boolean",
27446             affectsEmit: true,
27447             category: ts.Diagnostics.Advanced_Options,
27448             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
27449         },
27450         {
27451             name: "noEmitOnError",
27452             type: "boolean",
27453             affectsEmit: true,
27454             category: ts.Diagnostics.Advanced_Options,
27455             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
27456             transpileOptionValue: undefined
27457         },
27458         {
27459             name: "preserveConstEnums",
27460             type: "boolean",
27461             affectsEmit: true,
27462             category: ts.Diagnostics.Advanced_Options,
27463             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
27464         },
27465         {
27466             name: "declarationDir",
27467             type: "string",
27468             affectsEmit: true,
27469             isFilePath: true,
27470             paramType: ts.Diagnostics.DIRECTORY,
27471             category: ts.Diagnostics.Advanced_Options,
27472             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
27473             transpileOptionValue: undefined
27474         },
27475         {
27476             name: "skipLibCheck",
27477             type: "boolean",
27478             category: ts.Diagnostics.Advanced_Options,
27479             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
27480         },
27481         {
27482             name: "allowUnusedLabels",
27483             type: "boolean",
27484             affectsBindDiagnostics: true,
27485             affectsSemanticDiagnostics: true,
27486             category: ts.Diagnostics.Advanced_Options,
27487             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
27488         },
27489         {
27490             name: "allowUnreachableCode",
27491             type: "boolean",
27492             affectsBindDiagnostics: true,
27493             affectsSemanticDiagnostics: true,
27494             category: ts.Diagnostics.Advanced_Options,
27495             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
27496         },
27497         {
27498             name: "suppressExcessPropertyErrors",
27499             type: "boolean",
27500             affectsSemanticDiagnostics: true,
27501             category: ts.Diagnostics.Advanced_Options,
27502             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
27503         },
27504         {
27505             name: "suppressImplicitAnyIndexErrors",
27506             type: "boolean",
27507             affectsSemanticDiagnostics: true,
27508             category: ts.Diagnostics.Advanced_Options,
27509             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
27510         },
27511         {
27512             name: "forceConsistentCasingInFileNames",
27513             type: "boolean",
27514             affectsModuleResolution: true,
27515             category: ts.Diagnostics.Advanced_Options,
27516             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
27517         },
27518         {
27519             name: "maxNodeModuleJsDepth",
27520             type: "number",
27521             affectsModuleResolution: true,
27522             category: ts.Diagnostics.Advanced_Options,
27523             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
27524         },
27525         {
27526             name: "noStrictGenericChecks",
27527             type: "boolean",
27528             affectsSemanticDiagnostics: true,
27529             category: ts.Diagnostics.Advanced_Options,
27530             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
27531         },
27532         {
27533             name: "useDefineForClassFields",
27534             type: "boolean",
27535             affectsSemanticDiagnostics: true,
27536             affectsEmit: true,
27537             category: ts.Diagnostics.Advanced_Options,
27538             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
27539         },
27540         {
27541             name: "keyofStringsOnly",
27542             type: "boolean",
27543             category: ts.Diagnostics.Advanced_Options,
27544             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
27545         },
27546         {
27547             // A list of plugins to load in the language service
27548             name: "plugins",
27549             type: "list",
27550             isTSConfigOnly: true,
27551             element: {
27552                 name: "plugin",
27553                 type: "object"
27554             },
27555             description: ts.Diagnostics.List_of_language_service_plugins
27556         },
27557     ]);
27558     /* @internal */
27559     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
27560     /* @internal */
27561     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
27562     /* @internal */
27563     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
27564     /* @internal */
27565     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
27566         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
27567     });
27568     /* @internal */
27569     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
27570         return ts.hasProperty(option, "transpileOptionValue");
27571     });
27572     /* @internal */
27573     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
27574         {
27575             name: "verbose",
27576             shortName: "v",
27577             category: ts.Diagnostics.Command_line_Options,
27578             description: ts.Diagnostics.Enable_verbose_logging,
27579             type: "boolean"
27580         },
27581         {
27582             name: "dry",
27583             shortName: "d",
27584             category: ts.Diagnostics.Command_line_Options,
27585             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
27586             type: "boolean"
27587         },
27588         {
27589             name: "force",
27590             shortName: "f",
27591             category: ts.Diagnostics.Command_line_Options,
27592             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
27593             type: "boolean"
27594         },
27595         {
27596             name: "clean",
27597             category: ts.Diagnostics.Command_line_Options,
27598             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
27599             type: "boolean"
27600         }
27601     ]);
27602     /* @internal */
27603     ts.typeAcquisitionDeclarations = [
27604         {
27605             /* @deprecated typingOptions.enableAutoDiscovery
27606              * Use typeAcquisition.enable instead.
27607              */
27608             name: "enableAutoDiscovery",
27609             type: "boolean",
27610         },
27611         {
27612             name: "enable",
27613             type: "boolean",
27614         },
27615         {
27616             name: "include",
27617             type: "list",
27618             element: {
27619                 name: "include",
27620                 type: "string"
27621             }
27622         },
27623         {
27624             name: "exclude",
27625             type: "list",
27626             element: {
27627                 name: "exclude",
27628                 type: "string"
27629             }
27630         }
27631     ];
27632     /*@internal*/
27633     function createOptionNameMap(optionDeclarations) {
27634         var optionsNameMap = ts.createMap();
27635         var shortOptionNames = ts.createMap();
27636         ts.forEach(optionDeclarations, function (option) {
27637             optionsNameMap.set(option.name.toLowerCase(), option);
27638             if (option.shortName) {
27639                 shortOptionNames.set(option.shortName, option.name);
27640             }
27641         });
27642         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
27643     }
27644     ts.createOptionNameMap = createOptionNameMap;
27645     var optionsNameMapCache;
27646     /* @internal */
27647     function getOptionsNameMap() {
27648         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
27649     }
27650     ts.getOptionsNameMap = getOptionsNameMap;
27651     /* @internal */
27652     ts.defaultInitCompilerOptions = {
27653         module: ts.ModuleKind.CommonJS,
27654         target: 1 /* ES5 */,
27655         strict: true,
27656         esModuleInterop: true,
27657         forceConsistentCasingInFileNames: true,
27658         skipLibCheck: true
27659     };
27660     /* @internal */
27661     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
27662         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
27663         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
27664             return {
27665                 enable: typeAcquisition.enableAutoDiscovery,
27666                 include: typeAcquisition.include || [],
27667                 exclude: typeAcquisition.exclude || []
27668             };
27669         }
27670         return typeAcquisition;
27671     }
27672     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
27673     /* @internal */
27674     function createCompilerDiagnosticForInvalidCustomType(opt) {
27675         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
27676     }
27677     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
27678     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
27679         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
27680         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
27681     }
27682     /* @internal */
27683     function parseCustomTypeOption(opt, value, errors) {
27684         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
27685     }
27686     ts.parseCustomTypeOption = parseCustomTypeOption;
27687     /* @internal */
27688     function parseListTypeOption(opt, value, errors) {
27689         if (value === void 0) { value = ""; }
27690         value = trimString(value);
27691         if (ts.startsWith(value, "-")) {
27692             return undefined;
27693         }
27694         if (value === "") {
27695             return [];
27696         }
27697         var values = value.split(",");
27698         switch (opt.element.type) {
27699             case "number":
27700                 return ts.map(values, parseInt);
27701             case "string":
27702                 return ts.map(values, function (v) { return v || ""; });
27703             default:
27704                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
27705         }
27706     }
27707     ts.parseListTypeOption = parseListTypeOption;
27708     function getOptionName(option) {
27709         return option.name;
27710     }
27711     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
27712         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
27713         return possibleOption ?
27714             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
27715             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
27716     }
27717     /*@internal*/
27718     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
27719         var options = {};
27720         var watchOptions;
27721         var fileNames = [];
27722         var errors = [];
27723         parseStrings(commandLine);
27724         return {
27725             options: options,
27726             watchOptions: watchOptions,
27727             fileNames: fileNames,
27728             errors: errors
27729         };
27730         function parseStrings(args) {
27731             var i = 0;
27732             while (i < args.length) {
27733                 var s = args[i];
27734                 i++;
27735                 if (s.charCodeAt(0) === 64 /* at */) {
27736                     parseResponseFile(s.slice(1));
27737                 }
27738                 else if (s.charCodeAt(0) === 45 /* minus */) {
27739                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
27740                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27741                     if (opt) {
27742                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
27743                     }
27744                     else {
27745                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27746                         if (watchOpt) {
27747                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
27748                         }
27749                         else {
27750                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
27751                         }
27752                     }
27753                 }
27754                 else {
27755                     fileNames.push(s);
27756                 }
27757             }
27758         }
27759         function parseResponseFile(fileName) {
27760             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
27761             if (!ts.isString(text)) {
27762                 errors.push(text);
27763                 return;
27764             }
27765             var args = [];
27766             var pos = 0;
27767             while (true) {
27768                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
27769                     pos++;
27770                 if (pos >= text.length)
27771                     break;
27772                 var start = pos;
27773                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
27774                     pos++;
27775                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
27776                         pos++;
27777                     if (pos < text.length) {
27778                         args.push(text.substring(start + 1, pos));
27779                         pos++;
27780                     }
27781                     else {
27782                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
27783                     }
27784                 }
27785                 else {
27786                     while (text.charCodeAt(pos) > 32 /* space */)
27787                         pos++;
27788                     args.push(text.substring(start, pos));
27789                 }
27790             }
27791             parseStrings(args);
27792         }
27793     }
27794     ts.parseCommandLineWorker = parseCommandLineWorker;
27795     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
27796         if (opt.isTSConfigOnly) {
27797             var optValue = args[i];
27798             if (optValue === "null") {
27799                 options[opt.name] = undefined;
27800                 i++;
27801             }
27802             else if (opt.type === "boolean") {
27803                 if (optValue === "false") {
27804                     options[opt.name] = false;
27805                     i++;
27806                 }
27807                 else {
27808                     if (optValue === "true")
27809                         i++;
27810                     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));
27811                 }
27812             }
27813             else {
27814                 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));
27815                 if (optValue && !ts.startsWith(optValue, "-"))
27816                     i++;
27817             }
27818         }
27819         else {
27820             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
27821             if (!args[i] && opt.type !== "boolean") {
27822                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
27823             }
27824             if (args[i] !== "null") {
27825                 switch (opt.type) {
27826                     case "number":
27827                         options[opt.name] = parseInt(args[i]);
27828                         i++;
27829                         break;
27830                     case "boolean":
27831                         // boolean flag has optional value true, false, others
27832                         var optValue = args[i];
27833                         options[opt.name] = optValue !== "false";
27834                         // consume next argument as boolean flag value
27835                         if (optValue === "false" || optValue === "true") {
27836                             i++;
27837                         }
27838                         break;
27839                     case "string":
27840                         options[opt.name] = args[i] || "";
27841                         i++;
27842                         break;
27843                     case "list":
27844                         var result = parseListTypeOption(opt, args[i], errors);
27845                         options[opt.name] = result || [];
27846                         if (result) {
27847                             i++;
27848                         }
27849                         break;
27850                     // If not a primitive, the possible types are specified in what is effectively a map of options.
27851                     default:
27852                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
27853                         i++;
27854                         break;
27855                 }
27856             }
27857             else {
27858                 options[opt.name] = undefined;
27859                 i++;
27860             }
27861         }
27862         return i;
27863     }
27864     /*@internal*/
27865     ts.compilerOptionsDidYouMeanDiagnostics = {
27866         getOptionsNameMap: getOptionsNameMap,
27867         optionDeclarations: ts.optionDeclarations,
27868         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
27869         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
27870         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
27871     };
27872     function parseCommandLine(commandLine, readFile) {
27873         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
27874     }
27875     ts.parseCommandLine = parseCommandLine;
27876     /** @internal */
27877     function getOptionFromName(optionName, allowShort) {
27878         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
27879     }
27880     ts.getOptionFromName = getOptionFromName;
27881     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
27882         if (allowShort === void 0) { allowShort = false; }
27883         optionName = optionName.toLowerCase();
27884         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
27885         // Try to translate short option names to their full equivalents.
27886         if (allowShort) {
27887             var short = shortOptionNames.get(optionName);
27888             if (short !== undefined) {
27889                 optionName = short;
27890             }
27891         }
27892         return optionsNameMap.get(optionName);
27893     }
27894     var buildOptionsNameMapCache;
27895     function getBuildOptionsNameMap() {
27896         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
27897     }
27898     var buildOptionsDidYouMeanDiagnostics = {
27899         getOptionsNameMap: getBuildOptionsNameMap,
27900         optionDeclarations: ts.buildOpts,
27901         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
27902         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
27903         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
27904     };
27905     /*@internal*/
27906     function parseBuildCommand(args) {
27907         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
27908         var buildOptions = options;
27909         if (projects.length === 0) {
27910             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
27911             projects.push(".");
27912         }
27913         // Nonsensical combinations
27914         if (buildOptions.clean && buildOptions.force) {
27915             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
27916         }
27917         if (buildOptions.clean && buildOptions.verbose) {
27918             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
27919         }
27920         if (buildOptions.clean && buildOptions.watch) {
27921             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
27922         }
27923         if (buildOptions.watch && buildOptions.dry) {
27924             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
27925         }
27926         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
27927     }
27928     ts.parseBuildCommand = parseBuildCommand;
27929     /* @internal */
27930     function getDiagnosticText(_message) {
27931         var _args = [];
27932         for (var _i = 1; _i < arguments.length; _i++) {
27933             _args[_i - 1] = arguments[_i];
27934         }
27935         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
27936         return diagnostic.messageText;
27937     }
27938     ts.getDiagnosticText = getDiagnosticText;
27939     /**
27940      * Reads the config file, reports errors if any and exits if the config file cannot be found
27941      */
27942     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
27943         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
27944         if (!ts.isString(configFileText)) {
27945             host.onUnRecoverableConfigFileDiagnostic(configFileText);
27946             return undefined;
27947         }
27948         var result = ts.parseJsonText(configFileName, configFileText);
27949         var cwd = host.getCurrentDirectory();
27950         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
27951         result.resolvedPath = result.path;
27952         result.originalFileName = result.fileName;
27953         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
27954         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
27955     }
27956     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
27957     /**
27958      * Read tsconfig.json file
27959      * @param fileName The path to the config file
27960      */
27961     function readConfigFile(fileName, readFile) {
27962         var textOrDiagnostic = tryReadFile(fileName, readFile);
27963         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
27964     }
27965     ts.readConfigFile = readConfigFile;
27966     /**
27967      * Parse the text of the tsconfig.json file
27968      * @param fileName The path to the config file
27969      * @param jsonText The text of the config file
27970      */
27971     function parseConfigFileTextToJson(fileName, jsonText) {
27972         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
27973         return {
27974             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
27975             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
27976         };
27977     }
27978     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
27979     /**
27980      * Read tsconfig.json file
27981      * @param fileName The path to the config file
27982      */
27983     function readJsonConfigFile(fileName, readFile) {
27984         var textOrDiagnostic = tryReadFile(fileName, readFile);
27985         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
27986     }
27987     ts.readJsonConfigFile = readJsonConfigFile;
27988     /*@internal*/
27989     function tryReadFile(fileName, readFile) {
27990         var text;
27991         try {
27992             text = readFile(fileName);
27993         }
27994         catch (e) {
27995             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
27996         }
27997         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
27998     }
27999     ts.tryReadFile = tryReadFile;
28000     function commandLineOptionsToMap(options) {
28001         return ts.arrayToMap(options, getOptionName);
28002     }
28003     var typeAcquisitionDidYouMeanDiagnostics = {
28004         optionDeclarations: ts.typeAcquisitionDeclarations,
28005         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
28006         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
28007     };
28008     var watchOptionsNameMapCache;
28009     function getWatchOptionsNameMap() {
28010         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
28011     }
28012     var watchOptionsDidYouMeanDiagnostics = {
28013         getOptionsNameMap: getWatchOptionsNameMap,
28014         optionDeclarations: ts.optionsForWatch,
28015         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
28016         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
28017         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
28018     };
28019     var commandLineCompilerOptionsMapCache;
28020     function getCommandLineCompilerOptionsMap() {
28021         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
28022     }
28023     var commandLineWatchOptionsMapCache;
28024     function getCommandLineWatchOptionsMap() {
28025         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
28026     }
28027     var commandLineTypeAcquisitionMapCache;
28028     function getCommandLineTypeAcquisitionMap() {
28029         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
28030     }
28031     var _tsconfigRootOptions;
28032     function getTsconfigRootOptionsMap() {
28033         if (_tsconfigRootOptions === undefined) {
28034             _tsconfigRootOptions = {
28035                 name: undefined,
28036                 type: "object",
28037                 elementOptions: commandLineOptionsToMap([
28038                     {
28039                         name: "compilerOptions",
28040                         type: "object",
28041                         elementOptions: getCommandLineCompilerOptionsMap(),
28042                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
28043                     },
28044                     {
28045                         name: "watchOptions",
28046                         type: "object",
28047                         elementOptions: getCommandLineWatchOptionsMap(),
28048                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
28049                     },
28050                     {
28051                         name: "typingOptions",
28052                         type: "object",
28053                         elementOptions: getCommandLineTypeAcquisitionMap(),
28054                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
28055                     },
28056                     {
28057                         name: "typeAcquisition",
28058                         type: "object",
28059                         elementOptions: getCommandLineTypeAcquisitionMap(),
28060                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
28061                     },
28062                     {
28063                         name: "extends",
28064                         type: "string"
28065                     },
28066                     {
28067                         name: "references",
28068                         type: "list",
28069                         element: {
28070                             name: "references",
28071                             type: "object"
28072                         }
28073                     },
28074                     {
28075                         name: "files",
28076                         type: "list",
28077                         element: {
28078                             name: "files",
28079                             type: "string"
28080                         }
28081                     },
28082                     {
28083                         name: "include",
28084                         type: "list",
28085                         element: {
28086                             name: "include",
28087                             type: "string"
28088                         }
28089                     },
28090                     {
28091                         name: "exclude",
28092                         type: "list",
28093                         element: {
28094                             name: "exclude",
28095                             type: "string"
28096                         }
28097                     },
28098                     ts.compileOnSaveCommandLineOption
28099                 ])
28100             };
28101         }
28102         return _tsconfigRootOptions;
28103     }
28104     /**
28105      * Convert the json syntax tree into the json value
28106      */
28107     function convertToObject(sourceFile, errors) {
28108         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
28109     }
28110     ts.convertToObject = convertToObject;
28111     /**
28112      * Convert the json syntax tree into the json value and report errors
28113      * This returns the json value (apart from checking errors) only if returnValue provided is true.
28114      * Otherwise it just checks the errors and returns undefined
28115      */
28116     /*@internal*/
28117     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
28118         if (!sourceFile.statements.length) {
28119             return returnValue ? {} : undefined;
28120         }
28121         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
28122         function isRootOptionMap(knownOptions) {
28123             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
28124         }
28125         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
28126             var result = returnValue ? {} : undefined;
28127             var _loop_3 = function (element) {
28128                 if (element.kind !== 281 /* PropertyAssignment */) {
28129                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
28130                     return "continue";
28131                 }
28132                 if (element.questionToken) {
28133                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
28134                 }
28135                 if (!isDoubleQuotedString(element.name)) {
28136                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
28137                 }
28138                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
28139                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
28140                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
28141                 if (keyText && extraKeyDiagnostics && !option) {
28142                     if (knownOptions) {
28143                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
28144                     }
28145                     else {
28146                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
28147                     }
28148                 }
28149                 var value = convertPropertyValueToJson(element.initializer, option);
28150                 if (typeof keyText !== "undefined") {
28151                     if (returnValue) {
28152                         result[keyText] = value;
28153                     }
28154                     // Notify key value set, if user asked for it
28155                     if (jsonConversionNotifier &&
28156                         // Current callbacks are only on known parent option or if we are setting values in the root
28157                         (parentOption || isRootOptionMap(knownOptions))) {
28158                         var isValidOptionValue = isCompilerOptionsValue(option, value);
28159                         if (parentOption) {
28160                             if (isValidOptionValue) {
28161                                 // Notify option set in the parent if its a valid option value
28162                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
28163                             }
28164                         }
28165                         else if (isRootOptionMap(knownOptions)) {
28166                             if (isValidOptionValue) {
28167                                 // Notify about the valid root key value being set
28168                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28169                             }
28170                             else if (!option) {
28171                                 // Notify about the unknown root key value being set
28172                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28173                             }
28174                         }
28175                     }
28176                 }
28177             };
28178             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28179                 var element = _a[_i];
28180                 _loop_3(element);
28181             }
28182             return result;
28183         }
28184         function convertArrayLiteralExpressionToJson(elements, elementOption) {
28185             if (!returnValue) {
28186                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
28187             }
28188             // Filter out invalid values
28189             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
28190         }
28191         function convertPropertyValueToJson(valueExpression, option) {
28192             switch (valueExpression.kind) {
28193                 case 106 /* TrueKeyword */:
28194                     reportInvalidOptionValue(option && option.type !== "boolean");
28195                     return true;
28196                 case 91 /* FalseKeyword */:
28197                     reportInvalidOptionValue(option && option.type !== "boolean");
28198                     return false;
28199                 case 100 /* NullKeyword */:
28200                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
28201                     return null; // eslint-disable-line no-null/no-null
28202                 case 10 /* StringLiteral */:
28203                     if (!isDoubleQuotedString(valueExpression)) {
28204                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
28205                     }
28206                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
28207                     var text = valueExpression.text;
28208                     if (option && !ts.isString(option.type)) {
28209                         var customOption = option;
28210                         // Validate custom option type
28211                         if (!customOption.type.has(text.toLowerCase())) {
28212                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
28213                         }
28214                     }
28215                     return text;
28216                 case 8 /* NumericLiteral */:
28217                     reportInvalidOptionValue(option && option.type !== "number");
28218                     return Number(valueExpression.text);
28219                 case 207 /* PrefixUnaryExpression */:
28220                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
28221                         break; // not valid JSON syntax
28222                     }
28223                     reportInvalidOptionValue(option && option.type !== "number");
28224                     return -Number(valueExpression.operand.text);
28225                 case 193 /* ObjectLiteralExpression */:
28226                     reportInvalidOptionValue(option && option.type !== "object");
28227                     var objectLiteralExpression = valueExpression;
28228                     // Currently having element option declaration in the tsconfig with type "object"
28229                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
28230                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
28231                     // that satifies it and need it to modify options set in them (for normalizing file paths)
28232                     // vs what we set in the json
28233                     // If need arises, we can modify this interface and callbacks as needed
28234                     if (option) {
28235                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
28236                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
28237                     }
28238                     else {
28239                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
28240                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
28241                     }
28242                 case 192 /* ArrayLiteralExpression */:
28243                     reportInvalidOptionValue(option && option.type !== "list");
28244                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
28245             }
28246             // Not in expected format
28247             if (option) {
28248                 reportInvalidOptionValue(/*isError*/ true);
28249             }
28250             else {
28251                 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));
28252             }
28253             return undefined;
28254             function reportInvalidOptionValue(isError) {
28255                 if (isError) {
28256                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
28257                 }
28258             }
28259         }
28260         function isDoubleQuotedString(node) {
28261             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
28262         }
28263     }
28264     ts.convertToObjectWorker = convertToObjectWorker;
28265     function getCompilerOptionValueTypeString(option) {
28266         return option.type === "list" ?
28267             "Array" :
28268             ts.isString(option.type) ? option.type : "string";
28269     }
28270     function isCompilerOptionsValue(option, value) {
28271         if (option) {
28272             if (isNullOrUndefined(value))
28273                 return true; // All options are undefinable/nullable
28274             if (option.type === "list") {
28275                 return ts.isArray(value);
28276             }
28277             var expectedType = ts.isString(option.type) ? option.type : "string";
28278             return typeof value === expectedType;
28279         }
28280         return false;
28281     }
28282     /**
28283      * Generate an uncommented, complete tsconfig for use with "--showConfig"
28284      * @param configParseResult options to be generated into tsconfig.json
28285      * @param configFileName name of the parsed config file - output paths will be generated relative to this
28286      * @param host provides current directory and case sensitivity services
28287      */
28288     /** @internal */
28289     function convertToTSConfig(configParseResult, configFileName, host) {
28290         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28291         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); });
28292         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
28293         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
28294         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 ? {
28295             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
28296             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
28297         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
28298         return config;
28299     }
28300     ts.convertToTSConfig = convertToTSConfig;
28301     function optionMapToObject(optionMap) {
28302         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
28303             var _a;
28304             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
28305         }, {}));
28306     }
28307     function filterSameAsDefaultInclude(specs) {
28308         if (!ts.length(specs))
28309             return undefined;
28310         if (ts.length(specs) !== 1)
28311             return specs;
28312         if (specs[0] === "**/*")
28313             return undefined;
28314         return specs;
28315     }
28316     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
28317         if (!includeSpecs)
28318             return function (_) { return true; };
28319         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
28320         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
28321         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
28322         if (includeRe) {
28323             if (excludeRe) {
28324                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
28325             }
28326             return function (path) { return !includeRe.test(path); };
28327         }
28328         if (excludeRe) {
28329             return function (path) { return excludeRe.test(path); };
28330         }
28331         return function (_) { return true; };
28332     }
28333     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
28334         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
28335             // this is of a type CommandLineOptionOfPrimitiveType
28336             return undefined;
28337         }
28338         else if (optionDefinition.type === "list") {
28339             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
28340         }
28341         else {
28342             return optionDefinition.type;
28343         }
28344     }
28345     function getNameOfCompilerOptionValue(value, customTypeMap) {
28346         // There is a typeMap associated with this command-line option so use it to map value back to its name
28347         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
28348             if (mapValue === value) {
28349                 return key;
28350             }
28351         });
28352     }
28353     function serializeCompilerOptions(options, pathOptions) {
28354         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
28355     }
28356     function serializeWatchOptions(options) {
28357         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
28358     }
28359     function serializeOptionBaseObject(options, _a, pathOptions) {
28360         var optionsNameMap = _a.optionsNameMap;
28361         var result = ts.createMap();
28362         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
28363         var _loop_4 = function (name) {
28364             if (ts.hasProperty(options, name)) {
28365                 // tsconfig only options cannot be specified via command line,
28366                 // so we can assume that only types that can appear here string | number | boolean
28367                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
28368                     return "continue";
28369                 }
28370                 var value = options[name];
28371                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
28372                 if (optionDefinition) {
28373                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
28374                     if (!customTypeMap_1) {
28375                         // There is no map associated with this compiler option then use the value as-is
28376                         // This is the case if the value is expect to be string, number, boolean or list of string
28377                         if (pathOptions && optionDefinition.isFilePath) {
28378                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
28379                         }
28380                         else {
28381                             result.set(name, value);
28382                         }
28383                     }
28384                     else {
28385                         if (optionDefinition.type === "list") {
28386                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
28387                         }
28388                         else {
28389                             // There is a typeMap associated with this command-line option so use it to map value back to its name
28390                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
28391                         }
28392                     }
28393                 }
28394             }
28395         };
28396         for (var name in options) {
28397             _loop_4(name);
28398         }
28399         return result;
28400     }
28401     /**
28402      * Generate tsconfig configuration when running command line "--init"
28403      * @param options commandlineOptions to be generated into tsconfig.json
28404      * @param fileNames array of filenames to be generated into tsconfig.json
28405      */
28406     /* @internal */
28407     function generateTSConfig(options, fileNames, newLine) {
28408         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
28409         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
28410         return writeConfigurations();
28411         function getDefaultValueForOption(option) {
28412             switch (option.type) {
28413                 case "number":
28414                     return 1;
28415                 case "boolean":
28416                     return true;
28417                 case "string":
28418                     return option.isFilePath ? "./" : "";
28419                 case "list":
28420                     return [];
28421                 case "object":
28422                     return {};
28423                 default:
28424                     var iterResult = option.type.keys().next();
28425                     if (!iterResult.done)
28426                         return iterResult.value;
28427                     return ts.Debug.fail("Expected 'option.type' to have entries.");
28428             }
28429         }
28430         function makePadding(paddingLength) {
28431             return Array(paddingLength + 1).join(" ");
28432         }
28433         function isAllowedOption(_a) {
28434             var category = _a.category, name = _a.name;
28435             // Skip options which do not have a category or have category `Command_line_Options`
28436             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
28437             return category !== undefined
28438                 && category !== ts.Diagnostics.Command_line_Options
28439                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
28440         }
28441         function writeConfigurations() {
28442             // Filter applicable options to place in the file
28443             var categorizedOptions = ts.createMultiMap();
28444             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
28445                 var option = optionDeclarations_1[_i];
28446                 var category = option.category;
28447                 if (isAllowedOption(option)) {
28448                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
28449                 }
28450             }
28451             // Serialize all options and their descriptions
28452             var marginLength = 0;
28453             var seenKnownKeys = 0;
28454             var entries = [];
28455             categorizedOptions.forEach(function (options, category) {
28456                 if (entries.length !== 0) {
28457                     entries.push({ value: "" });
28458                 }
28459                 entries.push({ value: "/* " + category + " */" });
28460                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
28461                     var option = options_1[_i];
28462                     var optionName = void 0;
28463                     if (compilerOptionsMap.has(option.name)) {
28464                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
28465                     }
28466                     else {
28467                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
28468                     }
28469                     entries.push({
28470                         value: optionName,
28471                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
28472                     });
28473                     marginLength = Math.max(optionName.length, marginLength);
28474                 }
28475             });
28476             // Write the output
28477             var tab = makePadding(2);
28478             var result = [];
28479             result.push("{");
28480             result.push(tab + "\"compilerOptions\": {");
28481             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
28482             result.push("");
28483             // Print out each row, aligning all the descriptions on the same column.
28484             for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
28485                 var entry = entries_3[_a];
28486                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
28487                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
28488             }
28489             if (fileNames.length) {
28490                 result.push(tab + "},");
28491                 result.push(tab + "\"files\": [");
28492                 for (var i = 0; i < fileNames.length; i++) {
28493                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
28494                 }
28495                 result.push(tab + "]");
28496             }
28497             else {
28498                 result.push(tab + "}");
28499             }
28500             result.push("}");
28501             return result.join(newLine) + newLine;
28502         }
28503     }
28504     ts.generateTSConfig = generateTSConfig;
28505     /* @internal */
28506     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
28507         var result = {};
28508         var optionsNameMap = getOptionsNameMap().optionsNameMap;
28509         for (var name in options) {
28510             if (ts.hasProperty(options, name)) {
28511                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
28512             }
28513         }
28514         if (result.configFilePath) {
28515             result.configFilePath = toAbsolutePath(result.configFilePath);
28516         }
28517         return result;
28518     }
28519     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
28520     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
28521         if (option && !isNullOrUndefined(value)) {
28522             if (option.type === "list") {
28523                 var values = value;
28524                 if (option.element.isFilePath && values.length) {
28525                     return values.map(toAbsolutePath);
28526                 }
28527             }
28528             else if (option.isFilePath) {
28529                 return toAbsolutePath(value);
28530             }
28531         }
28532         return value;
28533     }
28534     /**
28535      * Parse the contents of a config file (tsconfig.json).
28536      * @param json The contents of the config file to parse
28537      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28538      * @param basePath A root directory to resolve relative path entries in the config
28539      *    file to. e.g. outDir
28540      */
28541     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28542         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28543     }
28544     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
28545     /**
28546      * Parse the contents of a config file (tsconfig.json).
28547      * @param jsonNode The contents of the config file to parse
28548      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28549      * @param basePath A root directory to resolve relative path entries in the config
28550      *    file to. e.g. outDir
28551      */
28552     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28553         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28554     }
28555     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
28556     /*@internal*/
28557     function setConfigFileInOptions(options, configFile) {
28558         if (configFile) {
28559             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
28560         }
28561     }
28562     ts.setConfigFileInOptions = setConfigFileInOptions;
28563     function isNullOrUndefined(x) {
28564         return x === undefined || x === null; // eslint-disable-line no-null/no-null
28565     }
28566     function directoryOfCombinedPath(fileName, basePath) {
28567         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
28568         // until consistent casing errors are reported
28569         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
28570     }
28571     /**
28572      * Parse the contents of a config file from json or json source file (tsconfig.json).
28573      * @param json The contents of the config file to parse
28574      * @param sourceFile sourceFile corresponding to the Json
28575      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28576      * @param basePath A root directory to resolve relative path entries in the config
28577      *    file to. e.g. outDir
28578      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
28579      */
28580     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
28581         if (existingOptions === void 0) { existingOptions = {}; }
28582         if (resolutionStack === void 0) { resolutionStack = []; }
28583         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28584         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
28585         var errors = [];
28586         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
28587         var raw = parsedConfig.raw;
28588         var options = ts.extend(existingOptions, parsedConfig.options || {});
28589         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
28590             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
28591             parsedConfig.watchOptions || existingWatchOptions;
28592         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
28593         setConfigFileInOptions(options, sourceFile);
28594         var projectReferences;
28595         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
28596         return {
28597             options: options,
28598             watchOptions: watchOptions,
28599             fileNames: fileNames,
28600             projectReferences: projectReferences,
28601             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
28602             raw: raw,
28603             errors: errors,
28604             wildcardDirectories: wildcardDirectories,
28605             compileOnSave: !!raw.compileOnSave,
28606             configFileSpecs: spec
28607         };
28608         function getFileNames() {
28609             var filesSpecs;
28610             if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
28611                 if (ts.isArray(raw.files)) {
28612                     filesSpecs = raw.files;
28613                     var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
28614                     var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
28615                     var hasExtends = ts.hasProperty(raw, "extends");
28616                     if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
28617                         if (sourceFile) {
28618                             var fileName = configFileName || "tsconfig.json";
28619                             var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
28620                             var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
28621                             var error = nodeValue
28622                                 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
28623                                 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
28624                             errors.push(error);
28625                         }
28626                         else {
28627                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
28628                         }
28629                     }
28630                 }
28631                 else {
28632                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
28633                 }
28634             }
28635             var includeSpecs;
28636             if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
28637                 if (ts.isArray(raw.include)) {
28638                     includeSpecs = raw.include;
28639                 }
28640                 else {
28641                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
28642                 }
28643             }
28644             var excludeSpecs;
28645             if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
28646                 if (ts.isArray(raw.exclude)) {
28647                     excludeSpecs = raw.exclude;
28648                 }
28649                 else {
28650                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
28651                 }
28652             }
28653             else if (raw.compilerOptions) {
28654                 var outDir = raw.compilerOptions.outDir;
28655                 var declarationDir = raw.compilerOptions.declarationDir;
28656                 if (outDir || declarationDir) {
28657                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
28658                 }
28659             }
28660             if (filesSpecs === undefined && includeSpecs === undefined) {
28661                 includeSpecs = ["**/*"];
28662             }
28663             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
28664             if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
28665                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
28666             }
28667             if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
28668                 if (ts.isArray(raw.references)) {
28669                     for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
28670                         var ref = _a[_i];
28671                         if (typeof ref.path !== "string") {
28672                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
28673                         }
28674                         else {
28675                             (projectReferences || (projectReferences = [])).push({
28676                                 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
28677                                 originalPath: ref.path,
28678                                 prepend: ref.prepend,
28679                                 circular: ref.circular
28680                             });
28681                         }
28682                     }
28683                 }
28684                 else {
28685                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
28686                 }
28687             }
28688             return result;
28689         }
28690         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
28691             if (!sourceFile) {
28692                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
28693             }
28694         }
28695     }
28696     function isErrorNoInputFiles(error) {
28697         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
28698     }
28699     function getErrorForNoInputFiles(_a, configFileName) {
28700         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
28701         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 || []));
28702     }
28703     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
28704         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
28705     }
28706     /*@internal*/
28707     function canJsonReportNoInutFiles(raw) {
28708         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
28709     }
28710     ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
28711     /*@internal*/
28712     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
28713         var existingErrors = configParseDiagnostics.length;
28714         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
28715             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
28716         }
28717         else {
28718             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
28719         }
28720         return existingErrors !== configParseDiagnostics.length;
28721     }
28722     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
28723     function isSuccessfulParsedTsconfig(value) {
28724         return !!value.options;
28725     }
28726     /**
28727      * This *just* extracts options/include/exclude/files out of a config file.
28728      * It does *not* resolve the included files.
28729      */
28730     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
28731         basePath = ts.normalizeSlashes(basePath);
28732         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
28733         if (resolutionStack.indexOf(resolvedPath) >= 0) {
28734             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
28735             return { raw: json || convertToObject(sourceFile, errors) };
28736         }
28737         var ownConfig = json ?
28738             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
28739             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
28740         if (ownConfig.extendedConfigPath) {
28741             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
28742             resolutionStack = resolutionStack.concat([resolvedPath]);
28743             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
28744             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
28745                 var baseRaw_1 = extendedConfig.raw;
28746                 var raw_1 = ownConfig.raw;
28747                 var setPropertyInRawIfNotUndefined = function (propertyName) {
28748                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
28749                     if (value) {
28750                         raw_1[propertyName] = value;
28751                     }
28752                 };
28753                 setPropertyInRawIfNotUndefined("include");
28754                 setPropertyInRawIfNotUndefined("exclude");
28755                 setPropertyInRawIfNotUndefined("files");
28756                 if (raw_1.compileOnSave === undefined) {
28757                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
28758                 }
28759                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
28760                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
28761                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
28762                     ownConfig.watchOptions || extendedConfig.watchOptions;
28763                 // TODO extend type typeAcquisition
28764             }
28765         }
28766         return ownConfig;
28767     }
28768     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
28769         if (ts.hasProperty(json, "excludes")) {
28770             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28771         }
28772         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
28773         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
28774         // It should be removed in future releases - use typeAcquisition instead.
28775         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
28776         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
28777         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
28778         var extendedConfigPath;
28779         if (json.extends) {
28780             if (!ts.isString(json.extends)) {
28781                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
28782             }
28783             else {
28784                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28785                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
28786             }
28787         }
28788         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28789     }
28790     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
28791         var options = getDefaultCompilerOptions(configFileName);
28792         var typeAcquisition, typingOptionstypeAcquisition;
28793         var watchOptions;
28794         var extendedConfigPath;
28795         var optionsIterator = {
28796             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
28797                 var currentOption;
28798                 switch (parentOption) {
28799                     case "compilerOptions":
28800                         currentOption = options;
28801                         break;
28802                     case "watchOptions":
28803                         currentOption = (watchOptions || (watchOptions = {}));
28804                         break;
28805                     case "typeAcquisition":
28806                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
28807                         break;
28808                     case "typingOptions":
28809                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
28810                         break;
28811                     default:
28812                         ts.Debug.fail("Unknown option");
28813                 }
28814                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
28815             },
28816             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
28817                 switch (key) {
28818                     case "extends":
28819                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28820                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
28821                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
28822                         });
28823                         return;
28824                 }
28825             },
28826             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
28827                 if (key === "excludes") {
28828                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28829                 }
28830             }
28831         };
28832         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
28833         if (!typeAcquisition) {
28834             if (typingOptionstypeAcquisition) {
28835                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
28836                     {
28837                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
28838                         include: typingOptionstypeAcquisition.include,
28839                         exclude: typingOptionstypeAcquisition.exclude
28840                     } :
28841                     typingOptionstypeAcquisition;
28842             }
28843             else {
28844                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
28845             }
28846         }
28847         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28848     }
28849     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
28850         extendedConfig = ts.normalizeSlashes(extendedConfig);
28851         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
28852             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
28853             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
28854                 extendedConfigPath = extendedConfigPath + ".json";
28855                 if (!host.fileExists(extendedConfigPath)) {
28856                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28857                     return undefined;
28858                 }
28859             }
28860             return extendedConfigPath;
28861         }
28862         // If the path isn't a rooted or relative path, resolve like a module
28863         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
28864         if (resolved.resolvedModule) {
28865             return resolved.resolvedModule.resolvedFileName;
28866         }
28867         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28868         return undefined;
28869     }
28870     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
28871         var _a;
28872         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
28873         var value;
28874         var extendedResult;
28875         var extendedConfig;
28876         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
28877             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
28878         }
28879         else {
28880             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
28881             if (!extendedResult.parseDiagnostics.length) {
28882                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
28883                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
28884                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
28885                     // Update the paths to reflect base path
28886                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
28887                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
28888                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
28889                         if (raw_2[propertyName]) {
28890                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
28891                         }
28892                     };
28893                     var raw_2 = extendedConfig.raw;
28894                     mapPropertiesInRawIfNotUndefined("include");
28895                     mapPropertiesInRawIfNotUndefined("exclude");
28896                     mapPropertiesInRawIfNotUndefined("files");
28897                 }
28898             }
28899             if (extendedConfigCache) {
28900                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
28901             }
28902         }
28903         if (sourceFile) {
28904             sourceFile.extendedSourceFiles = [extendedResult.fileName];
28905             if (extendedResult.extendedSourceFiles) {
28906                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
28907             }
28908         }
28909         if (extendedResult.parseDiagnostics.length) {
28910             errors.push.apply(errors, extendedResult.parseDiagnostics);
28911             return undefined;
28912         }
28913         return extendedConfig;
28914     }
28915     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
28916         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
28917             return false;
28918         }
28919         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
28920         return typeof result === "boolean" && result;
28921     }
28922     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
28923         var errors = [];
28924         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28925         return { options: options, errors: errors };
28926     }
28927     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
28928     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
28929         var errors = [];
28930         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28931         return { options: options, errors: errors };
28932     }
28933     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
28934     function getDefaultCompilerOptions(configFileName) {
28935         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
28936             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
28937             : {};
28938         return options;
28939     }
28940     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28941         var options = getDefaultCompilerOptions(configFileName);
28942         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
28943         if (configFileName) {
28944             options.configFilePath = ts.normalizeSlashes(configFileName);
28945         }
28946         return options;
28947     }
28948     function getDefaultTypeAcquisition(configFileName) {
28949         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
28950     }
28951     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28952         var options = getDefaultTypeAcquisition(configFileName);
28953         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
28954         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
28955         return options;
28956     }
28957     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
28958         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
28959     }
28960     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
28961         if (!jsonOptions) {
28962             return;
28963         }
28964         for (var id in jsonOptions) {
28965             var opt = optionsNameMap.get(id);
28966             if (opt) {
28967                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
28968             }
28969             else {
28970                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
28971             }
28972         }
28973         return defaultOptions;
28974     }
28975     function convertJsonOption(opt, value, basePath, errors) {
28976         if (isCompilerOptionsValue(opt, value)) {
28977             var optType = opt.type;
28978             if (optType === "list" && ts.isArray(value)) {
28979                 return convertJsonOptionOfListType(opt, value, basePath, errors);
28980             }
28981             else if (!ts.isString(optType)) {
28982                 return convertJsonOptionOfCustomType(opt, value, errors);
28983             }
28984             return normalizeNonListOptionValue(opt, basePath, value);
28985         }
28986         else {
28987             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
28988         }
28989     }
28990     function normalizeOptionValue(option, basePath, value) {
28991         if (isNullOrUndefined(value))
28992             return undefined;
28993         if (option.type === "list") {
28994             var listOption_1 = option;
28995             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
28996                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
28997             }
28998             return value;
28999         }
29000         else if (!ts.isString(option.type)) {
29001             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
29002         }
29003         return normalizeNonListOptionValue(option, basePath, value);
29004     }
29005     function normalizeNonListOptionValue(option, basePath, value) {
29006         if (option.isFilePath) {
29007             value = ts.getNormalizedAbsolutePath(value, basePath);
29008             if (value === "") {
29009                 value = ".";
29010             }
29011         }
29012         return value;
29013     }
29014     function convertJsonOptionOfCustomType(opt, value, errors) {
29015         if (isNullOrUndefined(value))
29016             return undefined;
29017         var key = value.toLowerCase();
29018         var val = opt.type.get(key);
29019         if (val !== undefined) {
29020             return val;
29021         }
29022         else {
29023             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
29024         }
29025     }
29026     function convertJsonOptionOfListType(option, values, basePath, errors) {
29027         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
29028     }
29029     function trimString(s) {
29030         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
29031     }
29032     /**
29033      * Tests for a path that ends in a recursive directory wildcard.
29034      * Matches **, \**, **\, and \**\, but not a**b.
29035      *
29036      * NOTE: used \ in place of / above to avoid issues with multiline comments.
29037      *
29038      * Breakdown:
29039      *  (^|\/)      # matches either the beginning of the string or a directory separator.
29040      *  \*\*        # matches the recursive directory wildcard "**".
29041      *  \/?$        # matches an optional trailing directory separator at the end of the string.
29042      */
29043     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
29044     /**
29045      * Tests for a path where .. appears after a recursive directory wildcard.
29046      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
29047      *
29048      * NOTE: used \ in place of / above to avoid issues with multiline comments.
29049      *
29050      * Breakdown:
29051      *  (^|\/)      # matches either the beginning of the string or a directory separator.
29052      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
29053      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
29054      *  \.\.        # matches a parent directory path component ".."
29055      *  ($|\/)      # matches either the end of the string or a directory separator.
29056      */
29057     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
29058     /**
29059      * Tests for a path containing a wildcard character in a directory component of the path.
29060      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
29061      *
29062      * NOTE: used \ in place of / above to avoid issues with multiline comments.
29063      *
29064      * Breakdown:
29065      *  \/          # matches a directory separator.
29066      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
29067      *  [*?]        # matches either a wildcard character (* or ?)
29068      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
29069      *  \/          # matches a directory separator.
29070      */
29071     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
29072     /**
29073      * Matches the portion of a wildcard path that does not contain wildcards.
29074      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
29075      *
29076      * NOTE: used \ in place of / above to avoid issues with multiline comments.
29077      *
29078      * Breakdown:
29079      *  ^                   # matches the beginning of the string
29080      *  [^*?]*              # matches any number of non-wildcard characters
29081      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
29082      *                      # a path component that contains at least one wildcard character (* or ?).
29083      */
29084     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
29085     /**
29086      * Expands an array of file specifications.
29087      *
29088      * @param filesSpecs The literal file names to include.
29089      * @param includeSpecs The wildcard file specifications to include.
29090      * @param excludeSpecs The wildcard file specifications to exclude.
29091      * @param basePath The base path for any relative file specifications.
29092      * @param options Compiler options.
29093      * @param host The host used to resolve files and directories.
29094      * @param errors An array for diagnostic reporting.
29095      */
29096     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
29097         basePath = ts.normalizePath(basePath);
29098         var validatedIncludeSpecs, validatedExcludeSpecs;
29099         // The exclude spec list is converted into a regular expression, which allows us to quickly
29100         // test whether a file or directory should be excluded before recursively traversing the
29101         // file system.
29102         if (includeSpecs) {
29103             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
29104         }
29105         if (excludeSpecs) {
29106             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
29107         }
29108         // Wildcard directories (provided as part of a wildcard path) are stored in a
29109         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
29110         // or a recursive directory. This information is used by filesystem watchers to monitor for
29111         // new entries in these paths.
29112         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
29113         var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
29114         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
29115     }
29116     /**
29117      * Gets the file names from the provided config file specs that contain, files, include, exclude and
29118      * other properties needed to resolve the file names
29119      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
29120      * @param basePath The base path for any relative file specifications.
29121      * @param options Compiler options.
29122      * @param host The host used to resolve files and directories.
29123      * @param extraFileExtensions optionaly file extra file extension information from host
29124      */
29125     /* @internal */
29126     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
29127         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
29128         basePath = ts.normalizePath(basePath);
29129         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
29130         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
29131         // file map with a possibly case insensitive key. We use this map later when when including
29132         // wildcard paths.
29133         var literalFileMap = ts.createMap();
29134         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
29135         // file map with a possibly case insensitive key. We use this map to store paths matched
29136         // via wildcard, and to handle extension priority.
29137         var wildcardFileMap = ts.createMap();
29138         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
29139         // file map with a possibly case insensitive key. We use this map to store paths matched
29140         // via wildcard of *.json kind
29141         var wildCardJsonFileMap = ts.createMap();
29142         var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
29143         // Rather than requery this for each file and filespec, we query the supported extensions
29144         // once and store it on the expansion context.
29145         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
29146         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
29147         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
29148         // remove a literal file.
29149         if (filesSpecs) {
29150             for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
29151                 var fileName = filesSpecs_1[_i];
29152                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
29153                 literalFileMap.set(keyMapper(file), file);
29154             }
29155         }
29156         var jsonOnlyIncludeRegexes;
29157         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
29158             var _loop_5 = function (file) {
29159                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
29160                     // Valid only if *.json specified
29161                     if (!jsonOnlyIncludeRegexes) {
29162                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
29163                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
29164                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
29165                     }
29166                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
29167                     if (includeIndex !== -1) {
29168                         var key_1 = keyMapper(file);
29169                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
29170                             wildCardJsonFileMap.set(key_1, file);
29171                         }
29172                     }
29173                     return "continue";
29174                 }
29175                 // If we have already included a literal or wildcard path with a
29176                 // higher priority extension, we should skip this file.
29177                 //
29178                 // This handles cases where we may encounter both <file>.ts and
29179                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
29180                 // directory when they are compilation outputs.
29181                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
29182                     return "continue";
29183                 }
29184                 // We may have included a wildcard path with a lower priority
29185                 // extension due to the user-defined order of entries in the
29186                 // "include" array. If there is a lower priority extension in the
29187                 // same directory, we should remove it.
29188                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
29189                 var key = keyMapper(file);
29190                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
29191                     wildcardFileMap.set(key, file);
29192                 }
29193             };
29194             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
29195                 var file = _b[_a];
29196                 _loop_5(file);
29197             }
29198         }
29199         var literalFiles = ts.arrayFrom(literalFileMap.values());
29200         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
29201         return {
29202             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
29203             wildcardDirectories: wildcardDirectories,
29204             spec: spec
29205         };
29206     }
29207     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
29208     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
29209         return specs.filter(function (spec) {
29210             var diag = specToDiagnostic(spec, allowTrailingRecursion);
29211             if (diag !== undefined) {
29212                 errors.push(createDiagnostic(diag, spec));
29213             }
29214             return diag === undefined;
29215         });
29216         function createDiagnostic(message, spec) {
29217             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
29218             return element ?
29219                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
29220                 ts.createCompilerDiagnostic(message, spec);
29221         }
29222     }
29223     function specToDiagnostic(spec, allowTrailingRecursion) {
29224         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
29225             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29226         }
29227         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
29228             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29229         }
29230     }
29231     /**
29232      * Gets directories in a set of include patterns that should be watched for changes.
29233      */
29234     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
29235         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
29236         // of the pattern:
29237         //
29238         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
29239         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
29240         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
29241         //
29242         // We watch a directory without recursion if it contains a wildcard in the file segment of
29243         // the pattern:
29244         //
29245         //  /a/b/*      - Watch /a/b directly to catch any new file
29246         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
29247         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
29248         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
29249         var wildcardDirectories = {};
29250         if (include !== undefined) {
29251             var recursiveKeys = [];
29252             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
29253                 var file = include_1[_i];
29254                 var spec = ts.normalizePath(ts.combinePaths(path, file));
29255                 if (excludeRegex && excludeRegex.test(spec)) {
29256                     continue;
29257                 }
29258                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
29259                 if (match) {
29260                     var key = match.key, flags = match.flags;
29261                     var existingFlags = wildcardDirectories[key];
29262                     if (existingFlags === undefined || existingFlags < flags) {
29263                         wildcardDirectories[key] = flags;
29264                         if (flags === 1 /* Recursive */) {
29265                             recursiveKeys.push(key);
29266                         }
29267                     }
29268                 }
29269             }
29270             // Remove any subpaths under an existing recursively watched directory.
29271             for (var key in wildcardDirectories) {
29272                 if (ts.hasProperty(wildcardDirectories, key)) {
29273                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
29274                         var recursiveKey = recursiveKeys_1[_a];
29275                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
29276                             delete wildcardDirectories[key];
29277                         }
29278                     }
29279                 }
29280             }
29281         }
29282         return wildcardDirectories;
29283     }
29284     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
29285         var match = wildcardDirectoryPattern.exec(spec);
29286         if (match) {
29287             return {
29288                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
29289                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
29290             };
29291         }
29292         if (ts.isImplicitGlob(spec)) {
29293             return { key: spec, flags: 1 /* Recursive */ };
29294         }
29295         return undefined;
29296     }
29297     /**
29298      * Determines whether a literal or wildcard file has already been included that has a higher
29299      * extension priority.
29300      *
29301      * @param file The path to the file.
29302      * @param extensionPriority The priority of the extension.
29303      * @param context The expansion context.
29304      */
29305     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
29306         var extensionPriority = ts.getExtensionPriority(file, extensions);
29307         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
29308         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
29309             var higherPriorityExtension = extensions[i];
29310             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
29311             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
29312                 return true;
29313             }
29314         }
29315         return false;
29316     }
29317     /**
29318      * Removes files included via wildcard expansion with a lower extension priority that have
29319      * already been included.
29320      *
29321      * @param file The path to the file.
29322      * @param extensionPriority The priority of the extension.
29323      * @param context The expansion context.
29324      */
29325     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
29326         var extensionPriority = ts.getExtensionPriority(file, extensions);
29327         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
29328         for (var i = nextExtensionPriority; i < extensions.length; i++) {
29329             var lowerPriorityExtension = extensions[i];
29330             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
29331             wildcardFiles.delete(lowerPriorityPath);
29332         }
29333     }
29334     /**
29335      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
29336      * Also converts enum values back to strings.
29337      */
29338     /* @internal */
29339     function convertCompilerOptionsForTelemetry(opts) {
29340         var out = {};
29341         for (var key in opts) {
29342             if (opts.hasOwnProperty(key)) {
29343                 var type = getOptionFromName(key);
29344                 if (type !== undefined) { // Ignore unknown options
29345                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
29346                 }
29347             }
29348         }
29349         return out;
29350     }
29351     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
29352     function getOptionValueWithEmptyStrings(value, option) {
29353         switch (option.type) {
29354             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
29355                 return "";
29356             case "string": // Could be any arbitrary string -- use empty string instead.
29357                 return "";
29358             case "number": // Allow numbers, but be sure to check it's actually a number.
29359                 return typeof value === "number" ? value : "";
29360             case "boolean":
29361                 return typeof value === "boolean" ? value : "";
29362             case "list":
29363                 var elementType_1 = option.element;
29364                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
29365             default:
29366                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
29367                     if (optionEnumValue === value) {
29368                         return optionStringValue;
29369                     }
29370                 }); // TODO: GH#18217
29371         }
29372     }
29373 })(ts || (ts = {}));
29374 var ts;
29375 (function (ts) {
29376     function trace(host) {
29377         host.trace(ts.formatMessage.apply(undefined, arguments));
29378     }
29379     ts.trace = trace;
29380     /* @internal */
29381     function isTraceEnabled(compilerOptions, host) {
29382         return !!compilerOptions.traceResolution && host.trace !== undefined;
29383     }
29384     ts.isTraceEnabled = isTraceEnabled;
29385     function withPackageId(packageInfo, r) {
29386         var packageId;
29387         if (r && packageInfo) {
29388             var packageJsonContent = packageInfo.packageJsonContent;
29389             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
29390                 packageId = {
29391                     name: packageJsonContent.name,
29392                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
29393                     version: packageJsonContent.version
29394                 };
29395             }
29396         }
29397         return r && { path: r.path, extension: r.ext, packageId: packageId };
29398     }
29399     function noPackageId(r) {
29400         return withPackageId(/*packageInfo*/ undefined, r);
29401     }
29402     function removeIgnoredPackageId(r) {
29403         if (r) {
29404             ts.Debug.assert(r.packageId === undefined);
29405             return { path: r.path, ext: r.extension };
29406         }
29407     }
29408     /**
29409      * Kinds of file that we are currently looking for.
29410      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
29411      */
29412     var Extensions;
29413     (function (Extensions) {
29414         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
29415         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
29416         Extensions[Extensions["Json"] = 2] = "Json";
29417         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
29418         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
29419     })(Extensions || (Extensions = {}));
29420     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
29421     function resolvedTypeScriptOnly(resolved) {
29422         if (!resolved) {
29423             return undefined;
29424         }
29425         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
29426         return { fileName: resolved.path, packageId: resolved.packageId };
29427     }
29428     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
29429         var _a;
29430         if (resultFromCache) {
29431             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
29432             return resultFromCache;
29433         }
29434         return {
29435             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
29436             failedLookupLocations: failedLookupLocations
29437         };
29438     }
29439     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
29440         if (!ts.hasProperty(jsonContent, fieldName)) {
29441             if (state.traceEnabled) {
29442                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
29443             }
29444             return;
29445         }
29446         var value = jsonContent[fieldName];
29447         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
29448             if (state.traceEnabled) {
29449                 // eslint-disable-next-line no-null/no-null
29450                 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);
29451             }
29452             return;
29453         }
29454         return value;
29455     }
29456     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
29457         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
29458         if (fileName === undefined) {
29459             return;
29460         }
29461         if (!fileName) {
29462             if (state.traceEnabled) {
29463                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
29464             }
29465             return;
29466         }
29467         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
29468         if (state.traceEnabled) {
29469             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
29470         }
29471         return path;
29472     }
29473     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
29474         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
29475             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
29476     }
29477     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
29478         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
29479     }
29480     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
29481         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
29482     }
29483     function readPackageJsonTypesVersionsField(jsonContent, state) {
29484         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
29485         if (typesVersions === undefined)
29486             return;
29487         if (state.traceEnabled) {
29488             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
29489         }
29490         return typesVersions;
29491     }
29492     function readPackageJsonTypesVersionPaths(jsonContent, state) {
29493         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
29494         if (typesVersions === undefined)
29495             return;
29496         if (state.traceEnabled) {
29497             for (var key in typesVersions) {
29498                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
29499                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
29500                 }
29501             }
29502         }
29503         var result = getPackageJsonTypesVersionsPaths(typesVersions);
29504         if (!result) {
29505             if (state.traceEnabled) {
29506                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
29507             }
29508             return;
29509         }
29510         var bestVersionKey = result.version, bestVersionPaths = result.paths;
29511         if (typeof bestVersionPaths !== "object") {
29512             if (state.traceEnabled) {
29513                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
29514             }
29515             return;
29516         }
29517         return result;
29518     }
29519     var typeScriptVersion;
29520     /* @internal */
29521     function getPackageJsonTypesVersionsPaths(typesVersions) {
29522         if (!typeScriptVersion)
29523             typeScriptVersion = new ts.Version(ts.version);
29524         for (var key in typesVersions) {
29525             if (!ts.hasProperty(typesVersions, key))
29526                 continue;
29527             var keyRange = ts.VersionRange.tryParse(key);
29528             if (keyRange === undefined) {
29529                 continue;
29530             }
29531             // return the first entry whose range matches the current compiler version.
29532             if (keyRange.test(typeScriptVersion)) {
29533                 return { version: key, paths: typesVersions[key] };
29534             }
29535         }
29536     }
29537     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
29538     function getEffectiveTypeRoots(options, host) {
29539         if (options.typeRoots) {
29540             return options.typeRoots;
29541         }
29542         var currentDirectory;
29543         if (options.configFilePath) {
29544             currentDirectory = ts.getDirectoryPath(options.configFilePath);
29545         }
29546         else if (host.getCurrentDirectory) {
29547             currentDirectory = host.getCurrentDirectory();
29548         }
29549         if (currentDirectory !== undefined) {
29550             return getDefaultTypeRoots(currentDirectory, host);
29551         }
29552     }
29553     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
29554     /**
29555      * Returns the path to every node_modules/@types directory from some ancestor directory.
29556      * Returns undefined if there are none.
29557      */
29558     function getDefaultTypeRoots(currentDirectory, host) {
29559         if (!host.directoryExists) {
29560             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
29561             // And if it doesn't exist, tough.
29562         }
29563         var typeRoots;
29564         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
29565             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
29566             if (host.directoryExists(atTypes)) {
29567                 (typeRoots || (typeRoots = [])).push(atTypes);
29568             }
29569             return undefined;
29570         });
29571         return typeRoots;
29572     }
29573     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
29574     /**
29575      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
29576      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
29577      * is assumed to be the same as root directory of the project.
29578      */
29579     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
29580         var traceEnabled = isTraceEnabled(options, host);
29581         if (redirectedReference) {
29582             options = redirectedReference.commandLine.options;
29583         }
29584         var failedLookupLocations = [];
29585         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29586         var typeRoots = getEffectiveTypeRoots(options, host);
29587         if (traceEnabled) {
29588             if (containingFile === undefined) {
29589                 if (typeRoots === undefined) {
29590                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
29591                 }
29592                 else {
29593                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
29594                 }
29595             }
29596             else {
29597                 if (typeRoots === undefined) {
29598                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
29599                 }
29600                 else {
29601                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
29602                 }
29603             }
29604             if (redirectedReference) {
29605                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29606             }
29607         }
29608         var resolved = primaryLookup();
29609         var primary = true;
29610         if (!resolved) {
29611             resolved = secondaryLookup();
29612             primary = false;
29613         }
29614         var resolvedTypeReferenceDirective;
29615         if (resolved) {
29616             var fileName = resolved.fileName, packageId = resolved.packageId;
29617             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
29618             if (traceEnabled) {
29619                 if (packageId) {
29620                     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);
29621                 }
29622                 else {
29623                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
29624                 }
29625             }
29626             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
29627         }
29628         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
29629         function primaryLookup() {
29630             // Check primary library paths
29631             if (typeRoots && typeRoots.length) {
29632                 if (traceEnabled) {
29633                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
29634                 }
29635                 return ts.firstDefined(typeRoots, function (typeRoot) {
29636                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
29637                     var candidateDirectory = ts.getDirectoryPath(candidate);
29638                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
29639                     if (!directoryExists && traceEnabled) {
29640                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
29641                     }
29642                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
29643                 });
29644             }
29645             else {
29646                 if (traceEnabled) {
29647                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
29648                 }
29649             }
29650         }
29651         function secondaryLookup() {
29652             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
29653             if (initialLocationForSecondaryLookup !== undefined) {
29654                 // check secondary locations
29655                 if (traceEnabled) {
29656                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
29657                 }
29658                 var result = void 0;
29659                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
29660                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
29661                     result = searchResult && searchResult.value;
29662                 }
29663                 else {
29664                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
29665                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
29666                 }
29667                 var resolvedFile = resolvedTypeScriptOnly(result);
29668                 if (!resolvedFile && traceEnabled) {
29669                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
29670                 }
29671                 return resolvedFile;
29672             }
29673             else {
29674                 if (traceEnabled) {
29675                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
29676                 }
29677             }
29678         }
29679     }
29680     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
29681     /**
29682      * Given a set of options, returns the set of type directive names
29683      *   that should be included for this program automatically.
29684      * This list could either come from the config file,
29685      *   or from enumerating the types root + initial secondary types lookup location.
29686      * More type directives might appear in the program later as a result of loading actual source files;
29687      *   this list is only the set of defaults that are implicitly included.
29688      */
29689     function getAutomaticTypeDirectiveNames(options, host) {
29690         // Use explicit type list from tsconfig.json
29691         if (options.types) {
29692             return options.types;
29693         }
29694         // Walk the primary type lookup locations
29695         var result = [];
29696         if (host.directoryExists && host.getDirectories) {
29697             var typeRoots = getEffectiveTypeRoots(options, host);
29698             if (typeRoots) {
29699                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
29700                     var root = typeRoots_1[_i];
29701                     if (host.directoryExists(root)) {
29702                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
29703                             var typeDirectivePath = _b[_a];
29704                             var normalized = ts.normalizePath(typeDirectivePath);
29705                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
29706                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
29707                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
29708                             // eslint-disable-next-line no-null/no-null
29709                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
29710                             if (!isNotNeededPackage) {
29711                                 var baseFileName = ts.getBaseFileName(normalized);
29712                                 // At this stage, skip results with leading dot.
29713                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
29714                                     // Return just the type directive names
29715                                     result.push(baseFileName);
29716                                 }
29717                             }
29718                         }
29719                     }
29720                 }
29721             }
29722         }
29723         return result;
29724     }
29725     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
29726     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
29727         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
29728     }
29729     ts.createModuleResolutionCache = createModuleResolutionCache;
29730     /*@internal*/
29731     function createCacheWithRedirects(options) {
29732         var ownMap = ts.createMap();
29733         var redirectsMap = ts.createMap();
29734         return {
29735             ownMap: ownMap,
29736             redirectsMap: redirectsMap,
29737             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
29738             clear: clear,
29739             setOwnOptions: setOwnOptions,
29740             setOwnMap: setOwnMap
29741         };
29742         function setOwnOptions(newOptions) {
29743             options = newOptions;
29744         }
29745         function setOwnMap(newOwnMap) {
29746             ownMap = newOwnMap;
29747         }
29748         function getOrCreateMapOfCacheRedirects(redirectedReference) {
29749             if (!redirectedReference) {
29750                 return ownMap;
29751             }
29752             var path = redirectedReference.sourceFile.path;
29753             var redirects = redirectsMap.get(path);
29754             if (!redirects) {
29755                 // Reuse map if redirected reference map uses same resolution
29756                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
29757                 redirectsMap.set(path, redirects);
29758             }
29759             return redirects;
29760         }
29761         function clear() {
29762             ownMap.clear();
29763             redirectsMap.clear();
29764         }
29765     }
29766     ts.createCacheWithRedirects = createCacheWithRedirects;
29767     /*@internal*/
29768     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
29769         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
29770         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
29771             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
29772             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
29773         }
29774         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
29775             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
29776             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
29777         }
29778         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
29779             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
29780             var result = cache.get(key);
29781             if (!result) {
29782                 result = create();
29783                 cache.set(key, result);
29784             }
29785             return result;
29786         }
29787         function createPerModuleNameCache() {
29788             var directoryPathMap = ts.createMap();
29789             return { get: get, set: set };
29790             function get(directory) {
29791                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
29792             }
29793             /**
29794              * At first this function add entry directory -> module resolution result to the table.
29795              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
29796              * and for every parent folder in set it adds entry: parent -> module resolution. .
29797              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
29798              * Set of parent folders that should have the same result will be:
29799              * [
29800              *     /a/b/c/d, /a/b/c, /a/b
29801              * ]
29802              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
29803              */
29804             function set(directory, result) {
29805                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
29806                 // if entry is already in cache do nothing
29807                 if (directoryPathMap.has(path)) {
29808                     return;
29809                 }
29810                 directoryPathMap.set(path, result);
29811                 var resolvedFileName = result.resolvedModule &&
29812                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
29813                 // find common prefix between directory and resolved file name
29814                 // this common prefix should be the shortest path that has the same resolution
29815                 // directory: /a/b/c/d/e
29816                 // resolvedFileName: /a/b/foo.d.ts
29817                 // commonPrefix: /a/b
29818                 // for failed lookups cache the result for every directory up to root
29819                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
29820                 var current = path;
29821                 while (current !== commonPrefix) {
29822                     var parent = ts.getDirectoryPath(current);
29823                     if (parent === current || directoryPathMap.has(parent)) {
29824                         break;
29825                     }
29826                     directoryPathMap.set(parent, result);
29827                     current = parent;
29828                 }
29829             }
29830             function getCommonPrefix(directory, resolution) {
29831                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
29832                 // find first position where directory and resolution differs
29833                 var i = 0;
29834                 var limit = Math.min(directory.length, resolutionDirectory.length);
29835                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
29836                     i++;
29837                 }
29838                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
29839                     return directory;
29840                 }
29841                 var rootLength = ts.getRootLength(directory);
29842                 if (i < rootLength) {
29843                     return undefined;
29844                 }
29845                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
29846                 if (sep === -1) {
29847                     return undefined;
29848                 }
29849                 return directory.substr(0, Math.max(sep, rootLength));
29850             }
29851         }
29852     }
29853     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
29854     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
29855         var containingDirectory = ts.getDirectoryPath(containingFile);
29856         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
29857         return perFolderCache && perFolderCache.get(moduleName);
29858     }
29859     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
29860     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
29861         var traceEnabled = isTraceEnabled(compilerOptions, host);
29862         if (redirectedReference) {
29863             compilerOptions = redirectedReference.commandLine.options;
29864         }
29865         if (traceEnabled) {
29866             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
29867             if (redirectedReference) {
29868                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29869             }
29870         }
29871         var containingDirectory = ts.getDirectoryPath(containingFile);
29872         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
29873         var result = perFolderCache && perFolderCache.get(moduleName);
29874         if (result) {
29875             if (traceEnabled) {
29876                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
29877             }
29878         }
29879         else {
29880             var moduleResolution = compilerOptions.moduleResolution;
29881             if (moduleResolution === undefined) {
29882                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
29883                 if (traceEnabled) {
29884                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
29885                 }
29886             }
29887             else {
29888                 if (traceEnabled) {
29889                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
29890                 }
29891             }
29892             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
29893             switch (moduleResolution) {
29894                 case ts.ModuleResolutionKind.NodeJs:
29895                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29896                     break;
29897                 case ts.ModuleResolutionKind.Classic:
29898                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29899                     break;
29900                 default:
29901                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
29902             }
29903             if (result && result.resolvedModule)
29904                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
29905             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
29906             if (perFolderCache) {
29907                 perFolderCache.set(moduleName, result);
29908                 if (!ts.isExternalModuleNameRelative(moduleName)) {
29909                     // put result in per-module name cache
29910                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
29911                 }
29912             }
29913         }
29914         if (traceEnabled) {
29915             if (result.resolvedModule) {
29916                 if (result.resolvedModule.packageId) {
29917                     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));
29918                 }
29919                 else {
29920                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
29921                 }
29922             }
29923             else {
29924                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
29925             }
29926         }
29927         return result;
29928     }
29929     ts.resolveModuleName = resolveModuleName;
29930     /**
29931      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
29932      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
29933      * can be resolved successfully by TypeScript compiler and runtime module loader.
29934      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
29935      * fallback to standard resolution routine.
29936      *
29937      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
29938      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
29939      * be '/a/b/c/d'
29940      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
29941      * will be resolved based on the content of the module name.
29942      * Structure of 'paths' compiler options
29943      * 'paths': {
29944      *    pattern-1: [...substitutions],
29945      *    pattern-2: [...substitutions],
29946      *    ...
29947      *    pattern-n: [...substitutions]
29948      * }
29949      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
29950      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
29951      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
29952      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
29953      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
29954      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
29955      * from the candidate location.
29956      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
29957      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
29958      * will be converted to absolute using baseUrl.
29959      * For example:
29960      * baseUrl: /a/b/c
29961      * "paths": {
29962      *     // match all module names
29963      *     "*": [
29964      *         "*",        // use matched name as is,
29965      *                     // <matched name> will be looked as /a/b/c/<matched name>
29966      *
29967      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
29968      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
29969      *     ],
29970      *     // match module names that start with 'components/'
29971      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
29972      *                                              // it is rooted so it will be final candidate location
29973      * }
29974      *
29975      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
29976      * they were in the same location. For example lets say there are two files
29977      * '/local/src/content/file1.ts'
29978      * '/shared/components/contracts/src/content/protocols/file2.ts'
29979      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
29980      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
29981      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
29982      * root dirs were merged together.
29983      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
29984      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
29985      * '/local/src/content/protocols/file2' and try to load it - failure.
29986      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
29987      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
29988      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
29989      */
29990     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
29991         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
29992         if (resolved)
29993             return resolved.value;
29994         if (!ts.isExternalModuleNameRelative(moduleName)) {
29995             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
29996         }
29997         else {
29998             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
29999         }
30000     }
30001     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
30002         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
30003         if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
30004             if (state.traceEnabled) {
30005                 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
30006                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
30007             }
30008             return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
30009         }
30010     }
30011     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
30012         if (!state.compilerOptions.rootDirs) {
30013             return undefined;
30014         }
30015         if (state.traceEnabled) {
30016             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
30017         }
30018         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30019         var matchedRootDir;
30020         var matchedNormalizedPrefix;
30021         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
30022             var rootDir = _a[_i];
30023             // rootDirs are expected to be absolute
30024             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
30025             // using location of tsconfig.json as base location
30026             var normalizedRoot = ts.normalizePath(rootDir);
30027             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
30028                 normalizedRoot += ts.directorySeparator;
30029             }
30030             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
30031                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
30032             if (state.traceEnabled) {
30033                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
30034             }
30035             if (isLongestMatchingPrefix) {
30036                 matchedNormalizedPrefix = normalizedRoot;
30037                 matchedRootDir = rootDir;
30038             }
30039         }
30040         if (matchedNormalizedPrefix) {
30041             if (state.traceEnabled) {
30042                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
30043             }
30044             var suffix = candidate.substr(matchedNormalizedPrefix.length);
30045             // first - try to load from a initial location
30046             if (state.traceEnabled) {
30047                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
30048             }
30049             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
30050             if (resolvedFileName) {
30051                 return resolvedFileName;
30052             }
30053             if (state.traceEnabled) {
30054                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
30055             }
30056             // then try to resolve using remaining entries in rootDirs
30057             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
30058                 var rootDir = _c[_b];
30059                 if (rootDir === matchedRootDir) {
30060                     // skip the initially matched entry
30061                     continue;
30062                 }
30063                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
30064                 if (state.traceEnabled) {
30065                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
30066                 }
30067                 var baseDirectory = ts.getDirectoryPath(candidate_1);
30068                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
30069                 if (resolvedFileName_1) {
30070                     return resolvedFileName_1;
30071                 }
30072             }
30073             if (state.traceEnabled) {
30074                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
30075             }
30076         }
30077         return undefined;
30078     }
30079     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
30080         var baseUrl = state.compilerOptions.baseUrl;
30081         if (!baseUrl) {
30082             return undefined;
30083         }
30084         if (state.traceEnabled) {
30085             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
30086         }
30087         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
30088         if (state.traceEnabled) {
30089             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
30090         }
30091         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30092     }
30093     /**
30094      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
30095      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
30096      * Throws an error if the module can't be resolved.
30097      */
30098     /* @internal */
30099     function resolveJSModule(moduleName, initialDir, host) {
30100         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
30101         if (!resolvedModule) {
30102             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
30103         }
30104         return resolvedModule.resolvedFileName;
30105     }
30106     ts.resolveJSModule = resolveJSModule;
30107     /* @internal */
30108     function tryResolveJSModule(moduleName, initialDir, host) {
30109         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
30110         return resolvedModule && resolvedModule.resolvedFileName;
30111     }
30112     ts.tryResolveJSModule = tryResolveJSModule;
30113     var jsOnlyExtensions = [Extensions.JavaScript];
30114     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
30115     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
30116     var tsconfigExtensions = [Extensions.TSConfig];
30117     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
30118         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
30119     }
30120     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
30121         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
30122     }
30123     ts.nodeModuleNameResolver = nodeModuleNameResolver;
30124     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
30125         var _a, _b;
30126         var traceEnabled = isTraceEnabled(compilerOptions, host);
30127         var failedLookupLocations = [];
30128         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30129         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
30130         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);
30131         function tryResolve(extensions) {
30132             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
30133             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
30134             if (resolved) {
30135                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
30136             }
30137             if (!ts.isExternalModuleNameRelative(moduleName)) {
30138                 if (traceEnabled) {
30139                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
30140                 }
30141                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
30142                 if (!resolved_1)
30143                     return undefined;
30144                 var resolvedValue = resolved_1.value;
30145                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
30146                     var path = realPath(resolvedValue.path, host, traceEnabled);
30147                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
30148                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
30149                 }
30150                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
30151                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
30152             }
30153             else {
30154                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
30155                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
30156                 // Treat explicit "node_modules" import as an external library import.
30157                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
30158             }
30159         }
30160     }
30161     function realPath(path, host, traceEnabled) {
30162         if (!host.realpath) {
30163             return path;
30164         }
30165         var real = ts.normalizePath(host.realpath(path));
30166         if (traceEnabled) {
30167             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
30168         }
30169         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
30170         return real;
30171     }
30172     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30173         if (state.traceEnabled) {
30174             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
30175         }
30176         if (!ts.hasTrailingDirectorySeparator(candidate)) {
30177             if (!onlyRecordFailures) {
30178                 var parentOfCandidate = ts.getDirectoryPath(candidate);
30179                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
30180                     if (state.traceEnabled) {
30181                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
30182                     }
30183                     onlyRecordFailures = true;
30184                 }
30185             }
30186             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
30187             if (resolvedFromFile) {
30188                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
30189                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
30190                 return withPackageId(packageInfo, resolvedFromFile);
30191             }
30192         }
30193         if (!onlyRecordFailures) {
30194             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
30195             if (!candidateExists) {
30196                 if (state.traceEnabled) {
30197                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
30198                 }
30199                 onlyRecordFailures = true;
30200             }
30201         }
30202         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
30203     }
30204     /*@internal*/
30205     ts.nodeModulesPathPart = "/node_modules/";
30206     /*@internal*/
30207     function pathContainsNodeModules(path) {
30208         return ts.stringContains(path, ts.nodeModulesPathPart);
30209     }
30210     ts.pathContainsNodeModules = pathContainsNodeModules;
30211     /**
30212      * This will be called on the successfully resolved path from `loadModuleFromFile`.
30213      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
30214      *
30215      * packageDirectory is the directory of the package itself.
30216      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
30217      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
30218      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
30219      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
30220      */
30221     function parseNodeModuleFromPath(resolved) {
30222         var path = ts.normalizePath(resolved.path);
30223         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
30224         if (idx === -1) {
30225             return undefined;
30226         }
30227         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
30228         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
30229         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
30230             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
30231         }
30232         return path.slice(0, indexAfterPackageName);
30233     }
30234     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
30235         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
30236         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
30237     }
30238     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
30239         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
30240     }
30241     /**
30242      * @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
30243      * 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.
30244      */
30245     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
30246         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
30247             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
30248             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
30249         }
30250         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
30251         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
30252         if (resolvedByAddingExtension) {
30253             return resolvedByAddingExtension;
30254         }
30255         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
30256         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
30257         if (ts.hasJSFileExtension(candidate)) {
30258             var extensionless = ts.removeFileExtension(candidate);
30259             if (state.traceEnabled) {
30260                 var extension = candidate.substring(extensionless.length);
30261                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
30262             }
30263             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
30264         }
30265     }
30266     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
30267     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
30268         if (!onlyRecordFailures) {
30269             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
30270             var directory = ts.getDirectoryPath(candidate);
30271             if (directory) {
30272                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
30273             }
30274         }
30275         switch (extensions) {
30276             case Extensions.DtsOnly:
30277                 return tryExtension(".d.ts" /* Dts */);
30278             case Extensions.TypeScript:
30279                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
30280             case Extensions.JavaScript:
30281                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
30282             case Extensions.TSConfig:
30283             case Extensions.Json:
30284                 return tryExtension(".json" /* Json */);
30285         }
30286         function tryExtension(ext) {
30287             var path = tryFile(candidate + ext, onlyRecordFailures, state);
30288             return path === undefined ? undefined : { path: path, ext: ext };
30289         }
30290     }
30291     /** Return the file if it exists. */
30292     function tryFile(fileName, onlyRecordFailures, state) {
30293         if (!onlyRecordFailures) {
30294             if (state.host.fileExists(fileName)) {
30295                 if (state.traceEnabled) {
30296                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
30297                 }
30298                 return fileName;
30299             }
30300             else {
30301                 if (state.traceEnabled) {
30302                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
30303                 }
30304             }
30305         }
30306         state.failedLookupLocations.push(fileName);
30307         return undefined;
30308     }
30309     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30310         if (considerPackageJson === void 0) { considerPackageJson = true; }
30311         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
30312         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
30313         var versionPaths = packageInfo && packageInfo.versionPaths;
30314         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
30315     }
30316     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
30317         var host = state.host, traceEnabled = state.traceEnabled;
30318         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
30319         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
30320         if (directoryExists && host.fileExists(packageJsonPath)) {
30321             var packageJsonContent = ts.readJson(packageJsonPath, host);
30322             if (traceEnabled) {
30323                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
30324             }
30325             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
30326             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
30327         }
30328         else {
30329             if (directoryExists && traceEnabled) {
30330                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
30331             }
30332             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
30333             state.failedLookupLocations.push(packageJsonPath);
30334         }
30335     }
30336     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
30337         var packageFile;
30338         if (jsonContent) {
30339             switch (extensions) {
30340                 case Extensions.JavaScript:
30341                 case Extensions.Json:
30342                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
30343                     break;
30344                 case Extensions.TypeScript:
30345                     // When resolving typescript modules, try resolving using main field as well
30346                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
30347                     break;
30348                 case Extensions.DtsOnly:
30349                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
30350                     break;
30351                 case Extensions.TSConfig:
30352                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
30353                     break;
30354                 default:
30355                     return ts.Debug.assertNever(extensions);
30356             }
30357         }
30358         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30359             var fromFile = tryFile(candidate, onlyRecordFailures, state);
30360             if (fromFile) {
30361                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
30362                 if (resolved) {
30363                     return noPackageId(resolved);
30364                 }
30365                 if (state.traceEnabled) {
30366                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
30367                 }
30368             }
30369             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
30370             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
30371             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
30372             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
30373         };
30374         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
30375         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
30376         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
30377         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
30378             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
30379             if (state.traceEnabled) {
30380                 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);
30381             }
30382             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
30383             if (result) {
30384                 return removeIgnoredPackageId(result.value);
30385             }
30386         }
30387         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
30388         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
30389         if (packageFileResult)
30390             return packageFileResult;
30391         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
30392     }
30393     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
30394     function resolvedIfExtensionMatches(extensions, path) {
30395         var ext = ts.tryGetExtensionFromPath(path);
30396         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
30397     }
30398     /** True if `extension` is one of the supported `extensions`. */
30399     function extensionIsOk(extensions, extension) {
30400         switch (extensions) {
30401             case Extensions.JavaScript:
30402                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
30403             case Extensions.TSConfig:
30404             case Extensions.Json:
30405                 return extension === ".json" /* Json */;
30406             case Extensions.TypeScript:
30407                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
30408             case Extensions.DtsOnly:
30409                 return extension === ".d.ts" /* Dts */;
30410         }
30411     }
30412     /* @internal */
30413     function parsePackageName(moduleName) {
30414         var idx = moduleName.indexOf(ts.directorySeparator);
30415         if (moduleName[0] === "@") {
30416             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
30417         }
30418         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
30419     }
30420     ts.parsePackageName = parsePackageName;
30421     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
30422         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
30423     }
30424     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
30425         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
30426         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
30427     }
30428     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
30429         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30430         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
30431             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
30432                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
30433                 if (resolutionFromCache) {
30434                     return resolutionFromCache;
30435                 }
30436                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
30437             }
30438         });
30439     }
30440     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
30441         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
30442         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
30443         if (!nodeModulesFolderExists && state.traceEnabled) {
30444             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
30445         }
30446         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
30447         if (packageResult) {
30448             return packageResult;
30449         }
30450         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
30451             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
30452             var nodeModulesAtTypesExists = nodeModulesFolderExists;
30453             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
30454                 if (state.traceEnabled) {
30455                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
30456                 }
30457                 nodeModulesAtTypesExists = false;
30458             }
30459             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
30460         }
30461     }
30462     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
30463         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
30464         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
30465         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
30466         if (packageInfo) {
30467             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
30468             if (fromFile) {
30469                 return noPackageId(fromFile);
30470             }
30471             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
30472             return withPackageId(packageInfo, fromDirectory);
30473         }
30474         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30475             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
30476                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
30477             return withPackageId(packageInfo, pathAndExtension);
30478         };
30479         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
30480         if (rest !== "") { // If "rest" is empty, we just did this search above.
30481             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
30482             // 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.
30483             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
30484             if (packageInfo && packageInfo.versionPaths) {
30485                 if (state.traceEnabled) {
30486                     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);
30487                 }
30488                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
30489                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
30490                 if (fromPaths) {
30491                     return fromPaths.value;
30492                 }
30493             }
30494         }
30495         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
30496     }
30497     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
30498         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
30499         if (matchedPattern) {
30500             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
30501             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
30502             if (state.traceEnabled) {
30503                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
30504             }
30505             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
30506                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
30507                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
30508                 if (state.traceEnabled) {
30509                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
30510                 }
30511                 // A path mapping may have an extension, in contrast to an import, which should omit it.
30512                 var extension = ts.tryGetExtensionFromPath(candidate);
30513                 if (extension !== undefined) {
30514                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
30515                     if (path_1 !== undefined) {
30516                         return noPackageId({ path: path_1, ext: extension });
30517                     }
30518                 }
30519                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30520             });
30521             return { value: resolved };
30522         }
30523     }
30524     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
30525     var mangledScopedPackageSeparator = "__";
30526     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
30527     function mangleScopedPackageNameWithTrace(packageName, state) {
30528         var mangled = mangleScopedPackageName(packageName);
30529         if (state.traceEnabled && mangled !== packageName) {
30530             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
30531         }
30532         return mangled;
30533     }
30534     /* @internal */
30535     function getTypesPackageName(packageName) {
30536         return "@types/" + mangleScopedPackageName(packageName);
30537     }
30538     ts.getTypesPackageName = getTypesPackageName;
30539     /* @internal */
30540     function mangleScopedPackageName(packageName) {
30541         if (ts.startsWith(packageName, "@")) {
30542             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
30543             if (replaceSlash !== packageName) {
30544                 return replaceSlash.slice(1); // Take off the "@"
30545             }
30546         }
30547         return packageName;
30548     }
30549     ts.mangleScopedPackageName = mangleScopedPackageName;
30550     /* @internal */
30551     function getPackageNameFromTypesPackageName(mangledName) {
30552         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
30553         if (withoutAtTypePrefix !== mangledName) {
30554             return unmangleScopedPackageName(withoutAtTypePrefix);
30555         }
30556         return mangledName;
30557     }
30558     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
30559     /* @internal */
30560     function unmangleScopedPackageName(typesPackageName) {
30561         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
30562             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
30563             typesPackageName;
30564     }
30565     ts.unmangleScopedPackageName = unmangleScopedPackageName;
30566     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
30567         var result = cache && cache.get(containingDirectory);
30568         if (result) {
30569             if (state.traceEnabled) {
30570                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
30571             }
30572             state.resultFromCache = result;
30573             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
30574         }
30575     }
30576     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
30577         var traceEnabled = isTraceEnabled(compilerOptions, host);
30578         var failedLookupLocations = [];
30579         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30580         var containingDirectory = ts.getDirectoryPath(containingFile);
30581         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
30582         // No originalPath because classic resolution doesn't resolve realPath
30583         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
30584         function tryResolve(extensions) {
30585             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
30586             if (resolvedUsingSettings) {
30587                 return { value: resolvedUsingSettings };
30588             }
30589             if (!ts.isExternalModuleNameRelative(moduleName)) {
30590                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30591                 // Climb up parent directories looking for a module.
30592                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
30593                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
30594                     if (resolutionFromCache) {
30595                         return resolutionFromCache;
30596                     }
30597                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
30598                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
30599                 });
30600                 if (resolved_3) {
30601                     return resolved_3;
30602                 }
30603                 if (extensions === Extensions.TypeScript) {
30604                     // If we didn't find the file normally, look it up in @types.
30605                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
30606                 }
30607             }
30608             else {
30609                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30610                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
30611             }
30612         }
30613     }
30614     ts.classicNameResolver = classicNameResolver;
30615     /**
30616      * A host may load a module from a global cache of typings.
30617      * This is the minumum code needed to expose that functionality; the rest is in the host.
30618      */
30619     /* @internal */
30620     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
30621         var traceEnabled = isTraceEnabled(compilerOptions, host);
30622         if (traceEnabled) {
30623             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);
30624         }
30625         var failedLookupLocations = [];
30626         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30627         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
30628         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
30629     }
30630     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
30631     /**
30632      * Wraps value to SearchResult.
30633      * @returns undefined if value is undefined or { value } otherwise
30634      */
30635     function toSearchResult(value) {
30636         return value !== undefined ? { value: value } : undefined;
30637     }
30638 })(ts || (ts = {}));
30639 /* @internal */
30640 var ts;
30641 (function (ts) {
30642     var ModuleInstanceState;
30643     (function (ModuleInstanceState) {
30644         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
30645         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
30646         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
30647     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
30648     function getModuleInstanceState(node, visited) {
30649         if (node.body && !node.body.parent) {
30650             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
30651             setParentPointers(node, node.body);
30652         }
30653         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
30654     }
30655     ts.getModuleInstanceState = getModuleInstanceState;
30656     function getModuleInstanceStateCached(node, visited) {
30657         if (visited === void 0) { visited = ts.createMap(); }
30658         var nodeId = "" + ts.getNodeId(node);
30659         if (visited.has(nodeId)) {
30660             return visited.get(nodeId) || 0 /* NonInstantiated */;
30661         }
30662         visited.set(nodeId, undefined);
30663         var result = getModuleInstanceStateWorker(node, visited);
30664         visited.set(nodeId, result);
30665         return result;
30666     }
30667     function getModuleInstanceStateWorker(node, visited) {
30668         // A module is uninstantiated if it contains only
30669         switch (node.kind) {
30670             // 1. interface declarations, type alias declarations
30671             case 246 /* InterfaceDeclaration */:
30672             case 247 /* TypeAliasDeclaration */:
30673                 return 0 /* NonInstantiated */;
30674             // 2. const enum declarations
30675             case 248 /* EnumDeclaration */:
30676                 if (ts.isEnumConst(node)) {
30677                     return 2 /* ConstEnumOnly */;
30678                 }
30679                 break;
30680             // 3. non-exported import declarations
30681             case 254 /* ImportDeclaration */:
30682             case 253 /* ImportEqualsDeclaration */:
30683                 if (!(ts.hasModifier(node, 1 /* Export */))) {
30684                     return 0 /* NonInstantiated */;
30685                 }
30686                 break;
30687             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
30688             case 260 /* ExportDeclaration */:
30689                 var exportDeclaration = node;
30690                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
30691                     var state = 0 /* NonInstantiated */;
30692                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
30693                         var specifier = _a[_i];
30694                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
30695                         if (specifierState > state) {
30696                             state = specifierState;
30697                         }
30698                         if (state === 1 /* Instantiated */) {
30699                             return state;
30700                         }
30701                     }
30702                     return state;
30703                 }
30704                 break;
30705             // 5. other uninstantiated module declarations.
30706             case 250 /* ModuleBlock */: {
30707                 var state_1 = 0 /* NonInstantiated */;
30708                 ts.forEachChild(node, function (n) {
30709                     var childState = getModuleInstanceStateCached(n, visited);
30710                     switch (childState) {
30711                         case 0 /* NonInstantiated */:
30712                             // child is non-instantiated - continue searching
30713                             return;
30714                         case 2 /* ConstEnumOnly */:
30715                             // child is const enum only - record state and continue searching
30716                             state_1 = 2 /* ConstEnumOnly */;
30717                             return;
30718                         case 1 /* Instantiated */:
30719                             // child is instantiated - record state and stop
30720                             state_1 = 1 /* Instantiated */;
30721                             return true;
30722                         default:
30723                             ts.Debug.assertNever(childState);
30724                     }
30725                 });
30726                 return state_1;
30727             }
30728             case 249 /* ModuleDeclaration */:
30729                 return getModuleInstanceState(node, visited);
30730             case 75 /* Identifier */:
30731                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
30732                 // be considered the same as type alias
30733                 if (node.isInJSDocNamespace) {
30734                     return 0 /* NonInstantiated */;
30735                 }
30736         }
30737         return 1 /* Instantiated */;
30738     }
30739     function getModuleInstanceStateForAliasTarget(specifier, visited) {
30740         var name = specifier.propertyName || specifier.name;
30741         var p = specifier.parent;
30742         while (p) {
30743             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
30744                 var statements = p.statements;
30745                 var found = void 0;
30746                 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
30747                     var statement = statements_1[_i];
30748                     if (ts.nodeHasName(statement, name)) {
30749                         if (!statement.parent) {
30750                             setParentPointers(p, statement);
30751                         }
30752                         var state = getModuleInstanceStateCached(statement, visited);
30753                         if (found === undefined || state > found) {
30754                             found = state;
30755                         }
30756                         if (found === 1 /* Instantiated */) {
30757                             return found;
30758                         }
30759                     }
30760                 }
30761                 if (found !== undefined) {
30762                     return found;
30763                 }
30764             }
30765             p = p.parent;
30766         }
30767         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
30768     }
30769     var ContainerFlags;
30770     (function (ContainerFlags) {
30771         // The current node is not a container, and no container manipulation should happen before
30772         // recursing into it.
30773         ContainerFlags[ContainerFlags["None"] = 0] = "None";
30774         // The current node is a container.  It should be set as the current container (and block-
30775         // container) before recursing into it.  The current node does not have locals.  Examples:
30776         //
30777         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
30778         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
30779         // The current node is a block-scoped-container.  It should be set as the current block-
30780         // container before recursing into it.  Examples:
30781         //
30782         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
30783         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
30784         // The current node is the container of a control flow path. The current control flow should
30785         // be saved and restored, and a new control flow initialized within the container.
30786         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
30787         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
30788         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
30789         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
30790         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
30791         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
30792     })(ContainerFlags || (ContainerFlags = {}));
30793     function initFlowNode(node) {
30794         ts.Debug.attachFlowNodeDebugInfo(node);
30795         return node;
30796     }
30797     var binder = createBinder();
30798     function bindSourceFile(file, options) {
30799         ts.performance.mark("beforeBind");
30800         ts.perfLogger.logStartBindFile("" + file.fileName);
30801         binder(file, options);
30802         ts.perfLogger.logStopBindFile();
30803         ts.performance.mark("afterBind");
30804         ts.performance.measure("Bind", "beforeBind", "afterBind");
30805     }
30806     ts.bindSourceFile = bindSourceFile;
30807     function createBinder() {
30808         var file;
30809         var options;
30810         var languageVersion;
30811         var parent;
30812         var container;
30813         var thisParentContainer; // Container one level up
30814         var blockScopeContainer;
30815         var lastContainer;
30816         var delayedTypeAliases;
30817         var seenThisKeyword;
30818         // state used by control flow analysis
30819         var currentFlow;
30820         var currentBreakTarget;
30821         var currentContinueTarget;
30822         var currentReturnTarget;
30823         var currentTrueTarget;
30824         var currentFalseTarget;
30825         var currentExceptionTarget;
30826         var preSwitchCaseFlow;
30827         var activeLabelList;
30828         var hasExplicitReturn;
30829         // state used for emit helpers
30830         var emitFlags;
30831         // If this file is an external module, then it is automatically in strict-mode according to
30832         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
30833         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
30834         // or if compiler options contain alwaysStrict.
30835         var inStrictMode;
30836         var symbolCount = 0;
30837         var Symbol;
30838         var classifiableNames;
30839         var unreachableFlow = { flags: 1 /* Unreachable */ };
30840         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
30841         // state used to aggregate transform flags during bind.
30842         var subtreeTransformFlags = 0 /* None */;
30843         var skipTransformFlagAggregation;
30844         /**
30845          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
30846          * 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)
30847          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
30848          */
30849         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
30850             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
30851         }
30852         function bindSourceFile(f, opts) {
30853             file = f;
30854             options = opts;
30855             languageVersion = ts.getEmitScriptTarget(options);
30856             inStrictMode = bindInStrictMode(file, opts);
30857             classifiableNames = ts.createUnderscoreEscapedMap();
30858             symbolCount = 0;
30859             skipTransformFlagAggregation = file.isDeclarationFile;
30860             Symbol = ts.objectAllocator.getSymbolConstructor();
30861             // Attach debugging information if necessary
30862             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
30863             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
30864             if (!file.locals) {
30865                 bind(file);
30866                 file.symbolCount = symbolCount;
30867                 file.classifiableNames = classifiableNames;
30868                 delayedBindJSDocTypedefTag();
30869             }
30870             file = undefined;
30871             options = undefined;
30872             languageVersion = undefined;
30873             parent = undefined;
30874             container = undefined;
30875             thisParentContainer = undefined;
30876             blockScopeContainer = undefined;
30877             lastContainer = undefined;
30878             delayedTypeAliases = undefined;
30879             seenThisKeyword = false;
30880             currentFlow = undefined;
30881             currentBreakTarget = undefined;
30882             currentContinueTarget = undefined;
30883             currentReturnTarget = undefined;
30884             currentTrueTarget = undefined;
30885             currentFalseTarget = undefined;
30886             currentExceptionTarget = undefined;
30887             activeLabelList = undefined;
30888             hasExplicitReturn = false;
30889             emitFlags = 0 /* None */;
30890             subtreeTransformFlags = 0 /* None */;
30891         }
30892         return bindSourceFile;
30893         function bindInStrictMode(file, opts) {
30894             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
30895                 // bind in strict mode source files with alwaysStrict option
30896                 return true;
30897             }
30898             else {
30899                 return !!file.externalModuleIndicator;
30900             }
30901         }
30902         function createSymbol(flags, name) {
30903             symbolCount++;
30904             return new Symbol(flags, name);
30905         }
30906         function addDeclarationToSymbol(symbol, node, symbolFlags) {
30907             symbol.flags |= symbolFlags;
30908             node.symbol = symbol;
30909             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
30910             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
30911                 symbol.exports = ts.createSymbolTable();
30912             }
30913             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
30914                 symbol.members = ts.createSymbolTable();
30915             }
30916             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
30917             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
30918                 symbol.constEnumOnlyModule = false;
30919             }
30920             if (symbolFlags & 111551 /* Value */) {
30921                 ts.setValueDeclaration(symbol, node);
30922             }
30923         }
30924         // Should not be called on a declaration with a computed property name,
30925         // unless it is a well known Symbol.
30926         function getDeclarationName(node) {
30927             if (node.kind === 259 /* ExportAssignment */) {
30928                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
30929             }
30930             var name = ts.getNameOfDeclaration(node);
30931             if (name) {
30932                 if (ts.isAmbientModule(node)) {
30933                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
30934                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
30935                 }
30936                 if (name.kind === 154 /* ComputedPropertyName */) {
30937                     var nameExpression = name.expression;
30938                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
30939                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
30940                         return ts.escapeLeadingUnderscores(nameExpression.text);
30941                     }
30942                     if (ts.isSignedNumericLiteral(nameExpression)) {
30943                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
30944                     }
30945                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
30946                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
30947                 }
30948                 if (ts.isWellKnownSymbolSyntactically(name)) {
30949                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
30950                 }
30951                 if (ts.isPrivateIdentifier(name)) {
30952                     // containingClass exists because private names only allowed inside classes
30953                     var containingClass = ts.getContainingClass(node);
30954                     if (!containingClass) {
30955                         // we can get here in cases where there is already a parse error.
30956                         return undefined;
30957                     }
30958                     var containingClassSymbol = containingClass.symbol;
30959                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
30960                 }
30961                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
30962             }
30963             switch (node.kind) {
30964                 case 162 /* Constructor */:
30965                     return "__constructor" /* Constructor */;
30966                 case 170 /* FunctionType */:
30967                 case 165 /* CallSignature */:
30968                 case 305 /* JSDocSignature */:
30969                     return "__call" /* Call */;
30970                 case 171 /* ConstructorType */:
30971                 case 166 /* ConstructSignature */:
30972                     return "__new" /* New */;
30973                 case 167 /* IndexSignature */:
30974                     return "__index" /* Index */;
30975                 case 260 /* ExportDeclaration */:
30976                     return "__export" /* ExportStar */;
30977                 case 290 /* SourceFile */:
30978                     // json file should behave as
30979                     // module.exports = ...
30980                     return "export=" /* ExportEquals */;
30981                 case 209 /* BinaryExpression */:
30982                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
30983                         // module.exports = ...
30984                         return "export=" /* ExportEquals */;
30985                     }
30986                     ts.Debug.fail("Unknown binary declaration kind");
30987                     break;
30988                 case 300 /* JSDocFunctionType */:
30989                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
30990                 case 156 /* Parameter */:
30991                     // Parameters with names are handled at the top of this function.  Parameters
30992                     // without names can only come from JSDocFunctionTypes.
30993                     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"; });
30994                     var functionType = node.parent;
30995                     var index = functionType.parameters.indexOf(node);
30996                     return "arg" + index;
30997             }
30998         }
30999         function getDisplayName(node) {
31000             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
31001         }
31002         /**
31003          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
31004          * @param symbolTable - The symbol table which node will be added to.
31005          * @param parent - node's parent declaration.
31006          * @param node - The declaration to be added to the symbol table
31007          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
31008          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
31009          */
31010         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
31011             ts.Debug.assert(!ts.hasDynamicName(node));
31012             var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
31013             // The exported symbol for an export default function/class node is always named "default"
31014             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
31015             var symbol;
31016             if (name === undefined) {
31017                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
31018             }
31019             else {
31020                 // Check and see if the symbol table already has a symbol with this name.  If not,
31021                 // create a new symbol with this name and add it to the table.  Note that we don't
31022                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
31023                 // with the 'excludes' flags we pass in.
31024                 //
31025                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
31026                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
31027                 // the same symbol table.  If we have a conflict, report the issue on each
31028                 // declaration we have for this symbol, and then create a new symbol for this
31029                 // declaration.
31030                 //
31031                 // Note that when properties declared in Javascript constructors
31032                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
31033                 // Always. This allows the common Javascript pattern of overwriting a prototype method
31034                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
31035                 //
31036                 // If we created a new symbol, either because we didn't have a symbol with this name
31037                 // in the symbol table, or we conflicted with an existing symbol, then just add this
31038                 // node as the sole declaration of the new symbol.
31039                 //
31040                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
31041                 // you have multiple 'vars' with the same name in the same container).  In this case
31042                 // just add this node into the declarations list of the symbol.
31043                 symbol = symbolTable.get(name);
31044                 if (includes & 2885600 /* Classifiable */) {
31045                     classifiableNames.set(name, true);
31046                 }
31047                 if (!symbol) {
31048                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
31049                     if (isReplaceableByMethod)
31050                         symbol.isReplaceableByMethod = true;
31051                 }
31052                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
31053                     // A symbol already exists, so don't add this as a declaration.
31054                     return symbol;
31055                 }
31056                 else if (symbol.flags & excludes) {
31057                     if (symbol.isReplaceableByMethod) {
31058                         // Javascript constructor-declared symbols can be discarded in favor of
31059                         // prototype symbols like methods.
31060                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
31061                     }
31062                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
31063                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
31064                         if (ts.isNamedDeclaration(node)) {
31065                             node.name.parent = node;
31066                         }
31067                         // Report errors every position with duplicate declaration
31068                         // Report errors on previous encountered declarations
31069                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
31070                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
31071                             : ts.Diagnostics.Duplicate_identifier_0;
31072                         var messageNeedsName_1 = true;
31073                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
31074                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
31075                             messageNeedsName_1 = false;
31076                         }
31077                         var multipleDefaultExports_1 = false;
31078                         if (ts.length(symbol.declarations)) {
31079                             // If the current node is a default export of some sort, then check if
31080                             // there are any other default exports that we need to error on.
31081                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
31082                             if (isDefaultExport) {
31083                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
31084                                 messageNeedsName_1 = false;
31085                                 multipleDefaultExports_1 = true;
31086                             }
31087                             else {
31088                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
31089                                 // Error on multiple export default in the following case:
31090                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
31091                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
31092                                 if (symbol.declarations && symbol.declarations.length &&
31093                                     (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
31094                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
31095                                     messageNeedsName_1 = false;
31096                                     multipleDefaultExports_1 = true;
31097                                 }
31098                             }
31099                         }
31100                         var relatedInformation_1 = [];
31101                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
31102                             // export type T; - may have meant export type { T }?
31103                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
31104                         }
31105                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
31106                         ts.forEach(symbol.declarations, function (declaration, index) {
31107                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
31108                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
31109                             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);
31110                             if (multipleDefaultExports_1) {
31111                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
31112                             }
31113                         });
31114                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
31115                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
31116                         symbol = createSymbol(0 /* None */, name);
31117                     }
31118                 }
31119             }
31120             addDeclarationToSymbol(symbol, node, includes);
31121             if (symbol.parent) {
31122                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
31123             }
31124             else {
31125                 symbol.parent = parent;
31126             }
31127             return symbol;
31128         }
31129         function declareModuleMember(node, symbolFlags, symbolExcludes) {
31130             var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
31131             if (symbolFlags & 2097152 /* Alias */) {
31132                 if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
31133                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31134                 }
31135                 else {
31136                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31137                 }
31138             }
31139             else {
31140                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
31141                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
31142                 //
31143                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
31144                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
31145                 //      with the same name in the same container.
31146                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
31147                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
31148                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
31149                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
31150                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
31151                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
31152                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
31153                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
31154                 if (ts.isJSDocTypeAlias(node))
31155                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
31156                 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
31157                     if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
31158                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
31159                     }
31160                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
31161                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
31162                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31163                     node.localSymbol = local;
31164                     return local;
31165                 }
31166                 else {
31167                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31168                 }
31169             }
31170         }
31171         // All container nodes are kept on a linked list in declaration order. This list is used by
31172         // the getLocalNameOfContainer function in the type checker to validate that the local name
31173         // used for a container is unique.
31174         function bindContainer(node, containerFlags) {
31175             // Before we recurse into a node's children, we first save the existing parent, container
31176             // and block-container.  Then after we pop out of processing the children, we restore
31177             // these saved values.
31178             var saveContainer = container;
31179             var saveThisParentContainer = thisParentContainer;
31180             var savedBlockScopeContainer = blockScopeContainer;
31181             // Depending on what kind of node this is, we may have to adjust the current container
31182             // and block-container.   If the current node is a container, then it is automatically
31183             // considered the current block-container as well.  Also, for containers that we know
31184             // may contain locals, we eagerly initialize the .locals field. We do this because
31185             // it's highly likely that the .locals will be needed to place some child in (for example,
31186             // a parameter, or variable declaration).
31187             //
31188             // However, we do not proactively create the .locals for block-containers because it's
31189             // totally normal and common for block-containers to never actually have a block-scoped
31190             // variable in them.  We don't want to end up allocating an object for every 'block' we
31191             // run into when most of them won't be necessary.
31192             //
31193             // Finally, if this is a block-container, then we clear out any existing .locals object
31194             // it may contain within it.  This happens in incremental scenarios.  Because we can be
31195             // reusing a node from a previous compilation, that node may have had 'locals' created
31196             // for it.  We must clear this so we don't accidentally move any stale data forward from
31197             // a previous compilation.
31198             if (containerFlags & 1 /* IsContainer */) {
31199                 if (node.kind !== 202 /* ArrowFunction */) {
31200                     thisParentContainer = container;
31201                 }
31202                 container = blockScopeContainer = node;
31203                 if (containerFlags & 32 /* HasLocals */) {
31204                     container.locals = ts.createSymbolTable();
31205                 }
31206                 addToContainerChain(container);
31207             }
31208             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
31209                 blockScopeContainer = node;
31210                 blockScopeContainer.locals = undefined;
31211             }
31212             if (containerFlags & 4 /* IsControlFlowContainer */) {
31213                 var saveCurrentFlow = currentFlow;
31214                 var saveBreakTarget = currentBreakTarget;
31215                 var saveContinueTarget = currentContinueTarget;
31216                 var saveReturnTarget = currentReturnTarget;
31217                 var saveExceptionTarget = currentExceptionTarget;
31218                 var saveActiveLabelList = activeLabelList;
31219                 var saveHasExplicitReturn = hasExplicitReturn;
31220                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
31221                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
31222                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
31223                 // similarly to break statements that exit to a label just past the statement body.
31224                 if (!isIIFE) {
31225                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
31226                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
31227                         currentFlow.node = node;
31228                     }
31229                 }
31230                 // We create a return control flow graph for IIFEs and constructors. For constructors
31231                 // we use the return control flow graph in strict property initialization checks.
31232                 currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
31233                 currentExceptionTarget = undefined;
31234                 currentBreakTarget = undefined;
31235                 currentContinueTarget = undefined;
31236                 activeLabelList = undefined;
31237                 hasExplicitReturn = false;
31238                 bindChildren(node);
31239                 // Reset all reachability check related flags on node (for incremental scenarios)
31240                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
31241                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
31242                     node.flags |= 256 /* HasImplicitReturn */;
31243                     if (hasExplicitReturn)
31244                         node.flags |= 512 /* HasExplicitReturn */;
31245                     node.endFlowNode = currentFlow;
31246                 }
31247                 if (node.kind === 290 /* SourceFile */) {
31248                     node.flags |= emitFlags;
31249                 }
31250                 if (currentReturnTarget) {
31251                     addAntecedent(currentReturnTarget, currentFlow);
31252                     currentFlow = finishFlowLabel(currentReturnTarget);
31253                     if (node.kind === 162 /* Constructor */) {
31254                         node.returnFlowNode = currentFlow;
31255                     }
31256                 }
31257                 if (!isIIFE) {
31258                     currentFlow = saveCurrentFlow;
31259                 }
31260                 currentBreakTarget = saveBreakTarget;
31261                 currentContinueTarget = saveContinueTarget;
31262                 currentReturnTarget = saveReturnTarget;
31263                 currentExceptionTarget = saveExceptionTarget;
31264                 activeLabelList = saveActiveLabelList;
31265                 hasExplicitReturn = saveHasExplicitReturn;
31266             }
31267             else if (containerFlags & 64 /* IsInterface */) {
31268                 seenThisKeyword = false;
31269                 bindChildren(node);
31270                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
31271             }
31272             else {
31273                 bindChildren(node);
31274             }
31275             container = saveContainer;
31276             thisParentContainer = saveThisParentContainer;
31277             blockScopeContainer = savedBlockScopeContainer;
31278         }
31279         function bindChildren(node) {
31280             if (skipTransformFlagAggregation) {
31281                 bindChildrenWorker(node);
31282             }
31283             else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31284                 skipTransformFlagAggregation = true;
31285                 bindChildrenWorker(node);
31286                 skipTransformFlagAggregation = false;
31287                 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31288             }
31289             else {
31290                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31291                 subtreeTransformFlags = 0;
31292                 bindChildrenWorker(node);
31293                 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
31294             }
31295         }
31296         function bindEachFunctionsFirst(nodes) {
31297             bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31298             bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31299         }
31300         function bindEach(nodes, bindFunction) {
31301             if (bindFunction === void 0) { bindFunction = bind; }
31302             if (nodes === undefined) {
31303                 return;
31304             }
31305             if (skipTransformFlagAggregation) {
31306                 ts.forEach(nodes, bindFunction);
31307             }
31308             else {
31309                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31310                 subtreeTransformFlags = 0 /* None */;
31311                 var nodeArrayFlags = 0 /* None */;
31312                 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
31313                     var node = nodes_2[_i];
31314                     bindFunction(node);
31315                     nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
31316                 }
31317                 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
31318                 subtreeTransformFlags |= savedSubtreeTransformFlags;
31319             }
31320         }
31321         function bindEachChild(node) {
31322             ts.forEachChild(node, bind, bindEach);
31323         }
31324         function bindChildrenWorker(node) {
31325             if (checkUnreachable(node)) {
31326                 bindEachChild(node);
31327                 bindJSDoc(node);
31328                 return;
31329             }
31330             if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
31331                 node.flowNode = currentFlow;
31332             }
31333             switch (node.kind) {
31334                 case 229 /* WhileStatement */:
31335                     bindWhileStatement(node);
31336                     break;
31337                 case 228 /* DoStatement */:
31338                     bindDoStatement(node);
31339                     break;
31340                 case 230 /* ForStatement */:
31341                     bindForStatement(node);
31342                     break;
31343                 case 231 /* ForInStatement */:
31344                 case 232 /* ForOfStatement */:
31345                     bindForInOrForOfStatement(node);
31346                     break;
31347                 case 227 /* IfStatement */:
31348                     bindIfStatement(node);
31349                     break;
31350                 case 235 /* ReturnStatement */:
31351                 case 239 /* ThrowStatement */:
31352                     bindReturnOrThrow(node);
31353                     break;
31354                 case 234 /* BreakStatement */:
31355                 case 233 /* ContinueStatement */:
31356                     bindBreakOrContinueStatement(node);
31357                     break;
31358                 case 240 /* TryStatement */:
31359                     bindTryStatement(node);
31360                     break;
31361                 case 237 /* SwitchStatement */:
31362                     bindSwitchStatement(node);
31363                     break;
31364                 case 251 /* CaseBlock */:
31365                     bindCaseBlock(node);
31366                     break;
31367                 case 277 /* CaseClause */:
31368                     bindCaseClause(node);
31369                     break;
31370                 case 226 /* ExpressionStatement */:
31371                     bindExpressionStatement(node);
31372                     break;
31373                 case 238 /* LabeledStatement */:
31374                     bindLabeledStatement(node);
31375                     break;
31376                 case 207 /* PrefixUnaryExpression */:
31377                     bindPrefixUnaryExpressionFlow(node);
31378                     break;
31379                 case 208 /* PostfixUnaryExpression */:
31380                     bindPostfixUnaryExpressionFlow(node);
31381                     break;
31382                 case 209 /* BinaryExpression */:
31383                     bindBinaryExpressionFlow(node);
31384                     break;
31385                 case 203 /* DeleteExpression */:
31386                     bindDeleteExpressionFlow(node);
31387                     break;
31388                 case 210 /* ConditionalExpression */:
31389                     bindConditionalExpressionFlow(node);
31390                     break;
31391                 case 242 /* VariableDeclaration */:
31392                     bindVariableDeclarationFlow(node);
31393                     break;
31394                 case 194 /* PropertyAccessExpression */:
31395                 case 195 /* ElementAccessExpression */:
31396                     bindAccessExpressionFlow(node);
31397                     break;
31398                 case 196 /* CallExpression */:
31399                     bindCallExpressionFlow(node);
31400                     break;
31401                 case 218 /* NonNullExpression */:
31402                     bindNonNullExpressionFlow(node);
31403                     break;
31404                 case 322 /* JSDocTypedefTag */:
31405                 case 315 /* JSDocCallbackTag */:
31406                 case 316 /* JSDocEnumTag */:
31407                     bindJSDocTypeAlias(node);
31408                     break;
31409                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
31410                 case 290 /* SourceFile */: {
31411                     bindEachFunctionsFirst(node.statements);
31412                     bind(node.endOfFileToken);
31413                     break;
31414                 }
31415                 case 223 /* Block */:
31416                 case 250 /* ModuleBlock */:
31417                     bindEachFunctionsFirst(node.statements);
31418                     break;
31419                 default:
31420                     bindEachChild(node);
31421                     break;
31422             }
31423             bindJSDoc(node);
31424         }
31425         function isNarrowingExpression(expr) {
31426             switch (expr.kind) {
31427                 case 75 /* Identifier */:
31428                 case 104 /* ThisKeyword */:
31429                 case 194 /* PropertyAccessExpression */:
31430                 case 195 /* ElementAccessExpression */:
31431                     return containsNarrowableReference(expr);
31432                 case 196 /* CallExpression */:
31433                     return hasNarrowableArgument(expr);
31434                 case 200 /* ParenthesizedExpression */:
31435                     return isNarrowingExpression(expr.expression);
31436                 case 209 /* BinaryExpression */:
31437                     return isNarrowingBinaryExpression(expr);
31438                 case 207 /* PrefixUnaryExpression */:
31439                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
31440                 case 204 /* TypeOfExpression */:
31441                     return isNarrowingExpression(expr.expression);
31442             }
31443             return false;
31444         }
31445         function isNarrowableReference(expr) {
31446             return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
31447                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
31448                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
31449         }
31450         function containsNarrowableReference(expr) {
31451             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
31452         }
31453         function hasNarrowableArgument(expr) {
31454             if (expr.arguments) {
31455                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
31456                     var argument = _a[_i];
31457                     if (containsNarrowableReference(argument)) {
31458                         return true;
31459                     }
31460                 }
31461             }
31462             if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
31463                 containsNarrowableReference(expr.expression.expression)) {
31464                 return true;
31465             }
31466             return false;
31467         }
31468         function isNarrowingTypeofOperands(expr1, expr2) {
31469             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
31470         }
31471         function isNarrowableInOperands(left, right) {
31472             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
31473         }
31474         function isNarrowingBinaryExpression(expr) {
31475             switch (expr.operatorToken.kind) {
31476                 case 62 /* EqualsToken */:
31477                     return containsNarrowableReference(expr.left);
31478                 case 34 /* EqualsEqualsToken */:
31479                 case 35 /* ExclamationEqualsToken */:
31480                 case 36 /* EqualsEqualsEqualsToken */:
31481                 case 37 /* ExclamationEqualsEqualsToken */:
31482                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
31483                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
31484                 case 98 /* InstanceOfKeyword */:
31485                     return isNarrowableOperand(expr.left);
31486                 case 97 /* InKeyword */:
31487                     return isNarrowableInOperands(expr.left, expr.right);
31488                 case 27 /* CommaToken */:
31489                     return isNarrowingExpression(expr.right);
31490             }
31491             return false;
31492         }
31493         function isNarrowableOperand(expr) {
31494             switch (expr.kind) {
31495                 case 200 /* ParenthesizedExpression */:
31496                     return isNarrowableOperand(expr.expression);
31497                 case 209 /* BinaryExpression */:
31498                     switch (expr.operatorToken.kind) {
31499                         case 62 /* EqualsToken */:
31500                             return isNarrowableOperand(expr.left);
31501                         case 27 /* CommaToken */:
31502                             return isNarrowableOperand(expr.right);
31503                     }
31504             }
31505             return containsNarrowableReference(expr);
31506         }
31507         function createBranchLabel() {
31508             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
31509         }
31510         function createLoopLabel() {
31511             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
31512         }
31513         function createReduceLabel(target, antecedents, antecedent) {
31514             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
31515         }
31516         function setFlowNodeReferenced(flow) {
31517             // On first reference we set the Referenced flag, thereafter we set the Shared flag
31518             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
31519         }
31520         function addAntecedent(label, antecedent) {
31521             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
31522                 (label.antecedents || (label.antecedents = [])).push(antecedent);
31523                 setFlowNodeReferenced(antecedent);
31524             }
31525         }
31526         function createFlowCondition(flags, antecedent, expression) {
31527             if (antecedent.flags & 1 /* Unreachable */) {
31528                 return antecedent;
31529             }
31530             if (!expression) {
31531                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
31532             }
31533             if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
31534                 expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
31535                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
31536                 return unreachableFlow;
31537             }
31538             if (!isNarrowingExpression(expression)) {
31539                 return antecedent;
31540             }
31541             setFlowNodeReferenced(antecedent);
31542             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
31543         }
31544         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
31545             setFlowNodeReferenced(antecedent);
31546             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
31547         }
31548         function createFlowMutation(flags, antecedent, node) {
31549             setFlowNodeReferenced(antecedent);
31550             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
31551             if (currentExceptionTarget) {
31552                 addAntecedent(currentExceptionTarget, result);
31553             }
31554             return result;
31555         }
31556         function createFlowCall(antecedent, node) {
31557             setFlowNodeReferenced(antecedent);
31558             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
31559         }
31560         function finishFlowLabel(flow) {
31561             var antecedents = flow.antecedents;
31562             if (!antecedents) {
31563                 return unreachableFlow;
31564             }
31565             if (antecedents.length === 1) {
31566                 return antecedents[0];
31567             }
31568             return flow;
31569         }
31570         function isStatementCondition(node) {
31571             var parent = node.parent;
31572             switch (parent.kind) {
31573                 case 227 /* IfStatement */:
31574                 case 229 /* WhileStatement */:
31575                 case 228 /* DoStatement */:
31576                     return parent.expression === node;
31577                 case 230 /* ForStatement */:
31578                 case 210 /* ConditionalExpression */:
31579                     return parent.condition === node;
31580             }
31581             return false;
31582         }
31583         function isLogicalExpression(node) {
31584             while (true) {
31585                 if (node.kind === 200 /* ParenthesizedExpression */) {
31586                     node = node.expression;
31587                 }
31588                 else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
31589                     node = node.operand;
31590                 }
31591                 else {
31592                     return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
31593                         node.operatorToken.kind === 56 /* BarBarToken */ ||
31594                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
31595                 }
31596             }
31597         }
31598         function isTopLevelLogicalExpression(node) {
31599             while (ts.isParenthesizedExpression(node.parent) ||
31600                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
31601                 node = node.parent;
31602             }
31603             return !isStatementCondition(node) &&
31604                 !isLogicalExpression(node.parent) &&
31605                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
31606         }
31607         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
31608             var savedTrueTarget = currentTrueTarget;
31609             var savedFalseTarget = currentFalseTarget;
31610             currentTrueTarget = trueTarget;
31611             currentFalseTarget = falseTarget;
31612             action(value);
31613             currentTrueTarget = savedTrueTarget;
31614             currentFalseTarget = savedFalseTarget;
31615         }
31616         function bindCondition(node, trueTarget, falseTarget) {
31617             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
31618             if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
31619                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
31620                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
31621             }
31622         }
31623         function bindIterativeStatement(node, breakTarget, continueTarget) {
31624             var saveBreakTarget = currentBreakTarget;
31625             var saveContinueTarget = currentContinueTarget;
31626             currentBreakTarget = breakTarget;
31627             currentContinueTarget = continueTarget;
31628             bind(node);
31629             currentBreakTarget = saveBreakTarget;
31630             currentContinueTarget = saveContinueTarget;
31631         }
31632         function setContinueTarget(node, target) {
31633             var label = activeLabelList;
31634             while (label && node.parent.kind === 238 /* LabeledStatement */) {
31635                 label.continueTarget = target;
31636                 label = label.next;
31637                 node = node.parent;
31638             }
31639             return target;
31640         }
31641         function bindWhileStatement(node) {
31642             var preWhileLabel = setContinueTarget(node, createLoopLabel());
31643             var preBodyLabel = createBranchLabel();
31644             var postWhileLabel = createBranchLabel();
31645             addAntecedent(preWhileLabel, currentFlow);
31646             currentFlow = preWhileLabel;
31647             bindCondition(node.expression, preBodyLabel, postWhileLabel);
31648             currentFlow = finishFlowLabel(preBodyLabel);
31649             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
31650             addAntecedent(preWhileLabel, currentFlow);
31651             currentFlow = finishFlowLabel(postWhileLabel);
31652         }
31653         function bindDoStatement(node) {
31654             var preDoLabel = createLoopLabel();
31655             var preConditionLabel = setContinueTarget(node, createBranchLabel());
31656             var postDoLabel = createBranchLabel();
31657             addAntecedent(preDoLabel, currentFlow);
31658             currentFlow = preDoLabel;
31659             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
31660             addAntecedent(preConditionLabel, currentFlow);
31661             currentFlow = finishFlowLabel(preConditionLabel);
31662             bindCondition(node.expression, preDoLabel, postDoLabel);
31663             currentFlow = finishFlowLabel(postDoLabel);
31664         }
31665         function bindForStatement(node) {
31666             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31667             var preBodyLabel = createBranchLabel();
31668             var postLoopLabel = createBranchLabel();
31669             bind(node.initializer);
31670             addAntecedent(preLoopLabel, currentFlow);
31671             currentFlow = preLoopLabel;
31672             bindCondition(node.condition, preBodyLabel, postLoopLabel);
31673             currentFlow = finishFlowLabel(preBodyLabel);
31674             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31675             bind(node.incrementor);
31676             addAntecedent(preLoopLabel, currentFlow);
31677             currentFlow = finishFlowLabel(postLoopLabel);
31678         }
31679         function bindForInOrForOfStatement(node) {
31680             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31681             var postLoopLabel = createBranchLabel();
31682             bind(node.expression);
31683             addAntecedent(preLoopLabel, currentFlow);
31684             currentFlow = preLoopLabel;
31685             if (node.kind === 232 /* ForOfStatement */) {
31686                 bind(node.awaitModifier);
31687             }
31688             addAntecedent(postLoopLabel, currentFlow);
31689             bind(node.initializer);
31690             if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
31691                 bindAssignmentTargetFlow(node.initializer);
31692             }
31693             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31694             addAntecedent(preLoopLabel, currentFlow);
31695             currentFlow = finishFlowLabel(postLoopLabel);
31696         }
31697         function bindIfStatement(node) {
31698             var thenLabel = createBranchLabel();
31699             var elseLabel = createBranchLabel();
31700             var postIfLabel = createBranchLabel();
31701             bindCondition(node.expression, thenLabel, elseLabel);
31702             currentFlow = finishFlowLabel(thenLabel);
31703             bind(node.thenStatement);
31704             addAntecedent(postIfLabel, currentFlow);
31705             currentFlow = finishFlowLabel(elseLabel);
31706             bind(node.elseStatement);
31707             addAntecedent(postIfLabel, currentFlow);
31708             currentFlow = finishFlowLabel(postIfLabel);
31709         }
31710         function bindReturnOrThrow(node) {
31711             bind(node.expression);
31712             if (node.kind === 235 /* ReturnStatement */) {
31713                 hasExplicitReturn = true;
31714                 if (currentReturnTarget) {
31715                     addAntecedent(currentReturnTarget, currentFlow);
31716                 }
31717             }
31718             currentFlow = unreachableFlow;
31719         }
31720         function findActiveLabel(name) {
31721             for (var label = activeLabelList; label; label = label.next) {
31722                 if (label.name === name) {
31723                     return label;
31724                 }
31725             }
31726             return undefined;
31727         }
31728         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
31729             var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
31730             if (flowLabel) {
31731                 addAntecedent(flowLabel, currentFlow);
31732                 currentFlow = unreachableFlow;
31733             }
31734         }
31735         function bindBreakOrContinueStatement(node) {
31736             bind(node.label);
31737             if (node.label) {
31738                 var activeLabel = findActiveLabel(node.label.escapedText);
31739                 if (activeLabel) {
31740                     activeLabel.referenced = true;
31741                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
31742                 }
31743             }
31744             else {
31745                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
31746             }
31747         }
31748         function bindTryStatement(node) {
31749             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
31750             // to track code that causes mutations (because only mutations widen the possible control flow type of
31751             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
31752             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
31753             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
31754             // represent exceptions that occur before any mutations.
31755             var saveReturnTarget = currentReturnTarget;
31756             var saveExceptionTarget = currentExceptionTarget;
31757             var normalExitLabel = createBranchLabel();
31758             var returnLabel = createBranchLabel();
31759             var exceptionLabel = createBranchLabel();
31760             if (node.finallyBlock) {
31761                 currentReturnTarget = returnLabel;
31762             }
31763             addAntecedent(exceptionLabel, currentFlow);
31764             currentExceptionTarget = exceptionLabel;
31765             bind(node.tryBlock);
31766             addAntecedent(normalExitLabel, currentFlow);
31767             if (node.catchClause) {
31768                 // Start of catch clause is the target of exceptions from try block.
31769                 currentFlow = finishFlowLabel(exceptionLabel);
31770                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
31771                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
31772                 // acts like a second try block.
31773                 exceptionLabel = createBranchLabel();
31774                 addAntecedent(exceptionLabel, currentFlow);
31775                 currentExceptionTarget = exceptionLabel;
31776                 bind(node.catchClause);
31777                 addAntecedent(normalExitLabel, currentFlow);
31778             }
31779             currentReturnTarget = saveReturnTarget;
31780             currentExceptionTarget = saveExceptionTarget;
31781             if (node.finallyBlock) {
31782                 // Possible ways control can reach the finally block:
31783                 // 1) Normal completion of try block of a try-finally or try-catch-finally
31784                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
31785                 // 3) Return in try or catch block of a try-finally or try-catch-finally
31786                 // 4) Exception in try block of a try-finally
31787                 // 5) Exception in catch block of a try-catch-finally
31788                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
31789                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
31790                 // the finally block, we only want to consider the first two (if we're past a finally block then it
31791                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
31792                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
31793                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
31794                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
31795                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
31796                 var finallyLabel = createBranchLabel();
31797                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
31798                 currentFlow = finallyLabel;
31799                 bind(node.finallyBlock);
31800                 if (currentFlow.flags & 1 /* Unreachable */) {
31801                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
31802                     currentFlow = unreachableFlow;
31803                 }
31804                 else {
31805                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
31806                     // flow that goes back through the finally block and back through only the return statements.
31807                     if (currentReturnTarget && returnLabel.antecedents) {
31808                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
31809                     }
31810                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
31811                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
31812                     // result in an unreachable current control flow.
31813                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
31814                 }
31815             }
31816             else {
31817                 currentFlow = finishFlowLabel(normalExitLabel);
31818             }
31819         }
31820         function bindSwitchStatement(node) {
31821             var postSwitchLabel = createBranchLabel();
31822             bind(node.expression);
31823             var saveBreakTarget = currentBreakTarget;
31824             var savePreSwitchCaseFlow = preSwitchCaseFlow;
31825             currentBreakTarget = postSwitchLabel;
31826             preSwitchCaseFlow = currentFlow;
31827             bind(node.caseBlock);
31828             addAntecedent(postSwitchLabel, currentFlow);
31829             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
31830             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
31831             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
31832             // this property in control flow analysis, it's there only for backwards compatibility.
31833             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
31834             if (!hasDefault) {
31835                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
31836             }
31837             currentBreakTarget = saveBreakTarget;
31838             preSwitchCaseFlow = savePreSwitchCaseFlow;
31839             currentFlow = finishFlowLabel(postSwitchLabel);
31840         }
31841         function bindCaseBlock(node) {
31842             var savedSubtreeTransformFlags = subtreeTransformFlags;
31843             subtreeTransformFlags = 0;
31844             var clauses = node.clauses;
31845             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
31846             var fallthroughFlow = unreachableFlow;
31847             for (var i = 0; i < clauses.length; i++) {
31848                 var clauseStart = i;
31849                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
31850                     bind(clauses[i]);
31851                     i++;
31852                 }
31853                 var preCaseLabel = createBranchLabel();
31854                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
31855                 addAntecedent(preCaseLabel, fallthroughFlow);
31856                 currentFlow = finishFlowLabel(preCaseLabel);
31857                 var clause = clauses[i];
31858                 bind(clause);
31859                 fallthroughFlow = currentFlow;
31860                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
31861                     clause.fallthroughFlowNode = currentFlow;
31862                 }
31863             }
31864             clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
31865             subtreeTransformFlags |= savedSubtreeTransformFlags;
31866         }
31867         function bindCaseClause(node) {
31868             var saveCurrentFlow = currentFlow;
31869             currentFlow = preSwitchCaseFlow;
31870             bind(node.expression);
31871             currentFlow = saveCurrentFlow;
31872             bindEach(node.statements);
31873         }
31874         function bindExpressionStatement(node) {
31875             bind(node.expression);
31876             // A top level call expression with a dotted function name and at least one argument
31877             // is potentially an assertion and is therefore included in the control flow.
31878             if (node.expression.kind === 196 /* CallExpression */) {
31879                 var call = node.expression;
31880                 if (ts.isDottedName(call.expression)) {
31881                     currentFlow = createFlowCall(currentFlow, call);
31882                 }
31883             }
31884         }
31885         function bindLabeledStatement(node) {
31886             var postStatementLabel = createBranchLabel();
31887             activeLabelList = {
31888                 next: activeLabelList,
31889                 name: node.label.escapedText,
31890                 breakTarget: postStatementLabel,
31891                 continueTarget: undefined,
31892                 referenced: false
31893             };
31894             bind(node.label);
31895             bind(node.statement);
31896             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
31897                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
31898             }
31899             activeLabelList = activeLabelList.next;
31900             addAntecedent(postStatementLabel, currentFlow);
31901             currentFlow = finishFlowLabel(postStatementLabel);
31902         }
31903         function bindDestructuringTargetFlow(node) {
31904             if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
31905                 bindAssignmentTargetFlow(node.left);
31906             }
31907             else {
31908                 bindAssignmentTargetFlow(node);
31909             }
31910         }
31911         function bindAssignmentTargetFlow(node) {
31912             if (isNarrowableReference(node)) {
31913                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31914             }
31915             else if (node.kind === 192 /* ArrayLiteralExpression */) {
31916                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
31917                     var e = _a[_i];
31918                     if (e.kind === 213 /* SpreadElement */) {
31919                         bindAssignmentTargetFlow(e.expression);
31920                     }
31921                     else {
31922                         bindDestructuringTargetFlow(e);
31923                     }
31924                 }
31925             }
31926             else if (node.kind === 193 /* ObjectLiteralExpression */) {
31927                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
31928                     var p = _c[_b];
31929                     if (p.kind === 281 /* PropertyAssignment */) {
31930                         bindDestructuringTargetFlow(p.initializer);
31931                     }
31932                     else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
31933                         bindAssignmentTargetFlow(p.name);
31934                     }
31935                     else if (p.kind === 283 /* SpreadAssignment */) {
31936                         bindAssignmentTargetFlow(p.expression);
31937                     }
31938                 }
31939             }
31940         }
31941         function bindLogicalExpression(node, trueTarget, falseTarget) {
31942             var preRightLabel = createBranchLabel();
31943             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
31944                 bindCondition(node.left, preRightLabel, falseTarget);
31945             }
31946             else {
31947                 bindCondition(node.left, trueTarget, preRightLabel);
31948             }
31949             currentFlow = finishFlowLabel(preRightLabel);
31950             bind(node.operatorToken);
31951             bindCondition(node.right, trueTarget, falseTarget);
31952         }
31953         function bindPrefixUnaryExpressionFlow(node) {
31954             if (node.operator === 53 /* ExclamationToken */) {
31955                 var saveTrueTarget = currentTrueTarget;
31956                 currentTrueTarget = currentFalseTarget;
31957                 currentFalseTarget = saveTrueTarget;
31958                 bindEachChild(node);
31959                 currentFalseTarget = currentTrueTarget;
31960                 currentTrueTarget = saveTrueTarget;
31961             }
31962             else {
31963                 bindEachChild(node);
31964                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31965                     bindAssignmentTargetFlow(node.operand);
31966                 }
31967             }
31968         }
31969         function bindPostfixUnaryExpressionFlow(node) {
31970             bindEachChild(node);
31971             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31972                 bindAssignmentTargetFlow(node.operand);
31973             }
31974         }
31975         var BindBinaryExpressionFlowState;
31976         (function (BindBinaryExpressionFlowState) {
31977             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
31978             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
31979             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
31980             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
31981             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
31982         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
31983         function bindBinaryExpressionFlow(node) {
31984             var workStacks = {
31985                 expr: [node],
31986                 state: [1 /* MaybeBindLeft */],
31987                 inStrictMode: [undefined],
31988                 parent: [undefined],
31989                 subtreeFlags: [undefined]
31990             };
31991             var stackIndex = 0;
31992             while (stackIndex >= 0) {
31993                 node = workStacks.expr[stackIndex];
31994                 switch (workStacks.state[stackIndex]) {
31995                     case 0 /* BindThenBindChildren */: {
31996                         // This state is used only when recuring, to emulate the work that `bind` does before
31997                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
31998                         node.parent = parent;
31999                         var saveInStrictMode = inStrictMode;
32000                         bindWorker(node);
32001                         var saveParent = parent;
32002                         parent = node;
32003                         var subtreeFlagsState = void 0;
32004                         // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
32005                         // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
32006                         if (skipTransformFlagAggregation) {
32007                             // do nothing extra
32008                         }
32009                         else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
32010                             skipTransformFlagAggregation = true;
32011                             subtreeFlagsState = -1;
32012                         }
32013                         else {
32014                             var savedSubtreeTransformFlags = subtreeTransformFlags;
32015                             subtreeTransformFlags = 0;
32016                             subtreeFlagsState = savedSubtreeTransformFlags;
32017                         }
32018                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
32019                         break;
32020                     }
32021                     case 1 /* MaybeBindLeft */: {
32022                         var operator = node.operatorToken.kind;
32023                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
32024                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
32025                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
32026                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
32027                             if (isTopLevelLogicalExpression(node)) {
32028                                 var postExpressionLabel = createBranchLabel();
32029                                 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
32030                                 currentFlow = finishFlowLabel(postExpressionLabel);
32031                             }
32032                             else {
32033                                 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
32034                             }
32035                             completeNode();
32036                         }
32037                         else {
32038                             advanceState(2 /* BindToken */);
32039                             maybeBind(node.left);
32040                         }
32041                         break;
32042                     }
32043                     case 2 /* BindToken */: {
32044                         advanceState(3 /* BindRight */);
32045                         maybeBind(node.operatorToken);
32046                         break;
32047                     }
32048                     case 3 /* BindRight */: {
32049                         advanceState(4 /* FinishBind */);
32050                         maybeBind(node.right);
32051                         break;
32052                     }
32053                     case 4 /* FinishBind */: {
32054                         var operator = node.operatorToken.kind;
32055                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
32056                             bindAssignmentTargetFlow(node.left);
32057                             if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
32058                                 var elementAccess = node.left;
32059                                 if (isNarrowableOperand(elementAccess.expression)) {
32060                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32061                                 }
32062                             }
32063                         }
32064                         completeNode();
32065                         break;
32066                     }
32067                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
32068                 }
32069             }
32070             /**
32071              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
32072              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
32073              */
32074             function advanceState(state, isInStrictMode, parent, subtreeFlags) {
32075                 workStacks.state[stackIndex] = state;
32076                 if (isInStrictMode !== undefined) {
32077                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
32078                 }
32079                 if (parent !== undefined) {
32080                     workStacks.parent[stackIndex] = parent;
32081                 }
32082                 if (subtreeFlags !== undefined) {
32083                     workStacks.subtreeFlags[stackIndex] = subtreeFlags;
32084                 }
32085             }
32086             function completeNode() {
32087                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
32088                     if (workStacks.subtreeFlags[stackIndex] === -1) {
32089                         skipTransformFlagAggregation = false;
32090                         subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
32091                     }
32092                     else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
32093                         subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
32094                     }
32095                     inStrictMode = workStacks.inStrictMode[stackIndex];
32096                     parent = workStacks.parent[stackIndex];
32097                 }
32098                 stackIndex--;
32099             }
32100             /**
32101              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
32102              */
32103             function maybeBind(node) {
32104                 if (node && ts.isBinaryExpression(node)) {
32105                     stackIndex++;
32106                     workStacks.expr[stackIndex] = node;
32107                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
32108                     workStacks.inStrictMode[stackIndex] = undefined;
32109                     workStacks.parent[stackIndex] = undefined;
32110                     workStacks.subtreeFlags[stackIndex] = undefined;
32111                 }
32112                 else {
32113                     bind(node);
32114                 }
32115             }
32116         }
32117         function bindDeleteExpressionFlow(node) {
32118             bindEachChild(node);
32119             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32120                 bindAssignmentTargetFlow(node.expression);
32121             }
32122         }
32123         function bindConditionalExpressionFlow(node) {
32124             var trueLabel = createBranchLabel();
32125             var falseLabel = createBranchLabel();
32126             var postExpressionLabel = createBranchLabel();
32127             bindCondition(node.condition, trueLabel, falseLabel);
32128             currentFlow = finishFlowLabel(trueLabel);
32129             bind(node.questionToken);
32130             bind(node.whenTrue);
32131             addAntecedent(postExpressionLabel, currentFlow);
32132             currentFlow = finishFlowLabel(falseLabel);
32133             bind(node.colonToken);
32134             bind(node.whenFalse);
32135             addAntecedent(postExpressionLabel, currentFlow);
32136             currentFlow = finishFlowLabel(postExpressionLabel);
32137         }
32138         function bindInitializedVariableFlow(node) {
32139             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
32140             if (ts.isBindingPattern(name)) {
32141                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
32142                     var child = _a[_i];
32143                     bindInitializedVariableFlow(child);
32144                 }
32145             }
32146             else {
32147                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
32148             }
32149         }
32150         function bindVariableDeclarationFlow(node) {
32151             bindEachChild(node);
32152             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
32153                 bindInitializedVariableFlow(node);
32154             }
32155         }
32156         function bindJSDocTypeAlias(node) {
32157             node.tagName.parent = node;
32158             if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
32159                 setParentPointers(node, node.fullName);
32160             }
32161         }
32162         function bindJSDocClassTag(node) {
32163             bindEachChild(node);
32164             var host = ts.getHostSignatureFromJSDoc(node);
32165             if (host && host.kind !== 161 /* MethodDeclaration */) {
32166                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
32167             }
32168         }
32169         function bindOptionalExpression(node, trueTarget, falseTarget) {
32170             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
32171             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
32172                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32173                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32174             }
32175         }
32176         function bindOptionalChainRest(node) {
32177             switch (node.kind) {
32178                 case 194 /* PropertyAccessExpression */:
32179                     bind(node.questionDotToken);
32180                     bind(node.name);
32181                     break;
32182                 case 195 /* ElementAccessExpression */:
32183                     bind(node.questionDotToken);
32184                     bind(node.argumentExpression);
32185                     break;
32186                 case 196 /* CallExpression */:
32187                     bind(node.questionDotToken);
32188                     bindEach(node.typeArguments);
32189                     bindEach(node.arguments);
32190                     break;
32191             }
32192         }
32193         function bindOptionalChain(node, trueTarget, falseTarget) {
32194             // For an optional chain, we emulate the behavior of a logical expression:
32195             //
32196             // a?.b         -> a && a.b
32197             // a?.b.c       -> a && a.b.c
32198             // a?.b?.c      -> a && a.b && a.b.c
32199             // a?.[x = 1]   -> a && a[x = 1]
32200             //
32201             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
32202             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
32203             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
32204             // chain node. We then treat the entire node as the right side of the expression.
32205             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
32206             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
32207             if (preChainLabel) {
32208                 currentFlow = finishFlowLabel(preChainLabel);
32209             }
32210             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
32211             if (ts.isOutermostOptionalChain(node)) {
32212                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32213                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32214             }
32215         }
32216         function bindOptionalChainFlow(node) {
32217             if (isTopLevelLogicalExpression(node)) {
32218                 var postExpressionLabel = createBranchLabel();
32219                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
32220                 currentFlow = finishFlowLabel(postExpressionLabel);
32221             }
32222             else {
32223                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
32224             }
32225         }
32226         function bindNonNullExpressionFlow(node) {
32227             if (ts.isOptionalChain(node)) {
32228                 bindOptionalChainFlow(node);
32229             }
32230             else {
32231                 bindEachChild(node);
32232             }
32233         }
32234         function bindAccessExpressionFlow(node) {
32235             if (ts.isOptionalChain(node)) {
32236                 bindOptionalChainFlow(node);
32237             }
32238             else {
32239                 bindEachChild(node);
32240             }
32241         }
32242         function bindCallExpressionFlow(node) {
32243             if (ts.isOptionalChain(node)) {
32244                 bindOptionalChainFlow(node);
32245             }
32246             else {
32247                 // If the target of the call expression is a function expression or arrow function we have
32248                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
32249                 // the current control flow (which includes evaluation of the IIFE arguments).
32250                 var expr = ts.skipParentheses(node.expression);
32251                 if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
32252                     bindEach(node.typeArguments);
32253                     bindEach(node.arguments);
32254                     bind(node.expression);
32255                 }
32256                 else {
32257                     bindEachChild(node);
32258                 }
32259             }
32260             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32261                 var propertyAccess = node.expression;
32262                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
32263                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32264                 }
32265             }
32266         }
32267         function getContainerFlags(node) {
32268             switch (node.kind) {
32269                 case 214 /* ClassExpression */:
32270                 case 245 /* ClassDeclaration */:
32271                 case 248 /* EnumDeclaration */:
32272                 case 193 /* ObjectLiteralExpression */:
32273                 case 173 /* TypeLiteral */:
32274                 case 304 /* JSDocTypeLiteral */:
32275                 case 274 /* JsxAttributes */:
32276                     return 1 /* IsContainer */;
32277                 case 246 /* InterfaceDeclaration */:
32278                     return 1 /* IsContainer */ | 64 /* IsInterface */;
32279                 case 249 /* ModuleDeclaration */:
32280                 case 247 /* TypeAliasDeclaration */:
32281                 case 186 /* MappedType */:
32282                     return 1 /* IsContainer */ | 32 /* HasLocals */;
32283                 case 290 /* SourceFile */:
32284                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
32285                 case 161 /* MethodDeclaration */:
32286                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
32287                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
32288                     }
32289                 // falls through
32290                 case 162 /* Constructor */:
32291                 case 244 /* FunctionDeclaration */:
32292                 case 160 /* MethodSignature */:
32293                 case 163 /* GetAccessor */:
32294                 case 164 /* SetAccessor */:
32295                 case 165 /* CallSignature */:
32296                 case 305 /* JSDocSignature */:
32297                 case 300 /* JSDocFunctionType */:
32298                 case 170 /* FunctionType */:
32299                 case 166 /* ConstructSignature */:
32300                 case 167 /* IndexSignature */:
32301                 case 171 /* ConstructorType */:
32302                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
32303                 case 201 /* FunctionExpression */:
32304                 case 202 /* ArrowFunction */:
32305                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
32306                 case 250 /* ModuleBlock */:
32307                     return 4 /* IsControlFlowContainer */;
32308                 case 159 /* PropertyDeclaration */:
32309                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
32310                 case 280 /* CatchClause */:
32311                 case 230 /* ForStatement */:
32312                 case 231 /* ForInStatement */:
32313                 case 232 /* ForOfStatement */:
32314                 case 251 /* CaseBlock */:
32315                     return 2 /* IsBlockScopedContainer */;
32316                 case 223 /* Block */:
32317                     // do not treat blocks directly inside a function as a block-scoped-container.
32318                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
32319                     // would not appear to be a redeclaration of a block scoped local in the following
32320                     // example:
32321                     //
32322                     //      function foo() {
32323                     //          var x;
32324                     //          let x;
32325                     //      }
32326                     //
32327                     // If we placed 'var x' into the function locals and 'let x' into the locals of
32328                     // the block, then there would be no collision.
32329                     //
32330                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
32331                     // and 'let x' go into the Function-container's locals, and we do get a collision
32332                     // conflict.
32333                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
32334             }
32335             return 0 /* None */;
32336         }
32337         function addToContainerChain(next) {
32338             if (lastContainer) {
32339                 lastContainer.nextContainer = next;
32340             }
32341             lastContainer = next;
32342         }
32343         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
32344             switch (container.kind) {
32345                 // Modules, source files, and classes need specialized handling for how their
32346                 // members are declared (for example, a member of a class will go into a specific
32347                 // symbol table depending on if it is static or not). We defer to specialized
32348                 // handlers to take care of declaring these child members.
32349                 case 249 /* ModuleDeclaration */:
32350                     return declareModuleMember(node, symbolFlags, symbolExcludes);
32351                 case 290 /* SourceFile */:
32352                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
32353                 case 214 /* ClassExpression */:
32354                 case 245 /* ClassDeclaration */:
32355                     return declareClassMember(node, symbolFlags, symbolExcludes);
32356                 case 248 /* EnumDeclaration */:
32357                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
32358                 case 173 /* TypeLiteral */:
32359                 case 304 /* JSDocTypeLiteral */:
32360                 case 193 /* ObjectLiteralExpression */:
32361                 case 246 /* InterfaceDeclaration */:
32362                 case 274 /* JsxAttributes */:
32363                     // Interface/Object-types always have their children added to the 'members' of
32364                     // their container. They are only accessible through an instance of their
32365                     // container, and are never in scope otherwise (even inside the body of the
32366                     // object / type / interface declaring them). An exception is type parameters,
32367                     // which are in scope without qualification (similar to 'locals').
32368                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32369                 case 170 /* FunctionType */:
32370                 case 171 /* ConstructorType */:
32371                 case 165 /* CallSignature */:
32372                 case 166 /* ConstructSignature */:
32373                 case 305 /* JSDocSignature */:
32374                 case 167 /* IndexSignature */:
32375                 case 161 /* MethodDeclaration */:
32376                 case 160 /* MethodSignature */:
32377                 case 162 /* Constructor */:
32378                 case 163 /* GetAccessor */:
32379                 case 164 /* SetAccessor */:
32380                 case 244 /* FunctionDeclaration */:
32381                 case 201 /* FunctionExpression */:
32382                 case 202 /* ArrowFunction */:
32383                 case 300 /* JSDocFunctionType */:
32384                 case 322 /* JSDocTypedefTag */:
32385                 case 315 /* JSDocCallbackTag */:
32386                 case 247 /* TypeAliasDeclaration */:
32387                 case 186 /* MappedType */:
32388                     // All the children of these container types are never visible through another
32389                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
32390                     // they're only accessed 'lexically' (i.e. from code that exists underneath
32391                     // their container in the tree). To accomplish this, we simply add their declared
32392                     // symbol to the 'locals' of the container.  These symbols can then be found as
32393                     // the type checker walks up the containers, checking them for matching names.
32394                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32395             }
32396         }
32397         function declareClassMember(node, symbolFlags, symbolExcludes) {
32398             return ts.hasModifier(node, 32 /* Static */)
32399                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
32400                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32401         }
32402         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
32403             return ts.isExternalModule(file)
32404                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
32405                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32406         }
32407         function hasExportDeclarations(node) {
32408             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
32409             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
32410         }
32411         function setExportContextFlag(node) {
32412             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
32413             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
32414             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
32415                 node.flags |= 64 /* ExportContext */;
32416             }
32417             else {
32418                 node.flags &= ~64 /* ExportContext */;
32419             }
32420         }
32421         function bindModuleDeclaration(node) {
32422             setExportContextFlag(node);
32423             if (ts.isAmbientModule(node)) {
32424                 if (ts.hasModifier(node, 1 /* Export */)) {
32425                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
32426                 }
32427                 if (ts.isModuleAugmentationExternal(node)) {
32428                     declareModuleSymbol(node);
32429                 }
32430                 else {
32431                     var pattern = void 0;
32432                     if (node.name.kind === 10 /* StringLiteral */) {
32433                         var text = node.name.text;
32434                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
32435                             pattern = ts.tryParsePattern(text);
32436                         }
32437                         else {
32438                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
32439                         }
32440                     }
32441                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
32442                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
32443                 }
32444             }
32445             else {
32446                 var state = declareModuleSymbol(node);
32447                 if (state !== 0 /* NonInstantiated */) {
32448                     var symbol = node.symbol;
32449                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
32450                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
32451                         // Current must be `const enum` only
32452                         && state === 2 /* ConstEnumOnly */
32453                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
32454                         && symbol.constEnumOnlyModule !== false;
32455                 }
32456             }
32457         }
32458         function declareModuleSymbol(node) {
32459             var state = getModuleInstanceState(node);
32460             var instantiated = state !== 0 /* NonInstantiated */;
32461             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
32462             return state;
32463         }
32464         function bindFunctionOrConstructorType(node) {
32465             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
32466             // to the one we would get for: { <...>(...): T }
32467             //
32468             // We do that by making an anonymous type literal symbol, and then setting the function
32469             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
32470             // from an actual type literal symbol you would have gotten had you used the long form.
32471             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
32472             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
32473             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
32474             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
32475             typeLiteralSymbol.members = ts.createSymbolTable();
32476             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
32477         }
32478         function bindObjectLiteralExpression(node) {
32479             var ElementKind;
32480             (function (ElementKind) {
32481                 ElementKind[ElementKind["Property"] = 1] = "Property";
32482                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
32483             })(ElementKind || (ElementKind = {}));
32484             if (inStrictMode && !ts.isAssignmentTarget(node)) {
32485                 var seen = ts.createUnderscoreEscapedMap();
32486                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
32487                     var prop = _a[_i];
32488                     if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
32489                         continue;
32490                     }
32491                     var identifier = prop.name;
32492                     // ECMA-262 11.1.5 Object Initializer
32493                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
32494                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
32495                     // IsDataDescriptor(propId.descriptor) is true.
32496                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
32497                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
32498                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
32499                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
32500                     var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
32501                         ? 1 /* Property */
32502                         : 2 /* Accessor */;
32503                     var existingKind = seen.get(identifier.escapedText);
32504                     if (!existingKind) {
32505                         seen.set(identifier.escapedText, currentKind);
32506                         continue;
32507                     }
32508                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
32509                         var span = ts.getErrorSpanForNode(file, identifier);
32510                         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));
32511                     }
32512                 }
32513             }
32514             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
32515         }
32516         function bindJsxAttributes(node) {
32517             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
32518         }
32519         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
32520             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
32521         }
32522         function bindAnonymousDeclaration(node, symbolFlags, name) {
32523             var symbol = createSymbol(symbolFlags, name);
32524             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
32525                 symbol.parent = container.symbol;
32526             }
32527             addDeclarationToSymbol(symbol, node, symbolFlags);
32528             return symbol;
32529         }
32530         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
32531             switch (blockScopeContainer.kind) {
32532                 case 249 /* ModuleDeclaration */:
32533                     declareModuleMember(node, symbolFlags, symbolExcludes);
32534                     break;
32535                 case 290 /* SourceFile */:
32536                     if (ts.isExternalOrCommonJsModule(container)) {
32537                         declareModuleMember(node, symbolFlags, symbolExcludes);
32538                         break;
32539                     }
32540                 // falls through
32541                 default:
32542                     if (!blockScopeContainer.locals) {
32543                         blockScopeContainer.locals = ts.createSymbolTable();
32544                         addToContainerChain(blockScopeContainer);
32545                     }
32546                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32547             }
32548         }
32549         function delayedBindJSDocTypedefTag() {
32550             if (!delayedTypeAliases) {
32551                 return;
32552             }
32553             var saveContainer = container;
32554             var saveLastContainer = lastContainer;
32555             var saveBlockScopeContainer = blockScopeContainer;
32556             var saveParent = parent;
32557             var saveCurrentFlow = currentFlow;
32558             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
32559                 var typeAlias = delayedTypeAliases_1[_i];
32560                 var host = ts.getJSDocHost(typeAlias);
32561                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
32562                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
32563                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
32564                 parent = typeAlias;
32565                 bind(typeAlias.typeExpression);
32566                 var declName = ts.getNameOfDeclaration(typeAlias);
32567                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
32568                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
32569                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
32570                     if (isTopLevel) {
32571                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
32572                         var oldContainer = container;
32573                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
32574                             case 1 /* ExportsProperty */:
32575                             case 2 /* ModuleExports */:
32576                                 if (!ts.isExternalOrCommonJsModule(file)) {
32577                                     container = undefined;
32578                                 }
32579                                 else {
32580                                     container = file;
32581                                 }
32582                                 break;
32583                             case 4 /* ThisProperty */:
32584                                 container = declName.parent.expression;
32585                                 break;
32586                             case 3 /* PrototypeProperty */:
32587                                 container = declName.parent.expression.name;
32588                                 break;
32589                             case 5 /* Property */:
32590                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
32591                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
32592                                         : declName.parent.expression;
32593                                 break;
32594                             case 0 /* None */:
32595                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
32596                         }
32597                         if (container) {
32598                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32599                         }
32600                         container = oldContainer;
32601                     }
32602                 }
32603                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
32604                     parent = typeAlias.parent;
32605                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32606                 }
32607                 else {
32608                     bind(typeAlias.fullName);
32609                 }
32610             }
32611             container = saveContainer;
32612             lastContainer = saveLastContainer;
32613             blockScopeContainer = saveBlockScopeContainer;
32614             parent = saveParent;
32615             currentFlow = saveCurrentFlow;
32616         }
32617         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
32618         // check for reserved words used as identifiers in strict mode code.
32619         function checkStrictModeIdentifier(node) {
32620             if (inStrictMode &&
32621                 node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
32622                 node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
32623                 !ts.isIdentifierName(node) &&
32624                 !(node.flags & 8388608 /* Ambient */) &&
32625                 !(node.flags & 4194304 /* JSDoc */)) {
32626                 // Report error only if there are no parse errors in file
32627                 if (!file.parseDiagnostics.length) {
32628                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
32629                 }
32630             }
32631         }
32632         function getStrictModeIdentifierMessage(node) {
32633             // Provide specialized messages to help the user understand why we think they're in
32634             // strict mode.
32635             if (ts.getContainingClass(node)) {
32636                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
32637             }
32638             if (file.externalModuleIndicator) {
32639                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
32640             }
32641             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
32642         }
32643         // The binder visits every node, so this is a good place to check for
32644         // the reserved private name (there is only one)
32645         function checkPrivateIdentifier(node) {
32646             if (node.escapedText === "#constructor") {
32647                 // Report error only if there are no parse errors in file
32648                 if (!file.parseDiagnostics.length) {
32649                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
32650                 }
32651             }
32652         }
32653         function checkStrictModeBinaryExpression(node) {
32654             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
32655                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32656                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
32657                 checkStrictModeEvalOrArguments(node, node.left);
32658             }
32659         }
32660         function checkStrictModeCatchClause(node) {
32661             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
32662             // Catch production is eval or arguments
32663             if (inStrictMode && node.variableDeclaration) {
32664                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
32665             }
32666         }
32667         function checkStrictModeDeleteExpression(node) {
32668             // Grammar checking
32669             if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
32670                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
32671                 // UnaryExpression is a direct reference to a variable, function argument, or function name
32672                 var span = ts.getErrorSpanForNode(file, node.expression);
32673                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
32674             }
32675         }
32676         function isEvalOrArgumentsIdentifier(node) {
32677             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
32678         }
32679         function checkStrictModeEvalOrArguments(contextNode, name) {
32680             if (name && name.kind === 75 /* Identifier */) {
32681                 var identifier = name;
32682                 if (isEvalOrArgumentsIdentifier(identifier)) {
32683                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32684                     // otherwise report generic error message.
32685                     var span = ts.getErrorSpanForNode(file, name);
32686                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
32687                 }
32688             }
32689         }
32690         function getStrictModeEvalOrArgumentsMessage(node) {
32691             // Provide specialized messages to help the user understand why we think they're in
32692             // strict mode.
32693             if (ts.getContainingClass(node)) {
32694                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
32695             }
32696             if (file.externalModuleIndicator) {
32697                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
32698             }
32699             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
32700         }
32701         function checkStrictModeFunctionName(node) {
32702             if (inStrictMode) {
32703                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
32704                 checkStrictModeEvalOrArguments(node, node.name);
32705             }
32706         }
32707         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
32708             // Provide specialized messages to help the user understand why we think they're in
32709             // strict mode.
32710             if (ts.getContainingClass(node)) {
32711                 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;
32712             }
32713             if (file.externalModuleIndicator) {
32714                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
32715             }
32716             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
32717         }
32718         function checkStrictModeFunctionDeclaration(node) {
32719             if (languageVersion < 2 /* ES2015 */) {
32720                 // Report error if function is not top level function declaration
32721                 if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
32722                     blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
32723                     !ts.isFunctionLike(blockScopeContainer)) {
32724                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32725                     // otherwise report generic error message.
32726                     var errorSpan = ts.getErrorSpanForNode(file, node);
32727                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
32728                 }
32729             }
32730         }
32731         function checkStrictModeNumericLiteral(node) {
32732             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
32733                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
32734             }
32735         }
32736         function checkStrictModePostfixUnaryExpression(node) {
32737             // Grammar checking
32738             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32739             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
32740             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
32741             if (inStrictMode) {
32742                 checkStrictModeEvalOrArguments(node, node.operand);
32743             }
32744         }
32745         function checkStrictModePrefixUnaryExpression(node) {
32746             // Grammar checking
32747             if (inStrictMode) {
32748                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
32749                     checkStrictModeEvalOrArguments(node, node.operand);
32750                 }
32751             }
32752         }
32753         function checkStrictModeWithStatement(node) {
32754             // Grammar checking for withStatement
32755             if (inStrictMode) {
32756                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
32757             }
32758         }
32759         function checkStrictModeLabeledStatement(node) {
32760             // Grammar checking for labeledStatement
32761             if (inStrictMode && options.target >= 2 /* ES2015 */) {
32762                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
32763                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
32764                 }
32765             }
32766         }
32767         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
32768             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
32769             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
32770         }
32771         function errorOrSuggestionOnNode(isError, node, message) {
32772             errorOrSuggestionOnRange(isError, node, node, message);
32773         }
32774         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
32775             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
32776         }
32777         function addErrorOrSuggestionDiagnostic(isError, range, message) {
32778             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
32779             if (isError) {
32780                 file.bindDiagnostics.push(diag);
32781             }
32782             else {
32783                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
32784             }
32785         }
32786         function bind(node) {
32787             if (!node) {
32788                 return;
32789             }
32790             node.parent = parent;
32791             var saveInStrictMode = inStrictMode;
32792             // Even though in the AST the jsdoc @typedef node belongs to the current node,
32793             // its symbol might be in the same scope with the current node's symbol. Consider:
32794             //
32795             //     /** @typedef {string | number} MyType */
32796             //     function foo();
32797             //
32798             // Here the current node is "foo", which is a container, but the scope of "MyType" should
32799             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
32800             // and skip binding this tag later when binding all the other jsdoc tags.
32801             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
32802             // and then potentially add the symbol to an appropriate symbol table. Possible
32803             // destination symbol tables are:
32804             //
32805             //  1) The 'exports' table of the current container's symbol.
32806             //  2) The 'members' table of the current container's symbol.
32807             //  3) The 'locals' table of the current container.
32808             //
32809             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
32810             // (like TypeLiterals for example) will not be put in any table.
32811             bindWorker(node);
32812             // Then we recurse into the children of the node to bind them as well. For certain
32813             // symbols we do specialized work when we recurse. For example, we'll keep track of
32814             // the current 'container' node when it changes. This helps us know which symbol table
32815             // a local should go into for example. Since terminal nodes are known not to have
32816             // children, as an optimization we don't process those.
32817             if (node.kind > 152 /* LastToken */) {
32818                 var saveParent = parent;
32819                 parent = node;
32820                 var containerFlags = getContainerFlags(node);
32821                 if (containerFlags === 0 /* None */) {
32822                     bindChildren(node);
32823                 }
32824                 else {
32825                     bindContainer(node, containerFlags);
32826                 }
32827                 parent = saveParent;
32828             }
32829             else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
32830                 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
32831                 var saveParent = parent;
32832                 if (node.kind === 1 /* EndOfFileToken */)
32833                     parent = node;
32834                 bindJSDoc(node);
32835                 parent = saveParent;
32836             }
32837             inStrictMode = saveInStrictMode;
32838         }
32839         function bindJSDoc(node) {
32840             if (ts.hasJSDocNodes(node)) {
32841                 if (ts.isInJSFile(node)) {
32842                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
32843                         var j = _a[_i];
32844                         bind(j);
32845                     }
32846                 }
32847                 else {
32848                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
32849                         var j = _c[_b];
32850                         setParentPointers(node, j);
32851                     }
32852                 }
32853             }
32854         }
32855         function updateStrictModeStatementList(statements) {
32856             if (!inStrictMode) {
32857                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
32858                     var statement = statements_2[_i];
32859                     if (!ts.isPrologueDirective(statement)) {
32860                         return;
32861                     }
32862                     if (isUseStrictPrologueDirective(statement)) {
32863                         inStrictMode = true;
32864                         return;
32865                     }
32866                 }
32867             }
32868         }
32869         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
32870         function isUseStrictPrologueDirective(node) {
32871             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
32872             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
32873             // string to contain unicode escapes (as per ES5).
32874             return nodeText === '"use strict"' || nodeText === "'use strict'";
32875         }
32876         function bindWorker(node) {
32877             switch (node.kind) {
32878                 /* Strict mode checks */
32879                 case 75 /* Identifier */:
32880                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
32881                     // because it requires all containing namespaces to be in effect, namely the
32882                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
32883                     if (node.isInJSDocNamespace) {
32884                         var parentNode = node.parent;
32885                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
32886                             parentNode = parentNode.parent;
32887                         }
32888                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32889                         break;
32890                     }
32891                 // falls through
32892                 case 104 /* ThisKeyword */:
32893                     if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
32894                         node.flowNode = currentFlow;
32895                     }
32896                     return checkStrictModeIdentifier(node);
32897                 case 76 /* PrivateIdentifier */:
32898                     return checkPrivateIdentifier(node);
32899                 case 194 /* PropertyAccessExpression */:
32900                 case 195 /* ElementAccessExpression */:
32901                     var expr = node;
32902                     if (currentFlow && isNarrowableReference(expr)) {
32903                         expr.flowNode = currentFlow;
32904                     }
32905                     if (ts.isSpecialPropertyDeclaration(expr)) {
32906                         bindSpecialPropertyDeclaration(expr);
32907                     }
32908                     if (ts.isInJSFile(expr) &&
32909                         file.commonJsModuleIndicator &&
32910                         ts.isModuleExportsAccessExpression(expr) &&
32911                         !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
32912                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
32913                     }
32914                     break;
32915                 case 209 /* BinaryExpression */:
32916                     var specialKind = ts.getAssignmentDeclarationKind(node);
32917                     switch (specialKind) {
32918                         case 1 /* ExportsProperty */:
32919                             bindExportsPropertyAssignment(node);
32920                             break;
32921                         case 2 /* ModuleExports */:
32922                             bindModuleExportsAssignment(node);
32923                             break;
32924                         case 3 /* PrototypeProperty */:
32925                             bindPrototypePropertyAssignment(node.left, node);
32926                             break;
32927                         case 6 /* Prototype */:
32928                             bindPrototypeAssignment(node);
32929                             break;
32930                         case 4 /* ThisProperty */:
32931                             bindThisPropertyAssignment(node);
32932                             break;
32933                         case 5 /* Property */:
32934                             bindSpecialPropertyAssignment(node);
32935                             break;
32936                         case 0 /* None */:
32937                             // Nothing to do
32938                             break;
32939                         default:
32940                             ts.Debug.fail("Unknown binary expression special property assignment kind");
32941                     }
32942                     return checkStrictModeBinaryExpression(node);
32943                 case 280 /* CatchClause */:
32944                     return checkStrictModeCatchClause(node);
32945                 case 203 /* DeleteExpression */:
32946                     return checkStrictModeDeleteExpression(node);
32947                 case 8 /* NumericLiteral */:
32948                     return checkStrictModeNumericLiteral(node);
32949                 case 208 /* PostfixUnaryExpression */:
32950                     return checkStrictModePostfixUnaryExpression(node);
32951                 case 207 /* PrefixUnaryExpression */:
32952                     return checkStrictModePrefixUnaryExpression(node);
32953                 case 236 /* WithStatement */:
32954                     return checkStrictModeWithStatement(node);
32955                 case 238 /* LabeledStatement */:
32956                     return checkStrictModeLabeledStatement(node);
32957                 case 183 /* ThisType */:
32958                     seenThisKeyword = true;
32959                     return;
32960                 case 168 /* TypePredicate */:
32961                     break; // Binding the children will handle everything
32962                 case 155 /* TypeParameter */:
32963                     return bindTypeParameter(node);
32964                 case 156 /* Parameter */:
32965                     return bindParameter(node);
32966                 case 242 /* VariableDeclaration */:
32967                     return bindVariableDeclarationOrBindingElement(node);
32968                 case 191 /* BindingElement */:
32969                     node.flowNode = currentFlow;
32970                     return bindVariableDeclarationOrBindingElement(node);
32971                 case 159 /* PropertyDeclaration */:
32972                 case 158 /* PropertySignature */:
32973                     return bindPropertyWorker(node);
32974                 case 281 /* PropertyAssignment */:
32975                 case 282 /* ShorthandPropertyAssignment */:
32976                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
32977                 case 284 /* EnumMember */:
32978                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
32979                 case 165 /* CallSignature */:
32980                 case 166 /* ConstructSignature */:
32981                 case 167 /* IndexSignature */:
32982                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
32983                 case 161 /* MethodDeclaration */:
32984                 case 160 /* MethodSignature */:
32985                     // If this is an ObjectLiteralExpression method, then it sits in the same space
32986                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
32987                     // so that it will conflict with any other object literal members with the same
32988                     // name.
32989                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
32990                 case 244 /* FunctionDeclaration */:
32991                     return bindFunctionDeclaration(node);
32992                 case 162 /* Constructor */:
32993                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
32994                 case 163 /* GetAccessor */:
32995                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
32996                 case 164 /* SetAccessor */:
32997                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
32998                 case 170 /* FunctionType */:
32999                 case 300 /* JSDocFunctionType */:
33000                 case 305 /* JSDocSignature */:
33001                 case 171 /* ConstructorType */:
33002                     return bindFunctionOrConstructorType(node);
33003                 case 173 /* TypeLiteral */:
33004                 case 304 /* JSDocTypeLiteral */:
33005                 case 186 /* MappedType */:
33006                     return bindAnonymousTypeWorker(node);
33007                 case 310 /* JSDocClassTag */:
33008                     return bindJSDocClassTag(node);
33009                 case 193 /* ObjectLiteralExpression */:
33010                     return bindObjectLiteralExpression(node);
33011                 case 201 /* FunctionExpression */:
33012                 case 202 /* ArrowFunction */:
33013                     return bindFunctionExpression(node);
33014                 case 196 /* CallExpression */:
33015                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
33016                     switch (assignmentKind) {
33017                         case 7 /* ObjectDefinePropertyValue */:
33018                             return bindObjectDefinePropertyAssignment(node);
33019                         case 8 /* ObjectDefinePropertyExports */:
33020                             return bindObjectDefinePropertyExport(node);
33021                         case 9 /* ObjectDefinePrototypeProperty */:
33022                             return bindObjectDefinePrototypeProperty(node);
33023                         case 0 /* None */:
33024                             break; // Nothing to do
33025                         default:
33026                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
33027                     }
33028                     if (ts.isInJSFile(node)) {
33029                         bindCallExpression(node);
33030                     }
33031                     break;
33032                 // Members of classes, interfaces, and modules
33033                 case 214 /* ClassExpression */:
33034                 case 245 /* ClassDeclaration */:
33035                     // All classes are automatically in strict mode in ES6.
33036                     inStrictMode = true;
33037                     return bindClassLikeDeclaration(node);
33038                 case 246 /* InterfaceDeclaration */:
33039                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
33040                 case 247 /* TypeAliasDeclaration */:
33041                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
33042                 case 248 /* EnumDeclaration */:
33043                     return bindEnumDeclaration(node);
33044                 case 249 /* ModuleDeclaration */:
33045                     return bindModuleDeclaration(node);
33046                 // Jsx-attributes
33047                 case 274 /* JsxAttributes */:
33048                     return bindJsxAttributes(node);
33049                 case 273 /* JsxAttribute */:
33050                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
33051                 // Imports and exports
33052                 case 253 /* ImportEqualsDeclaration */:
33053                 case 256 /* NamespaceImport */:
33054                 case 258 /* ImportSpecifier */:
33055                 case 263 /* ExportSpecifier */:
33056                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33057                 case 252 /* NamespaceExportDeclaration */:
33058                     return bindNamespaceExportDeclaration(node);
33059                 case 255 /* ImportClause */:
33060                     return bindImportClause(node);
33061                 case 260 /* ExportDeclaration */:
33062                     return bindExportDeclaration(node);
33063                 case 259 /* ExportAssignment */:
33064                     return bindExportAssignment(node);
33065                 case 290 /* SourceFile */:
33066                     updateStrictModeStatementList(node.statements);
33067                     return bindSourceFileIfExternalModule();
33068                 case 223 /* Block */:
33069                     if (!ts.isFunctionLike(node.parent)) {
33070                         return;
33071                     }
33072                 // falls through
33073                 case 250 /* ModuleBlock */:
33074                     return updateStrictModeStatementList(node.statements);
33075                 case 317 /* JSDocParameterTag */:
33076                     if (node.parent.kind === 305 /* JSDocSignature */) {
33077                         return bindParameter(node);
33078                     }
33079                     if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
33080                         break;
33081                     }
33082                 // falls through
33083                 case 323 /* JSDocPropertyTag */:
33084                     var propTag = node;
33085                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
33086                         4 /* Property */ | 16777216 /* Optional */ :
33087                         4 /* Property */;
33088                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
33089                 case 322 /* JSDocTypedefTag */:
33090                 case 315 /* JSDocCallbackTag */:
33091                 case 316 /* JSDocEnumTag */:
33092                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
33093             }
33094         }
33095         function bindPropertyWorker(node) {
33096             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33097         }
33098         function bindAnonymousTypeWorker(node) {
33099             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
33100         }
33101         function bindSourceFileIfExternalModule() {
33102             setExportContextFlag(file);
33103             if (ts.isExternalModule(file)) {
33104                 bindSourceFileAsExternalModule();
33105             }
33106             else if (ts.isJsonSourceFile(file)) {
33107                 bindSourceFileAsExternalModule();
33108                 // Create symbol equivalent for the module.exports = {}
33109                 var originalSymbol = file.symbol;
33110                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
33111                 file.symbol = originalSymbol;
33112             }
33113         }
33114         function bindSourceFileAsExternalModule() {
33115             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
33116         }
33117         function bindExportAssignment(node) {
33118             if (!container.symbol || !container.symbol.exports) {
33119                 // Export assignment in some sort of block construct
33120                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
33121             }
33122             else {
33123                 var flags = ts.exportAssignmentIsAlias(node)
33124                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
33125                     ? 2097152 /* Alias */
33126                     // An export default clause with any other expression exports a value
33127                     : 4 /* Property */;
33128                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
33129                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
33130                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
33131                 if (node.isExportEquals) {
33132                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
33133                     ts.setValueDeclaration(symbol, node);
33134                 }
33135             }
33136         }
33137         function bindNamespaceExportDeclaration(node) {
33138             if (node.modifiers && node.modifiers.length) {
33139                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
33140             }
33141             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
33142                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
33143                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
33144                         : undefined;
33145             if (diag) {
33146                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
33147             }
33148             else {
33149                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
33150                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33151             }
33152         }
33153         function bindExportDeclaration(node) {
33154             if (!container.symbol || !container.symbol.exports) {
33155                 // Export * in some sort of block construct
33156                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
33157             }
33158             else if (!node.exportClause) {
33159                 // All export * declarations are collected in an __export symbol
33160                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
33161             }
33162             else if (ts.isNamespaceExport(node.exportClause)) {
33163                 // declareSymbol walks up parents to find name text, parent _must_ be set
33164                 // but won't be set by the normal binder walk until `bindChildren` later on.
33165                 node.exportClause.parent = node;
33166                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33167             }
33168         }
33169         function bindImportClause(node) {
33170             if (node.name) {
33171                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33172             }
33173         }
33174         function setCommonJsModuleIndicator(node) {
33175             if (file.externalModuleIndicator) {
33176                 return false;
33177             }
33178             if (!file.commonJsModuleIndicator) {
33179                 file.commonJsModuleIndicator = node;
33180                 bindSourceFileAsExternalModule();
33181             }
33182             return true;
33183         }
33184         function bindObjectDefinePropertyExport(node) {
33185             if (!setCommonJsModuleIndicator(node)) {
33186                 return;
33187             }
33188             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
33189                 if (symbol) {
33190                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33191                 }
33192                 return symbol;
33193             });
33194             if (symbol) {
33195                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
33196                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
33197             }
33198         }
33199         function bindExportsPropertyAssignment(node) {
33200             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
33201             // expression is the declaration
33202             if (!setCommonJsModuleIndicator(node)) {
33203                 return;
33204             }
33205             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
33206                 if (symbol) {
33207                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33208                 }
33209                 return symbol;
33210             });
33211             if (symbol) {
33212                 var flags = ts.isClassExpression(node.right) ?
33213                     4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
33214                     4 /* Property */ | 1048576 /* ExportValue */;
33215                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
33216             }
33217         }
33218         function bindModuleExportsAssignment(node) {
33219             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
33220             // is still pointing to 'module.exports'.
33221             // We do not want to consider this as 'export=' since a module can have only one of these.
33222             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
33223             if (!setCommonJsModuleIndicator(node)) {
33224                 return;
33225             }
33226             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
33227             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
33228                 return;
33229             }
33230             // 'module.exports = expr' assignment
33231             var flags = ts.exportAssignmentIsAlias(node)
33232                 ? 2097152 /* Alias */
33233                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
33234             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
33235             ts.setValueDeclaration(symbol, node);
33236         }
33237         function bindThisPropertyAssignment(node) {
33238             ts.Debug.assert(ts.isInJSFile(node));
33239             // private identifiers *must* be declared (even in JS files)
33240             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
33241                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
33242             if (hasPrivateIdentifier) {
33243                 return;
33244             }
33245             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
33246             switch (thisContainer.kind) {
33247                 case 244 /* FunctionDeclaration */:
33248                 case 201 /* FunctionExpression */:
33249                     var constructorSymbol = thisContainer.symbol;
33250                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
33251                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
33252                         var l = thisContainer.parent.left;
33253                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
33254                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
33255                         }
33256                     }
33257                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
33258                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
33259                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
33260                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
33261                         if (ts.hasDynamicName(node)) {
33262                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
33263                         }
33264                         else {
33265                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
33266                         }
33267                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
33268                     }
33269                     break;
33270                 case 162 /* Constructor */:
33271                 case 159 /* PropertyDeclaration */:
33272                 case 161 /* MethodDeclaration */:
33273                 case 163 /* GetAccessor */:
33274                 case 164 /* SetAccessor */:
33275                     // this.foo assignment in a JavaScript class
33276                     // Bind this property to the containing class
33277                     var containingClass = thisContainer.parent;
33278                     var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
33279                     if (ts.hasDynamicName(node)) {
33280                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
33281                     }
33282                     else {
33283                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
33284                     }
33285                     break;
33286                 case 290 /* SourceFile */:
33287                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
33288                     if (ts.hasDynamicName(node)) {
33289                         break;
33290                     }
33291                     else if (thisContainer.commonJsModuleIndicator) {
33292                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
33293                     }
33294                     else {
33295                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33296                     }
33297                     break;
33298                 default:
33299                     ts.Debug.failBadSyntaxKind(thisContainer);
33300             }
33301         }
33302         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
33303             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
33304             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
33305         }
33306         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
33307             if (symbol) {
33308                 var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
33309                 members.set("" + ts.getNodeId(node), node);
33310             }
33311         }
33312         function bindSpecialPropertyDeclaration(node) {
33313             if (node.expression.kind === 104 /* ThisKeyword */) {
33314                 bindThisPropertyAssignment(node);
33315             }
33316             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
33317                 if (ts.isPrototypeAccess(node.expression)) {
33318                     bindPrototypePropertyAssignment(node, node.parent);
33319                 }
33320                 else {
33321                     bindStaticPropertyAssignment(node);
33322                 }
33323             }
33324         }
33325         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
33326         function bindPrototypeAssignment(node) {
33327             node.left.parent = node;
33328             node.right.parent = node;
33329             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
33330         }
33331         function bindObjectDefinePrototypeProperty(node) {
33332             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
33333             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
33334                 // Ensure the namespace symbol becomes class-like
33335                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33336             }
33337             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
33338         }
33339         /**
33340          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
33341          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
33342          */
33343         function bindPrototypePropertyAssignment(lhs, parent) {
33344             // Look up the function in the local scope, since prototype assignments should
33345             // follow the function declaration
33346             var classPrototype = lhs.expression;
33347             var constructorFunction = classPrototype.expression;
33348             // Fix up parent pointers since we're going to use these nodes before we bind into them
33349             lhs.parent = parent;
33350             constructorFunction.parent = classPrototype;
33351             classPrototype.parent = lhs;
33352             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
33353         }
33354         function bindObjectDefinePropertyAssignment(node) {
33355             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
33356             var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
33357             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33358             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
33359         }
33360         function bindSpecialPropertyAssignment(node) {
33361             // Class declarations in Typescript do not allow property declarations
33362             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
33363             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
33364                 return;
33365             }
33366             // Fix up parent pointers since we're going to use these nodes before we bind into them
33367             node.left.parent = node;
33368             node.right.parent = node;
33369             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
33370                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
33371                 //    var util = module.exports;
33372                 //    util.property = function ...
33373                 bindExportsPropertyAssignment(node);
33374             }
33375             else if (ts.hasDynamicName(node)) {
33376                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
33377                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
33378                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
33379             }
33380             else {
33381                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
33382             }
33383         }
33384         /**
33385          * 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.
33386          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
33387          */
33388         function bindStaticPropertyAssignment(node) {
33389             ts.Debug.assert(!ts.isIdentifier(node));
33390             node.expression.parent = node;
33391             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33392         }
33393         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
33394             if (isToplevel && !isPrototypeProperty) {
33395                 // make symbols or add declarations for intermediate containers
33396                 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
33397                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
33398                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
33399                     if (symbol) {
33400                         addDeclarationToSymbol(symbol, id, flags_1);
33401                         return symbol;
33402                     }
33403                     else {
33404                         var table = parent ? parent.exports :
33405                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
33406                         return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
33407                     }
33408                 });
33409             }
33410             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
33411                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33412             }
33413             return namespaceSymbol;
33414         }
33415         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
33416             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
33417                 return;
33418             }
33419             // Set up the members collection if it doesn't exist already
33420             var symbolTable = isPrototypeProperty ?
33421                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
33422                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
33423             var includes = 0 /* None */;
33424             var excludes = 0 /* None */;
33425             // Method-like
33426             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
33427                 includes = 8192 /* Method */;
33428                 excludes = 103359 /* MethodExcludes */;
33429             }
33430             // Maybe accessor-like
33431             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
33432                 if (ts.some(declaration.arguments[2].properties, function (p) {
33433                     var id = ts.getNameOfDeclaration(p);
33434                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
33435                 })) {
33436                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
33437                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
33438                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
33439                     excludes |= 78783 /* SetAccessorExcludes */;
33440                 }
33441                 if (ts.some(declaration.arguments[2].properties, function (p) {
33442                     var id = ts.getNameOfDeclaration(p);
33443                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
33444                 })) {
33445                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
33446                     excludes |= 46015 /* GetAccessorExcludes */;
33447                 }
33448             }
33449             if (includes === 0 /* None */) {
33450                 includes = 4 /* Property */;
33451                 excludes = 0 /* PropertyExcludes */;
33452             }
33453             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
33454         }
33455         function isTopLevelNamespaceAssignment(propertyAccess) {
33456             return ts.isBinaryExpression(propertyAccess.parent)
33457                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
33458                 : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
33459         }
33460         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
33461             var namespaceSymbol = lookupSymbolForPropertyAccess(name);
33462             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
33463             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
33464             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
33465         }
33466         /**
33467          * Javascript expando values are:
33468          * - Functions
33469          * - classes
33470          * - namespaces
33471          * - variables initialized with function expressions
33472          * -                       with class expressions
33473          * -                       with empty object literals
33474          * -                       with non-empty object literals if assigned to the prototype property
33475          */
33476         function isExpandoSymbol(symbol) {
33477             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
33478                 return true;
33479             }
33480             var node = symbol.valueDeclaration;
33481             if (node && ts.isCallExpression(node)) {
33482                 return !!ts.getAssignedExpandoInitializer(node);
33483             }
33484             var init = !node ? undefined :
33485                 ts.isVariableDeclaration(node) ? node.initializer :
33486                     ts.isBinaryExpression(node) ? node.right :
33487                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
33488                             undefined;
33489             init = init && ts.getRightMostAssignedExpression(init);
33490             if (init) {
33491                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
33492                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
33493             }
33494             return false;
33495         }
33496         function getParentOfBinaryExpression(expr) {
33497             while (ts.isBinaryExpression(expr.parent)) {
33498                 expr = expr.parent;
33499             }
33500             return expr.parent;
33501         }
33502         function lookupSymbolForPropertyAccess(node, lookupContainer) {
33503             if (lookupContainer === void 0) { lookupContainer = container; }
33504             if (ts.isIdentifier(node)) {
33505                 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
33506             }
33507             else {
33508                 var symbol = lookupSymbolForPropertyAccess(node.expression);
33509                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
33510             }
33511         }
33512         function forEachIdentifierInEntityName(e, parent, action) {
33513             if (isExportsOrModuleExportsOrAlias(file, e)) {
33514                 return file.symbol;
33515             }
33516             else if (ts.isIdentifier(e)) {
33517                 return action(e, lookupSymbolForPropertyAccess(e), parent);
33518             }
33519             else {
33520                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
33521                 var name = ts.getNameOrArgument(e);
33522                 // unreachable
33523                 if (ts.isPrivateIdentifier(name)) {
33524                     ts.Debug.fail("unexpected PrivateIdentifier");
33525                 }
33526                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
33527             }
33528         }
33529         function bindCallExpression(node) {
33530             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
33531             // this check if we've already seen the module indicator
33532             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
33533                 setCommonJsModuleIndicator(node);
33534             }
33535         }
33536         function bindClassLikeDeclaration(node) {
33537             if (node.kind === 245 /* ClassDeclaration */) {
33538                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
33539             }
33540             else {
33541                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
33542                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
33543                 // Add name of class expression into the map for semantic classifier
33544                 if (node.name) {
33545                     classifiableNames.set(node.name.escapedText, true);
33546                 }
33547             }
33548             var symbol = node.symbol;
33549             // TypeScript 1.0 spec (April 2014): 8.4
33550             // Every class automatically contains a static property member named 'prototype', the
33551             // type of which is an instantiation of the class type with type Any supplied as a type
33552             // argument for each type parameter. It is an error to explicitly declare a static
33553             // property member with the name 'prototype'.
33554             //
33555             // Note: we check for this here because this class may be merging into a module.  The
33556             // module might have an exported variable called 'prototype'.  We can't allow that as
33557             // that would clash with the built-in 'prototype' for the class.
33558             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
33559             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
33560             if (symbolExport) {
33561                 if (node.name) {
33562                     node.name.parent = node;
33563                 }
33564                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
33565             }
33566             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
33567             prototypeSymbol.parent = symbol;
33568         }
33569         function bindEnumDeclaration(node) {
33570             return ts.isEnumConst(node)
33571                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
33572                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
33573         }
33574         function bindVariableDeclarationOrBindingElement(node) {
33575             if (inStrictMode) {
33576                 checkStrictModeEvalOrArguments(node, node.name);
33577             }
33578             if (!ts.isBindingPattern(node.name)) {
33579                 if (ts.isBlockOrCatchScoped(node)) {
33580                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
33581                 }
33582                 else if (ts.isParameterDeclaration(node)) {
33583                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
33584                     // because its parent chain has already been set up, since parents are set before descending into children.
33585                     //
33586                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
33587                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
33588                     // For example:
33589                     //      function foo([a,a]) {} // Duplicate Identifier error
33590                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
33591                     //                             // which correctly set excluded symbols
33592                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33593                 }
33594                 else {
33595                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33596                 }
33597             }
33598         }
33599         function bindParameter(node) {
33600             if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
33601                 return;
33602             }
33603             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
33604                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
33605                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
33606                 checkStrictModeEvalOrArguments(node, node.name);
33607             }
33608             if (ts.isBindingPattern(node.name)) {
33609                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
33610             }
33611             else {
33612                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33613             }
33614             // If this is a property-parameter, then also declare the property symbol into the
33615             // containing class.
33616             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
33617                 var classDeclaration = node.parent.parent;
33618                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33619             }
33620         }
33621         function bindFunctionDeclaration(node) {
33622             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33623                 if (ts.isAsyncFunction(node)) {
33624                     emitFlags |= 2048 /* HasAsyncFunctions */;
33625                 }
33626             }
33627             checkStrictModeFunctionName(node);
33628             if (inStrictMode) {
33629                 checkStrictModeFunctionDeclaration(node);
33630                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33631             }
33632             else {
33633                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33634             }
33635         }
33636         function bindFunctionExpression(node) {
33637             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33638                 if (ts.isAsyncFunction(node)) {
33639                     emitFlags |= 2048 /* HasAsyncFunctions */;
33640                 }
33641             }
33642             if (currentFlow) {
33643                 node.flowNode = currentFlow;
33644             }
33645             checkStrictModeFunctionName(node);
33646             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
33647             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
33648         }
33649         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
33650             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
33651                 emitFlags |= 2048 /* HasAsyncFunctions */;
33652             }
33653             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
33654                 node.flowNode = currentFlow;
33655             }
33656             return ts.hasDynamicName(node)
33657                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
33658                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
33659         }
33660         function getInferTypeContainer(node) {
33661             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
33662             return extendsType && extendsType.parent;
33663         }
33664         function bindTypeParameter(node) {
33665             if (ts.isJSDocTemplateTag(node.parent)) {
33666                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
33667                 if (container_1) {
33668                     if (!container_1.locals) {
33669                         container_1.locals = ts.createSymbolTable();
33670                     }
33671                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33672                 }
33673                 else {
33674                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33675                 }
33676             }
33677             else if (node.parent.kind === 181 /* InferType */) {
33678                 var container_2 = getInferTypeContainer(node.parent);
33679                 if (container_2) {
33680                     if (!container_2.locals) {
33681                         container_2.locals = ts.createSymbolTable();
33682                     }
33683                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33684                 }
33685                 else {
33686                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
33687                 }
33688             }
33689             else {
33690                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33691             }
33692         }
33693         // reachability checks
33694         function shouldReportErrorOnModuleDeclaration(node) {
33695             var instanceState = getModuleInstanceState(node);
33696             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
33697         }
33698         function checkUnreachable(node) {
33699             if (!(currentFlow.flags & 1 /* Unreachable */)) {
33700                 return false;
33701             }
33702             if (currentFlow === unreachableFlow) {
33703                 var reportError = 
33704                 // report error on all statements except empty ones
33705                 (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
33706                     // report error on class declarations
33707                     node.kind === 245 /* ClassDeclaration */ ||
33708                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
33709                     (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
33710                 if (reportError) {
33711                     currentFlow = reportedUnreachableFlow;
33712                     if (!options.allowUnreachableCode) {
33713                         // unreachable code is reported if
33714                         // - user has explicitly asked about it AND
33715                         // - statement is in not ambient context (statements in ambient context is already an error
33716                         //   so we should not report extras) AND
33717                         //   - node is not variable statement OR
33718                         //   - node is block scoped variable statement OR
33719                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
33720                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
33721                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
33722                         var isError_1 = ts.unreachableCodeIsError(options) &&
33723                             !(node.flags & 8388608 /* Ambient */) &&
33724                             (!ts.isVariableStatement(node) ||
33725                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
33726                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
33727                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
33728                     }
33729                 }
33730             }
33731             return true;
33732         }
33733     }
33734     function eachUnreachableRange(node, cb) {
33735         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
33736             var statements = node.parent.statements;
33737             var slice_1 = ts.sliceAfter(statements, node);
33738             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
33739         }
33740         else {
33741             cb(node, node);
33742         }
33743     }
33744     // As opposed to a pure declaration like an `interface`
33745     function isExecutableStatement(s) {
33746         // Don't remove statements that can validly be used before they appear.
33747         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
33748             // `var x;` may declare a variable used above
33749             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
33750     }
33751     function isPurelyTypeDeclaration(s) {
33752         switch (s.kind) {
33753             case 246 /* InterfaceDeclaration */:
33754             case 247 /* TypeAliasDeclaration */:
33755                 return true;
33756             case 249 /* ModuleDeclaration */:
33757                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
33758             case 248 /* EnumDeclaration */:
33759                 return ts.hasModifier(s, 2048 /* Const */);
33760             default:
33761                 return false;
33762         }
33763     }
33764     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
33765         var i = 0;
33766         var q = [node];
33767         while (q.length && i < 100) {
33768             i++;
33769             node = q.shift();
33770             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
33771                 return true;
33772             }
33773             else if (ts.isIdentifier(node)) {
33774                 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
33775                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
33776                     var init = symbol.valueDeclaration.initializer;
33777                     q.push(init);
33778                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
33779                         q.push(init.left);
33780                         q.push(init.right);
33781                     }
33782                 }
33783             }
33784         }
33785         return false;
33786     }
33787     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
33788     function lookupSymbolForNameWorker(container, name) {
33789         var local = container.locals && container.locals.get(name);
33790         if (local) {
33791             return local.exportSymbol || local;
33792         }
33793         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
33794             return container.jsGlobalAugmentations.get(name);
33795         }
33796         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
33797     }
33798     /**
33799      * Computes the transform flags for a node, given the transform flags of its subtree
33800      *
33801      * @param node The node to analyze
33802      * @param subtreeFlags Transform flags computed for this node's subtree
33803      */
33804     function computeTransformFlagsForNode(node, subtreeFlags) {
33805         var kind = node.kind;
33806         switch (kind) {
33807             case 196 /* CallExpression */:
33808                 return computeCallExpression(node, subtreeFlags);
33809             case 197 /* NewExpression */:
33810                 return computeNewExpression(node, subtreeFlags);
33811             case 249 /* ModuleDeclaration */:
33812                 return computeModuleDeclaration(node, subtreeFlags);
33813             case 200 /* ParenthesizedExpression */:
33814                 return computeParenthesizedExpression(node, subtreeFlags);
33815             case 209 /* BinaryExpression */:
33816                 return computeBinaryExpression(node, subtreeFlags);
33817             case 226 /* ExpressionStatement */:
33818                 return computeExpressionStatement(node, subtreeFlags);
33819             case 156 /* Parameter */:
33820                 return computeParameter(node, subtreeFlags);
33821             case 202 /* ArrowFunction */:
33822                 return computeArrowFunction(node, subtreeFlags);
33823             case 201 /* FunctionExpression */:
33824                 return computeFunctionExpression(node, subtreeFlags);
33825             case 244 /* FunctionDeclaration */:
33826                 return computeFunctionDeclaration(node, subtreeFlags);
33827             case 242 /* VariableDeclaration */:
33828                 return computeVariableDeclaration(node, subtreeFlags);
33829             case 243 /* VariableDeclarationList */:
33830                 return computeVariableDeclarationList(node, subtreeFlags);
33831             case 225 /* VariableStatement */:
33832                 return computeVariableStatement(node, subtreeFlags);
33833             case 238 /* LabeledStatement */:
33834                 return computeLabeledStatement(node, subtreeFlags);
33835             case 245 /* ClassDeclaration */:
33836                 return computeClassDeclaration(node, subtreeFlags);
33837             case 214 /* ClassExpression */:
33838                 return computeClassExpression(node, subtreeFlags);
33839             case 279 /* HeritageClause */:
33840                 return computeHeritageClause(node, subtreeFlags);
33841             case 280 /* CatchClause */:
33842                 return computeCatchClause(node, subtreeFlags);
33843             case 216 /* ExpressionWithTypeArguments */:
33844                 return computeExpressionWithTypeArguments(node, subtreeFlags);
33845             case 162 /* Constructor */:
33846                 return computeConstructor(node, subtreeFlags);
33847             case 159 /* PropertyDeclaration */:
33848                 return computePropertyDeclaration(node, subtreeFlags);
33849             case 161 /* MethodDeclaration */:
33850                 return computeMethod(node, subtreeFlags);
33851             case 163 /* GetAccessor */:
33852             case 164 /* SetAccessor */:
33853                 return computeAccessor(node, subtreeFlags);
33854             case 253 /* ImportEqualsDeclaration */:
33855                 return computeImportEquals(node, subtreeFlags);
33856             case 194 /* PropertyAccessExpression */:
33857                 return computePropertyAccess(node, subtreeFlags);
33858             case 195 /* ElementAccessExpression */:
33859                 return computeElementAccess(node, subtreeFlags);
33860             case 267 /* JsxSelfClosingElement */:
33861             case 268 /* JsxOpeningElement */:
33862                 return computeJsxOpeningLikeElement(node, subtreeFlags);
33863             default:
33864                 return computeOther(node, kind, subtreeFlags);
33865         }
33866     }
33867     ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
33868     function computeCallExpression(node, subtreeFlags) {
33869         var transformFlags = subtreeFlags;
33870         var callee = ts.skipOuterExpressions(node.expression);
33871         var expression = node.expression;
33872         if (node.flags & 32 /* OptionalChain */) {
33873             transformFlags |= 8 /* ContainsES2020 */;
33874         }
33875         if (node.typeArguments) {
33876             transformFlags |= 1 /* AssertTypeScript */;
33877         }
33878         if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
33879             // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
33880             // node.
33881             transformFlags |= 256 /* AssertES2015 */;
33882             if (ts.isSuperProperty(callee)) {
33883                 transformFlags |= 4096 /* ContainsLexicalThis */;
33884             }
33885         }
33886         if (expression.kind === 96 /* ImportKeyword */) {
33887             transformFlags |= 2097152 /* ContainsDynamicImport */;
33888         }
33889         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33890         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33891     }
33892     function computeNewExpression(node, subtreeFlags) {
33893         var transformFlags = subtreeFlags;
33894         if (node.typeArguments) {
33895             transformFlags |= 1 /* AssertTypeScript */;
33896         }
33897         if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
33898             // If the this node contains a SpreadElementExpression then it is an ES6
33899             // node.
33900             transformFlags |= 256 /* AssertES2015 */;
33901         }
33902         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33903         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33904     }
33905     function computeJsxOpeningLikeElement(node, subtreeFlags) {
33906         var transformFlags = subtreeFlags | 2 /* AssertJsx */;
33907         if (node.typeArguments) {
33908             transformFlags |= 1 /* AssertTypeScript */;
33909         }
33910         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33911         return transformFlags & ~536870912 /* NodeExcludes */;
33912     }
33913     function computeBinaryExpression(node, subtreeFlags) {
33914         var transformFlags = subtreeFlags;
33915         var operatorTokenKind = node.operatorToken.kind;
33916         var leftKind = node.left.kind;
33917         if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
33918             transformFlags |= 8 /* AssertES2020 */;
33919         }
33920         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
33921             // Destructuring object assignments with are ES2015 syntax
33922             // and possibly ES2018 if they contain rest
33923             transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33924         }
33925         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
33926             // Destructuring assignments are ES2015 syntax.
33927             transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33928         }
33929         else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
33930             || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
33931             // Exponentiation is ES2016 syntax.
33932             transformFlags |= 128 /* AssertES2016 */;
33933         }
33934         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33935         return transformFlags & ~536870912 /* NodeExcludes */;
33936     }
33937     function computeParameter(node, subtreeFlags) {
33938         var transformFlags = subtreeFlags;
33939         var name = node.name;
33940         var initializer = node.initializer;
33941         var dotDotDotToken = node.dotDotDotToken;
33942         // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
33943         // syntax.
33944         if (node.questionToken
33945             || node.type
33946             || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
33947             || ts.isThisIdentifier(name)) {
33948             transformFlags |= 1 /* AssertTypeScript */;
33949         }
33950         // If a parameter has an accessibility modifier, then it is TypeScript syntax.
33951         if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
33952             transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
33953         }
33954         // parameters with object rest destructuring are ES2018 syntax
33955         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33956             transformFlags |= 32 /* AssertES2018 */;
33957         }
33958         // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
33959         // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
33960         if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
33961             transformFlags |= 256 /* AssertES2015 */;
33962         }
33963         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33964         return transformFlags & ~536870912 /* ParameterExcludes */;
33965     }
33966     function computeParenthesizedExpression(node, subtreeFlags) {
33967         var transformFlags = subtreeFlags;
33968         var expression = node.expression;
33969         var expressionKind = expression.kind;
33970         // If the node is synthesized, it means the emitter put the parentheses there,
33971         // not the user. If we didn't want them, the emitter would not have put them
33972         // there.
33973         if (expressionKind === 217 /* AsExpression */
33974             || expressionKind === 199 /* TypeAssertionExpression */) {
33975             transformFlags |= 1 /* AssertTypeScript */;
33976         }
33977         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33978         return transformFlags & ~536870912 /* OuterExpressionExcludes */;
33979     }
33980     function computeClassDeclaration(node, subtreeFlags) {
33981         var transformFlags;
33982         if (ts.hasModifier(node, 2 /* Ambient */)) {
33983             // An ambient declaration is TypeScript syntax.
33984             transformFlags = 1 /* AssertTypeScript */;
33985         }
33986         else {
33987             // A ClassDeclaration is ES6 syntax.
33988             transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33989             // A class with a parameter property assignment or decorator is TypeScript syntax.
33990             // An exported declaration may be TypeScript syntax, but is handled by the visitor
33991             // for a namespace declaration.
33992             if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
33993                 || node.typeParameters) {
33994                 transformFlags |= 1 /* AssertTypeScript */;
33995             }
33996         }
33997         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33998         return transformFlags & ~536905728 /* ClassExcludes */;
33999     }
34000     function computeClassExpression(node, subtreeFlags) {
34001         // A ClassExpression is ES6 syntax.
34002         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34003         // A class with a parameter property assignment or decorator is TypeScript syntax.
34004         if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
34005             || node.typeParameters) {
34006             transformFlags |= 1 /* AssertTypeScript */;
34007         }
34008         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34009         return transformFlags & ~536905728 /* ClassExcludes */;
34010     }
34011     function computeHeritageClause(node, subtreeFlags) {
34012         var transformFlags = subtreeFlags;
34013         switch (node.token) {
34014             case 90 /* ExtendsKeyword */:
34015                 // An `extends` HeritageClause is ES6 syntax.
34016                 transformFlags |= 256 /* AssertES2015 */;
34017                 break;
34018             case 113 /* ImplementsKeyword */:
34019                 // An `implements` HeritageClause is TypeScript syntax.
34020                 transformFlags |= 1 /* AssertTypeScript */;
34021                 break;
34022             default:
34023                 ts.Debug.fail("Unexpected token for heritage clause");
34024                 break;
34025         }
34026         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34027         return transformFlags & ~536870912 /* NodeExcludes */;
34028     }
34029     function computeCatchClause(node, subtreeFlags) {
34030         var transformFlags = subtreeFlags;
34031         if (!node.variableDeclaration) {
34032             transformFlags |= 16 /* AssertES2019 */;
34033         }
34034         else if (ts.isBindingPattern(node.variableDeclaration.name)) {
34035             transformFlags |= 256 /* AssertES2015 */;
34036         }
34037         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34038         return transformFlags & ~536887296 /* CatchClauseExcludes */;
34039     }
34040     function computeExpressionWithTypeArguments(node, subtreeFlags) {
34041         // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
34042         // extends clause of a class.
34043         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34044         // If an ExpressionWithTypeArguments contains type arguments, then it
34045         // is TypeScript syntax.
34046         if (node.typeArguments) {
34047             transformFlags |= 1 /* AssertTypeScript */;
34048         }
34049         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34050         return transformFlags & ~536870912 /* NodeExcludes */;
34051     }
34052     function computeConstructor(node, subtreeFlags) {
34053         var transformFlags = subtreeFlags;
34054         // TypeScript-specific modifiers and overloads are TypeScript syntax
34055         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34056             || !node.body) {
34057             transformFlags |= 1 /* AssertTypeScript */;
34058         }
34059         // function declarations with object rest destructuring are ES2018 syntax
34060         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34061             transformFlags |= 32 /* AssertES2018 */;
34062         }
34063         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34064         return transformFlags & ~538923008 /* ConstructorExcludes */;
34065     }
34066     function computeMethod(node, subtreeFlags) {
34067         // A MethodDeclaration is ES6 syntax.
34068         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34069         // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
34070         // overloads are TypeScript syntax.
34071         if (node.decorators
34072             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34073             || node.typeParameters
34074             || node.type
34075             || !node.body
34076             || node.questionToken) {
34077             transformFlags |= 1 /* AssertTypeScript */;
34078         }
34079         // function declarations with object rest destructuring are ES2018 syntax
34080         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34081             transformFlags |= 32 /* AssertES2018 */;
34082         }
34083         // An async method declaration is ES2017 syntax.
34084         if (ts.hasModifier(node, 256 /* Async */)) {
34085             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34086         }
34087         if (node.asteriskToken) {
34088             transformFlags |= 512 /* AssertGenerator */;
34089         }
34090         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34091         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
34092     }
34093     function computeAccessor(node, subtreeFlags) {
34094         var transformFlags = subtreeFlags;
34095         // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
34096         // TypeScript syntax.
34097         if (node.decorators
34098             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34099             || node.type
34100             || !node.body) {
34101             transformFlags |= 1 /* AssertTypeScript */;
34102         }
34103         // function declarations with object rest destructuring are ES2018 syntax
34104         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34105             transformFlags |= 32 /* AssertES2018 */;
34106         }
34107         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34108         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
34109     }
34110     function computePropertyDeclaration(node, subtreeFlags) {
34111         var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
34112         // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
34113         if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
34114             transformFlags |= 1 /* AssertTypeScript */;
34115         }
34116         // Hoisted variables related to class properties should live within the TypeScript class wrapper.
34117         if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
34118             transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
34119         }
34120         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34121         return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
34122     }
34123     function computeFunctionDeclaration(node, subtreeFlags) {
34124         var transformFlags;
34125         var modifierFlags = ts.getModifierFlags(node);
34126         var body = node.body;
34127         if (!body || (modifierFlags & 2 /* Ambient */)) {
34128             // An ambient declaration is TypeScript syntax.
34129             // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
34130             transformFlags = 1 /* AssertTypeScript */;
34131         }
34132         else {
34133             transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34134             // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34135             // syntax.
34136             if (modifierFlags & 2270 /* TypeScriptModifier */
34137                 || node.typeParameters
34138                 || node.type) {
34139                 transformFlags |= 1 /* AssertTypeScript */;
34140             }
34141             // An async function declaration is ES2017 syntax.
34142             if (modifierFlags & 256 /* Async */) {
34143                 transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34144             }
34145             // function declarations with object rest destructuring are ES2018 syntax
34146             if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34147                 transformFlags |= 32 /* AssertES2018 */;
34148             }
34149             // If a FunctionDeclaration is generator function and is the body of a
34150             // transformed async function, then this node can be transformed to a
34151             // down-level generator.
34152             // Currently we do not support transforming any other generator functions
34153             // down level.
34154             if (node.asteriskToken) {
34155                 transformFlags |= 512 /* AssertGenerator */;
34156             }
34157         }
34158         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34159         return transformFlags & ~538925056 /* FunctionExcludes */;
34160     }
34161     function computeFunctionExpression(node, subtreeFlags) {
34162         var transformFlags = subtreeFlags;
34163         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34164         // syntax.
34165         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34166             || node.typeParameters
34167             || node.type) {
34168             transformFlags |= 1 /* AssertTypeScript */;
34169         }
34170         // An async function expression is ES2017 syntax.
34171         if (ts.hasModifier(node, 256 /* Async */)) {
34172             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34173         }
34174         // function expressions with object rest destructuring are ES2018 syntax
34175         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34176             transformFlags |= 32 /* AssertES2018 */;
34177         }
34178         // If a FunctionExpression is generator function and is the body of a
34179         // transformed async function, then this node can be transformed to a
34180         // down-level generator.
34181         if (node.asteriskToken) {
34182             transformFlags |= 512 /* AssertGenerator */;
34183         }
34184         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34185         return transformFlags & ~538925056 /* FunctionExcludes */;
34186     }
34187     function computeArrowFunction(node, subtreeFlags) {
34188         // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
34189         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34190         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34191         // syntax.
34192         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34193             || node.typeParameters
34194             || node.type) {
34195             transformFlags |= 1 /* AssertTypeScript */;
34196         }
34197         // An async arrow function is ES2017 syntax.
34198         if (ts.hasModifier(node, 256 /* Async */)) {
34199             transformFlags |= 64 /* AssertES2017 */;
34200         }
34201         // arrow functions with object rest destructuring are ES2018 syntax
34202         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34203             transformFlags |= 32 /* AssertES2018 */;
34204         }
34205         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34206         return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
34207     }
34208     function computePropertyAccess(node, subtreeFlags) {
34209         var transformFlags = subtreeFlags;
34210         if (node.flags & 32 /* OptionalChain */) {
34211             transformFlags |= 8 /* ContainsES2020 */;
34212         }
34213         // If a PropertyAccessExpression starts with a super keyword, then it is
34214         // ES6 syntax, and requires a lexical `this` binding.
34215         if (node.expression.kind === 102 /* SuperKeyword */) {
34216             // super inside of an async function requires hoisting the super access (ES2017).
34217             // same for super inside of an async generator, which is ES2018.
34218             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34219         }
34220         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34221         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34222     }
34223     function computeElementAccess(node, subtreeFlags) {
34224         var transformFlags = subtreeFlags;
34225         if (node.flags & 32 /* OptionalChain */) {
34226             transformFlags |= 8 /* ContainsES2020 */;
34227         }
34228         // If an ElementAccessExpression starts with a super keyword, then it is
34229         // ES6 syntax, and requires a lexical `this` binding.
34230         if (node.expression.kind === 102 /* SuperKeyword */) {
34231             // super inside of an async function requires hoisting the super access (ES2017).
34232             // same for super inside of an async generator, which is ES2018.
34233             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34234         }
34235         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34236         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34237     }
34238     function computeVariableDeclaration(node, subtreeFlags) {
34239         var transformFlags = subtreeFlags;
34240         transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
34241         // A VariableDeclaration containing ObjectRest is ES2018 syntax
34242         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34243             transformFlags |= 32 /* AssertES2018 */;
34244         }
34245         // Type annotations are TypeScript syntax.
34246         if (node.type || node.exclamationToken) {
34247             transformFlags |= 1 /* AssertTypeScript */;
34248         }
34249         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34250         return transformFlags & ~536870912 /* NodeExcludes */;
34251     }
34252     function computeVariableStatement(node, subtreeFlags) {
34253         var transformFlags;
34254         var declarationListTransformFlags = node.declarationList.transformFlags;
34255         // An ambient declaration is TypeScript syntax.
34256         if (ts.hasModifier(node, 2 /* Ambient */)) {
34257             transformFlags = 1 /* AssertTypeScript */;
34258         }
34259         else {
34260             transformFlags = subtreeFlags;
34261             if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
34262                 transformFlags |= 256 /* AssertES2015 */;
34263             }
34264         }
34265         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34266         return transformFlags & ~536870912 /* NodeExcludes */;
34267     }
34268     function computeLabeledStatement(node, subtreeFlags) {
34269         var transformFlags = subtreeFlags;
34270         // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
34271         if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
34272             && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
34273             transformFlags |= 256 /* AssertES2015 */;
34274         }
34275         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34276         return transformFlags & ~536870912 /* NodeExcludes */;
34277     }
34278     function computeImportEquals(node, subtreeFlags) {
34279         var transformFlags = subtreeFlags;
34280         // An ImportEqualsDeclaration with a namespace reference is TypeScript.
34281         if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
34282             transformFlags |= 1 /* AssertTypeScript */;
34283         }
34284         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34285         return transformFlags & ~536870912 /* NodeExcludes */;
34286     }
34287     function computeExpressionStatement(node, subtreeFlags) {
34288         var transformFlags = subtreeFlags;
34289         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34290         return transformFlags & ~536870912 /* NodeExcludes */;
34291     }
34292     function computeModuleDeclaration(node, subtreeFlags) {
34293         var transformFlags = 1 /* AssertTypeScript */;
34294         var modifierFlags = ts.getModifierFlags(node);
34295         if ((modifierFlags & 2 /* Ambient */) === 0) {
34296             transformFlags |= subtreeFlags;
34297         }
34298         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34299         return transformFlags & ~537991168 /* ModuleExcludes */;
34300     }
34301     function computeVariableDeclarationList(node, subtreeFlags) {
34302         var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34303         if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
34304             transformFlags |= 256 /* AssertES2015 */;
34305         }
34306         // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
34307         if (node.flags & 3 /* BlockScoped */) {
34308             transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
34309         }
34310         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34311         return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
34312     }
34313     function computeOther(node, kind, subtreeFlags) {
34314         // Mark transformations needed for each node
34315         var transformFlags = subtreeFlags;
34316         var excludeFlags = 536870912 /* NodeExcludes */;
34317         switch (kind) {
34318             case 126 /* AsyncKeyword */:
34319                 // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
34320                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
34321                 break;
34322             case 206 /* AwaitExpression */:
34323                 // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
34324                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
34325                 break;
34326             case 199 /* TypeAssertionExpression */:
34327             case 217 /* AsExpression */:
34328             case 326 /* PartiallyEmittedExpression */:
34329                 // These nodes are TypeScript syntax.
34330                 transformFlags |= 1 /* AssertTypeScript */;
34331                 excludeFlags = 536870912 /* OuterExpressionExcludes */;
34332                 break;
34333             case 119 /* PublicKeyword */:
34334             case 117 /* PrivateKeyword */:
34335             case 118 /* ProtectedKeyword */:
34336             case 122 /* AbstractKeyword */:
34337             case 130 /* DeclareKeyword */:
34338             case 81 /* ConstKeyword */:
34339             case 248 /* EnumDeclaration */:
34340             case 284 /* EnumMember */:
34341             case 218 /* NonNullExpression */:
34342             case 138 /* ReadonlyKeyword */:
34343                 // These nodes are TypeScript syntax.
34344                 transformFlags |= 1 /* AssertTypeScript */;
34345                 break;
34346             case 266 /* JsxElement */:
34347             case 11 /* JsxText */:
34348             case 269 /* JsxClosingElement */:
34349             case 270 /* JsxFragment */:
34350             case 271 /* JsxOpeningFragment */:
34351             case 272 /* JsxClosingFragment */:
34352             case 273 /* JsxAttribute */:
34353             case 274 /* JsxAttributes */:
34354             case 275 /* JsxSpreadAttribute */:
34355             case 276 /* JsxExpression */:
34356                 // These nodes are Jsx syntax.
34357                 transformFlags |= 2 /* AssertJsx */;
34358                 break;
34359             case 14 /* NoSubstitutionTemplateLiteral */:
34360             case 15 /* TemplateHead */:
34361             case 16 /* TemplateMiddle */:
34362             case 17 /* TemplateTail */:
34363                 if (node.templateFlags) {
34364                     transformFlags |= 32 /* AssertES2018 */;
34365                     break;
34366                 }
34367             // falls through
34368             case 198 /* TaggedTemplateExpression */:
34369                 if (ts.hasInvalidEscape(node.template)) {
34370                     transformFlags |= 32 /* AssertES2018 */;
34371                     break;
34372                 }
34373             // falls through
34374             case 211 /* TemplateExpression */:
34375             case 282 /* ShorthandPropertyAssignment */:
34376             case 120 /* StaticKeyword */:
34377             case 219 /* MetaProperty */:
34378                 // These nodes are ES6 syntax.
34379                 transformFlags |= 256 /* AssertES2015 */;
34380                 break;
34381             case 10 /* StringLiteral */:
34382                 if (node.hasExtendedUnicodeEscape) {
34383                     transformFlags |= 256 /* AssertES2015 */;
34384                 }
34385                 break;
34386             case 8 /* NumericLiteral */:
34387                 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
34388                     transformFlags |= 256 /* AssertES2015 */;
34389                 }
34390                 break;
34391             case 9 /* BigIntLiteral */:
34392                 transformFlags |= 4 /* AssertESNext */;
34393                 break;
34394             case 232 /* ForOfStatement */:
34395                 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
34396                 if (node.awaitModifier) {
34397                     transformFlags |= 32 /* AssertES2018 */;
34398                 }
34399                 transformFlags |= 256 /* AssertES2015 */;
34400                 break;
34401             case 212 /* YieldExpression */:
34402                 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
34403                 // generator).
34404                 transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
34405                 break;
34406             case 125 /* AnyKeyword */:
34407             case 140 /* NumberKeyword */:
34408             case 151 /* BigIntKeyword */:
34409             case 137 /* NeverKeyword */:
34410             case 141 /* ObjectKeyword */:
34411             case 143 /* StringKeyword */:
34412             case 128 /* BooleanKeyword */:
34413             case 144 /* SymbolKeyword */:
34414             case 110 /* VoidKeyword */:
34415             case 155 /* TypeParameter */:
34416             case 158 /* PropertySignature */:
34417             case 160 /* MethodSignature */:
34418             case 165 /* CallSignature */:
34419             case 166 /* ConstructSignature */:
34420             case 167 /* IndexSignature */:
34421             case 168 /* TypePredicate */:
34422             case 169 /* TypeReference */:
34423             case 170 /* FunctionType */:
34424             case 171 /* ConstructorType */:
34425             case 172 /* TypeQuery */:
34426             case 173 /* TypeLiteral */:
34427             case 174 /* ArrayType */:
34428             case 175 /* TupleType */:
34429             case 176 /* OptionalType */:
34430             case 177 /* RestType */:
34431             case 178 /* UnionType */:
34432             case 179 /* IntersectionType */:
34433             case 180 /* ConditionalType */:
34434             case 181 /* InferType */:
34435             case 182 /* ParenthesizedType */:
34436             case 246 /* InterfaceDeclaration */:
34437             case 247 /* TypeAliasDeclaration */:
34438             case 183 /* ThisType */:
34439             case 184 /* TypeOperator */:
34440             case 185 /* IndexedAccessType */:
34441             case 186 /* MappedType */:
34442             case 187 /* LiteralType */:
34443             case 252 /* NamespaceExportDeclaration */:
34444                 // Types and signatures are TypeScript syntax, and exclude all other facts.
34445                 transformFlags = 1 /* AssertTypeScript */;
34446                 excludeFlags = -2 /* TypeExcludes */;
34447                 break;
34448             case 154 /* ComputedPropertyName */:
34449                 // Even though computed property names are ES6, we don't treat them as such.
34450                 // This is so that they can flow through PropertyName transforms unaffected.
34451                 // Instead, we mark the container as ES6, so that it can properly handle the transform.
34452                 transformFlags |= 32768 /* ContainsComputedPropertyName */;
34453                 break;
34454             case 213 /* SpreadElement */:
34455                 transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
34456                 break;
34457             case 283 /* SpreadAssignment */:
34458                 transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34459                 break;
34460             case 102 /* SuperKeyword */:
34461                 // This node is ES6 syntax.
34462                 transformFlags |= 256 /* AssertES2015 */;
34463                 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
34464                 break;
34465             case 104 /* ThisKeyword */:
34466                 // Mark this node and its ancestors as containing a lexical `this` keyword.
34467                 transformFlags |= 4096 /* ContainsLexicalThis */;
34468                 break;
34469             case 189 /* ObjectBindingPattern */:
34470                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34471                 if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
34472                     transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34473                 }
34474                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34475                 break;
34476             case 190 /* ArrayBindingPattern */:
34477                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34478                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34479                 break;
34480             case 191 /* BindingElement */:
34481                 transformFlags |= 256 /* AssertES2015 */;
34482                 if (node.dotDotDotToken) {
34483                     transformFlags |= 8192 /* ContainsRestOrSpread */;
34484                 }
34485                 break;
34486             case 157 /* Decorator */:
34487                 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
34488                 transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
34489                 break;
34490             case 193 /* ObjectLiteralExpression */:
34491                 excludeFlags = 536922112 /* ObjectLiteralExcludes */;
34492                 if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
34493                     // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
34494                     // is an ES6 node.
34495                     transformFlags |= 256 /* AssertES2015 */;
34496                 }
34497                 if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34498                     // If an ObjectLiteralExpression contains a spread element, then it
34499                     // is an ES2018 node.
34500                     transformFlags |= 32 /* AssertES2018 */;
34501                 }
34502                 break;
34503             case 192 /* ArrayLiteralExpression */:
34504                 excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34505                 break;
34506             case 228 /* DoStatement */:
34507             case 229 /* WhileStatement */:
34508             case 230 /* ForStatement */:
34509             case 231 /* ForInStatement */:
34510                 // A loop containing a block scoped binding *may* need to be transformed from ES6.
34511                 if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
34512                     transformFlags |= 256 /* AssertES2015 */;
34513                 }
34514                 break;
34515             case 290 /* SourceFile */:
34516                 break;
34517             case 262 /* NamespaceExport */:
34518                 transformFlags |= 4 /* AssertESNext */;
34519                 break;
34520             case 235 /* ReturnStatement */:
34521                 // Return statements may require an `await` in ES2018.
34522                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
34523                 break;
34524             case 233 /* ContinueStatement */:
34525             case 234 /* BreakStatement */:
34526                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34527                 break;
34528             case 76 /* PrivateIdentifier */:
34529                 transformFlags |= 4194304 /* ContainsClassFields */;
34530                 break;
34531         }
34532         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34533         return transformFlags & ~excludeFlags;
34534     }
34535     function propagatePropertyNameFlags(node, transformFlags) {
34536         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
34537     }
34538     /**
34539      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
34540      *
34541      * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
34542      *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
34543      *       than calling this function.
34544      */
34545     function getTransformFlagsSubtreeExclusions(kind) {
34546         if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
34547             return -2 /* TypeExcludes */;
34548         }
34549         switch (kind) {
34550             case 196 /* CallExpression */:
34551             case 197 /* NewExpression */:
34552             case 192 /* ArrayLiteralExpression */:
34553                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34554             case 249 /* ModuleDeclaration */:
34555                 return 537991168 /* ModuleExcludes */;
34556             case 156 /* Parameter */:
34557                 return 536870912 /* ParameterExcludes */;
34558             case 202 /* ArrowFunction */:
34559                 return 538920960 /* ArrowFunctionExcludes */;
34560             case 201 /* FunctionExpression */:
34561             case 244 /* FunctionDeclaration */:
34562                 return 538925056 /* FunctionExcludes */;
34563             case 243 /* VariableDeclarationList */:
34564                 return 537018368 /* VariableDeclarationListExcludes */;
34565             case 245 /* ClassDeclaration */:
34566             case 214 /* ClassExpression */:
34567                 return 536905728 /* ClassExcludes */;
34568             case 162 /* Constructor */:
34569                 return 538923008 /* ConstructorExcludes */;
34570             case 161 /* MethodDeclaration */:
34571             case 163 /* GetAccessor */:
34572             case 164 /* SetAccessor */:
34573                 return 538923008 /* MethodOrAccessorExcludes */;
34574             case 125 /* AnyKeyword */:
34575             case 140 /* NumberKeyword */:
34576             case 151 /* BigIntKeyword */:
34577             case 137 /* NeverKeyword */:
34578             case 143 /* StringKeyword */:
34579             case 141 /* ObjectKeyword */:
34580             case 128 /* BooleanKeyword */:
34581             case 144 /* SymbolKeyword */:
34582             case 110 /* VoidKeyword */:
34583             case 155 /* TypeParameter */:
34584             case 158 /* PropertySignature */:
34585             case 160 /* MethodSignature */:
34586             case 165 /* CallSignature */:
34587             case 166 /* ConstructSignature */:
34588             case 167 /* IndexSignature */:
34589             case 246 /* InterfaceDeclaration */:
34590             case 247 /* TypeAliasDeclaration */:
34591                 return -2 /* TypeExcludes */;
34592             case 193 /* ObjectLiteralExpression */:
34593                 return 536922112 /* ObjectLiteralExcludes */;
34594             case 280 /* CatchClause */:
34595                 return 536887296 /* CatchClauseExcludes */;
34596             case 189 /* ObjectBindingPattern */:
34597             case 190 /* ArrayBindingPattern */:
34598                 return 536879104 /* BindingPatternExcludes */;
34599             case 199 /* TypeAssertionExpression */:
34600             case 217 /* AsExpression */:
34601             case 326 /* PartiallyEmittedExpression */:
34602             case 200 /* ParenthesizedExpression */:
34603             case 102 /* SuperKeyword */:
34604                 return 536870912 /* OuterExpressionExcludes */;
34605             case 194 /* PropertyAccessExpression */:
34606             case 195 /* ElementAccessExpression */:
34607                 return 536870912 /* PropertyAccessExcludes */;
34608             default:
34609                 return 536870912 /* NodeExcludes */;
34610         }
34611     }
34612     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
34613     /**
34614      * "Binds" JSDoc nodes in TypeScript code.
34615      * Since we will never create symbols for JSDoc, we just set parent pointers instead.
34616      */
34617     function setParentPointers(parent, child) {
34618         child.parent = parent;
34619         ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
34620     }
34621 })(ts || (ts = {}));
34622 /** @internal */
34623 var ts;
34624 (function (ts) {
34625     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
34626         return getSymbolWalker;
34627         function getSymbolWalker(accept) {
34628             if (accept === void 0) { accept = function () { return true; }; }
34629             var visitedTypes = []; // Sparse array from id to type
34630             var visitedSymbols = []; // Sparse array from id to symbol
34631             return {
34632                 walkType: function (type) {
34633                     try {
34634                         visitType(type);
34635                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34636                     }
34637                     finally {
34638                         ts.clear(visitedTypes);
34639                         ts.clear(visitedSymbols);
34640                     }
34641                 },
34642                 walkSymbol: function (symbol) {
34643                     try {
34644                         visitSymbol(symbol);
34645                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34646                     }
34647                     finally {
34648                         ts.clear(visitedTypes);
34649                         ts.clear(visitedSymbols);
34650                     }
34651                 },
34652             };
34653             function visitType(type) {
34654                 if (!type) {
34655                     return;
34656                 }
34657                 if (visitedTypes[type.id]) {
34658                     return;
34659                 }
34660                 visitedTypes[type.id] = type;
34661                 // Reuse visitSymbol to visit the type's symbol,
34662                 //  but be sure to bail on recuring into the type if accept declines the symbol.
34663                 var shouldBail = visitSymbol(type.symbol);
34664                 if (shouldBail)
34665                     return;
34666                 // Visit the type's related types, if any
34667                 if (type.flags & 524288 /* Object */) {
34668                     var objectType = type;
34669                     var objectFlags = objectType.objectFlags;
34670                     if (objectFlags & 4 /* Reference */) {
34671                         visitTypeReference(type);
34672                     }
34673                     if (objectFlags & 32 /* Mapped */) {
34674                         visitMappedType(type);
34675                     }
34676                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
34677                         visitInterfaceType(type);
34678                     }
34679                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
34680                         visitObjectType(objectType);
34681                     }
34682                 }
34683                 if (type.flags & 262144 /* TypeParameter */) {
34684                     visitTypeParameter(type);
34685                 }
34686                 if (type.flags & 3145728 /* UnionOrIntersection */) {
34687                     visitUnionOrIntersectionType(type);
34688                 }
34689                 if (type.flags & 4194304 /* Index */) {
34690                     visitIndexType(type);
34691                 }
34692                 if (type.flags & 8388608 /* IndexedAccess */) {
34693                     visitIndexedAccessType(type);
34694                 }
34695             }
34696             function visitTypeReference(type) {
34697                 visitType(type.target);
34698                 ts.forEach(getTypeArguments(type), visitType);
34699             }
34700             function visitTypeParameter(type) {
34701                 visitType(getConstraintOfTypeParameter(type));
34702             }
34703             function visitUnionOrIntersectionType(type) {
34704                 ts.forEach(type.types, visitType);
34705             }
34706             function visitIndexType(type) {
34707                 visitType(type.type);
34708             }
34709             function visitIndexedAccessType(type) {
34710                 visitType(type.objectType);
34711                 visitType(type.indexType);
34712                 visitType(type.constraint);
34713             }
34714             function visitMappedType(type) {
34715                 visitType(type.typeParameter);
34716                 visitType(type.constraintType);
34717                 visitType(type.templateType);
34718                 visitType(type.modifiersType);
34719             }
34720             function visitSignature(signature) {
34721                 var typePredicate = getTypePredicateOfSignature(signature);
34722                 if (typePredicate) {
34723                     visitType(typePredicate.type);
34724                 }
34725                 ts.forEach(signature.typeParameters, visitType);
34726                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
34727                     var parameter = _a[_i];
34728                     visitSymbol(parameter);
34729                 }
34730                 visitType(getRestTypeOfSignature(signature));
34731                 visitType(getReturnTypeOfSignature(signature));
34732             }
34733             function visitInterfaceType(interfaceT) {
34734                 visitObjectType(interfaceT);
34735                 ts.forEach(interfaceT.typeParameters, visitType);
34736                 ts.forEach(getBaseTypes(interfaceT), visitType);
34737                 visitType(interfaceT.thisType);
34738             }
34739             function visitObjectType(type) {
34740                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
34741                 visitType(stringIndexType);
34742                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
34743                 visitType(numberIndexType);
34744                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
34745                 var resolved = resolveStructuredTypeMembers(type);
34746                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
34747                     var signature = _a[_i];
34748                     visitSignature(signature);
34749                 }
34750                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
34751                     var signature = _c[_b];
34752                     visitSignature(signature);
34753                 }
34754                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
34755                     var p = _e[_d];
34756                     visitSymbol(p);
34757                 }
34758             }
34759             function visitSymbol(symbol) {
34760                 if (!symbol) {
34761                     return false;
34762                 }
34763                 var symbolId = ts.getSymbolId(symbol);
34764                 if (visitedSymbols[symbolId]) {
34765                     return false;
34766                 }
34767                 visitedSymbols[symbolId] = symbol;
34768                 if (!accept(symbol)) {
34769                     return true;
34770                 }
34771                 var t = getTypeOfSymbol(symbol);
34772                 visitType(t); // Should handle members on classes and such
34773                 if (symbol.exports) {
34774                     symbol.exports.forEach(visitSymbol);
34775                 }
34776                 ts.forEach(symbol.declarations, function (d) {
34777                     // Type queries are too far resolved when we just visit the symbol's type
34778                     //  (their type resolved directly to the member deeply referenced)
34779                     // So to get the intervening symbols, we need to check if there's a type
34780                     // query node on any of the symbol's declarations and get symbols there
34781                     if (d.type && d.type.kind === 172 /* TypeQuery */) {
34782                         var query = d.type;
34783                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
34784                         visitSymbol(entity);
34785                     }
34786                 });
34787                 return false;
34788             }
34789         }
34790     }
34791     ts.createGetSymbolWalker = createGetSymbolWalker;
34792 })(ts || (ts = {}));
34793 /* @internal */
34794 var ts;
34795 (function (ts) {
34796     var ambientModuleSymbolRegex = /^".+"$/;
34797     var anon = "(anonymous)";
34798     var nextSymbolId = 1;
34799     var nextNodeId = 1;
34800     var nextMergeId = 1;
34801     var nextFlowId = 1;
34802     var IterationUse;
34803     (function (IterationUse) {
34804         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
34805         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
34806         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
34807         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
34808         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
34809         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
34810         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
34811         // Spread, Destructuring, Array element assignment
34812         IterationUse[IterationUse["Element"] = 1] = "Element";
34813         IterationUse[IterationUse["Spread"] = 33] = "Spread";
34814         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
34815         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
34816         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
34817         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
34818         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
34819         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
34820         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
34821     })(IterationUse || (IterationUse = {}));
34822     var IterationTypeKind;
34823     (function (IterationTypeKind) {
34824         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
34825         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
34826         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
34827     })(IterationTypeKind || (IterationTypeKind = {}));
34828     var WideningKind;
34829     (function (WideningKind) {
34830         WideningKind[WideningKind["Normal"] = 0] = "Normal";
34831         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
34832         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
34833         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
34834     })(WideningKind || (WideningKind = {}));
34835     var TypeFacts;
34836     (function (TypeFacts) {
34837         TypeFacts[TypeFacts["None"] = 0] = "None";
34838         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
34839         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
34840         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
34841         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
34842         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
34843         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
34844         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
34845         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
34846         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
34847         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
34848         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
34849         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
34850         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
34851         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
34852         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
34853         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
34854         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
34855         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
34856         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
34857         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
34858         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
34859         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
34860         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
34861         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
34862         TypeFacts[TypeFacts["All"] = 16777215] = "All";
34863         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
34864         // The presence of a particular fact means that the given test is true for some (and possibly all) values
34865         // of that kind of type.
34866         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
34867         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
34868         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
34869         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
34870         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
34871         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
34872         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
34873         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
34874         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
34875         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
34876         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
34877         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
34878         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
34879         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
34880         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
34881         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
34882         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
34883         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
34884         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
34885         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
34886         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
34887         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
34888         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
34889         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
34890         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
34891         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
34892         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
34893         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
34894         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
34895         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
34896         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
34897         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
34898         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
34899         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
34900         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
34901         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
34902         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
34903         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
34904         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
34905         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
34906         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
34907         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
34908     })(TypeFacts || (TypeFacts = {}));
34909     var typeofEQFacts = ts.createMapFromTemplate({
34910         string: 1 /* TypeofEQString */,
34911         number: 2 /* TypeofEQNumber */,
34912         bigint: 4 /* TypeofEQBigInt */,
34913         boolean: 8 /* TypeofEQBoolean */,
34914         symbol: 16 /* TypeofEQSymbol */,
34915         undefined: 65536 /* EQUndefined */,
34916         object: 32 /* TypeofEQObject */,
34917         function: 64 /* TypeofEQFunction */
34918     });
34919     var typeofNEFacts = ts.createMapFromTemplate({
34920         string: 256 /* TypeofNEString */,
34921         number: 512 /* TypeofNENumber */,
34922         bigint: 1024 /* TypeofNEBigInt */,
34923         boolean: 2048 /* TypeofNEBoolean */,
34924         symbol: 4096 /* TypeofNESymbol */,
34925         undefined: 524288 /* NEUndefined */,
34926         object: 8192 /* TypeofNEObject */,
34927         function: 16384 /* TypeofNEFunction */
34928     });
34929     var TypeSystemPropertyName;
34930     (function (TypeSystemPropertyName) {
34931         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
34932         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
34933         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
34934         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
34935         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
34936         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
34937         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
34938     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
34939     var CheckMode;
34940     (function (CheckMode) {
34941         CheckMode[CheckMode["Normal"] = 0] = "Normal";
34942         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
34943         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
34944         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
34945         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
34946         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
34947     })(CheckMode || (CheckMode = {}));
34948     var AccessFlags;
34949     (function (AccessFlags) {
34950         AccessFlags[AccessFlags["None"] = 0] = "None";
34951         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
34952         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
34953         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
34954         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
34955     })(AccessFlags || (AccessFlags = {}));
34956     var SignatureCheckMode;
34957     (function (SignatureCheckMode) {
34958         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
34959         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
34960         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
34961         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
34962         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
34963     })(SignatureCheckMode || (SignatureCheckMode = {}));
34964     var IntersectionState;
34965     (function (IntersectionState) {
34966         IntersectionState[IntersectionState["None"] = 0] = "None";
34967         IntersectionState[IntersectionState["Source"] = 1] = "Source";
34968         IntersectionState[IntersectionState["Target"] = 2] = "Target";
34969         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
34970         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
34971     })(IntersectionState || (IntersectionState = {}));
34972     var MappedTypeModifiers;
34973     (function (MappedTypeModifiers) {
34974         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
34975         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
34976         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
34977         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
34978     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
34979     var ExpandingFlags;
34980     (function (ExpandingFlags) {
34981         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
34982         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
34983         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
34984         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
34985     })(ExpandingFlags || (ExpandingFlags = {}));
34986     var MembersOrExportsResolutionKind;
34987     (function (MembersOrExportsResolutionKind) {
34988         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
34989         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
34990     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
34991     var UnusedKind;
34992     (function (UnusedKind) {
34993         UnusedKind[UnusedKind["Local"] = 0] = "Local";
34994         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
34995     })(UnusedKind || (UnusedKind = {}));
34996     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
34997     var DeclarationMeaning;
34998     (function (DeclarationMeaning) {
34999         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
35000         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
35001         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
35002         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
35003         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
35004         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
35005     })(DeclarationMeaning || (DeclarationMeaning = {}));
35006     var DeclarationSpaces;
35007     (function (DeclarationSpaces) {
35008         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
35009         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
35010         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
35011         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
35012     })(DeclarationSpaces || (DeclarationSpaces = {}));
35013     function SymbolLinks() {
35014     }
35015     function NodeLinks() {
35016         this.flags = 0;
35017     }
35018     function getNodeId(node) {
35019         if (!node.id) {
35020             node.id = nextNodeId;
35021             nextNodeId++;
35022         }
35023         return node.id;
35024     }
35025     ts.getNodeId = getNodeId;
35026     function getSymbolId(symbol) {
35027         if (!symbol.id) {
35028             symbol.id = nextSymbolId;
35029             nextSymbolId++;
35030         }
35031         return symbol.id;
35032     }
35033     ts.getSymbolId = getSymbolId;
35034     function isInstantiatedModule(node, preserveConstEnums) {
35035         var moduleState = ts.getModuleInstanceState(node);
35036         return moduleState === 1 /* Instantiated */ ||
35037             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
35038     }
35039     ts.isInstantiatedModule = isInstantiatedModule;
35040     function createTypeChecker(host, produceDiagnostics) {
35041         var getPackagesSet = ts.memoize(function () {
35042             var set = ts.createMap();
35043             host.getSourceFiles().forEach(function (sf) {
35044                 if (!sf.resolvedModules)
35045                     return;
35046                 ts.forEachEntry(sf.resolvedModules, function (r) {
35047                     if (r && r.packageId)
35048                         set.set(r.packageId.name, true);
35049                 });
35050             });
35051             return set;
35052         });
35053         // Cancellation that controls whether or not we can cancel in the middle of type checking.
35054         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
35055         // computing something, and we will leave our internals in an inconsistent state.  Callers
35056         // who set the cancellation token should catch if a cancellation exception occurs, and
35057         // should throw away and create a new TypeChecker.
35058         //
35059         // Currently we only support setting the cancellation token when getting diagnostics.  This
35060         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
35061         // they no longer need the information (for example, if the user started editing again).
35062         var cancellationToken;
35063         var requestedExternalEmitHelpers;
35064         var externalHelpersModule;
35065         var Symbol = ts.objectAllocator.getSymbolConstructor();
35066         var Type = ts.objectAllocator.getTypeConstructor();
35067         var Signature = ts.objectAllocator.getSignatureConstructor();
35068         var typeCount = 0;
35069         var symbolCount = 0;
35070         var enumCount = 0;
35071         var totalInstantiationCount = 0;
35072         var instantiationCount = 0;
35073         var instantiationDepth = 0;
35074         var constraintDepth = 0;
35075         var currentNode;
35076         var emptySymbols = ts.createSymbolTable();
35077         var arrayVariances = [1 /* Covariant */];
35078         var compilerOptions = host.getCompilerOptions();
35079         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
35080         var moduleKind = ts.getEmitModuleKind(compilerOptions);
35081         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
35082         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
35083         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
35084         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
35085         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
35086         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
35087         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
35088         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
35089         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
35090         var emitResolver = createResolver();
35091         var nodeBuilder = createNodeBuilder();
35092         var globals = ts.createSymbolTable();
35093         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
35094         undefinedSymbol.declarations = [];
35095         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
35096         globalThisSymbol.exports = globals;
35097         globalThisSymbol.declarations = [];
35098         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
35099         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
35100         var requireSymbol = createSymbol(4 /* Property */, "require");
35101         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
35102         var apparentArgumentCount;
35103         // for public members that accept a Node or one of its subtypes, we must guard against
35104         // synthetic nodes created during transformations by calling `getParseTreeNode`.
35105         // for most of these, we perform the guard only on `checker` to avoid any possible
35106         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
35107         // checker.
35108         var checker = {
35109             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
35110             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
35111             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
35112             getTypeCount: function () { return typeCount; },
35113             getInstantiationCount: function () { return totalInstantiationCount; },
35114             getRelationCacheSizes: function () { return ({
35115                 assignable: assignableRelation.size,
35116                 identity: identityRelation.size,
35117                 subtype: subtypeRelation.size,
35118                 strictSubtype: strictSubtypeRelation.size,
35119             }); },
35120             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
35121             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
35122             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
35123             getMergedSymbol: getMergedSymbol,
35124             getDiagnostics: getDiagnostics,
35125             getGlobalDiagnostics: getGlobalDiagnostics,
35126             getTypeOfSymbolAtLocation: function (symbol, location) {
35127                 location = ts.getParseTreeNode(location);
35128                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
35129             },
35130             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
35131                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
35132                 if (parameter === undefined)
35133                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
35134                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
35135             },
35136             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
35137             getPropertiesOfType: getPropertiesOfType,
35138             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
35139             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
35140                 var node = ts.getParseTreeNode(location);
35141                 if (!node) {
35142                     return undefined;
35143                 }
35144                 var propName = ts.escapeLeadingUnderscores(name);
35145                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
35146                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
35147             },
35148             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
35149             getIndexInfoOfType: getIndexInfoOfType,
35150             getSignaturesOfType: getSignaturesOfType,
35151             getIndexTypeOfType: getIndexTypeOfType,
35152             getBaseTypes: getBaseTypes,
35153             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
35154             getWidenedType: getWidenedType,
35155             getTypeFromTypeNode: function (nodeIn) {
35156                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35157                 return node ? getTypeFromTypeNode(node) : errorType;
35158             },
35159             getParameterType: getTypeAtPosition,
35160             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
35161             getReturnTypeOfSignature: getReturnTypeOfSignature,
35162             isNullableType: isNullableType,
35163             getNullableType: getNullableType,
35164             getNonNullableType: getNonNullableType,
35165             getNonOptionalType: removeOptionalTypeMarker,
35166             getTypeArguments: getTypeArguments,
35167             typeToTypeNode: nodeBuilder.typeToTypeNode,
35168             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
35169             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
35170             symbolToEntityName: nodeBuilder.symbolToEntityName,
35171             symbolToExpression: nodeBuilder.symbolToExpression,
35172             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
35173             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
35174             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
35175             getSymbolsInScope: function (location, meaning) {
35176                 location = ts.getParseTreeNode(location);
35177                 return location ? getSymbolsInScope(location, meaning) : [];
35178             },
35179             getSymbolAtLocation: function (node) {
35180                 node = ts.getParseTreeNode(node);
35181                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
35182                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
35183             },
35184             getShorthandAssignmentValueSymbol: function (node) {
35185                 node = ts.getParseTreeNode(node);
35186                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
35187             },
35188             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
35189                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
35190                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
35191             },
35192             getExportSymbolOfSymbol: function (symbol) {
35193                 return getMergedSymbol(symbol.exportSymbol || symbol);
35194             },
35195             getTypeAtLocation: function (node) {
35196                 node = ts.getParseTreeNode(node);
35197                 return node ? getTypeOfNode(node) : errorType;
35198             },
35199             getTypeOfAssignmentPattern: function (nodeIn) {
35200                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
35201                 return node && getTypeOfAssignmentPattern(node) || errorType;
35202             },
35203             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
35204                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
35205                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
35206             },
35207             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
35208                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
35209             },
35210             typeToString: function (type, enclosingDeclaration, flags) {
35211                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
35212             },
35213             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
35214                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
35215             },
35216             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
35217                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
35218             },
35219             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
35220                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
35221             },
35222             writeType: function (type, enclosingDeclaration, flags, writer) {
35223                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35224             },
35225             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
35226                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
35227             },
35228             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
35229                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35230             },
35231             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
35232             getRootSymbols: getRootSymbols,
35233             getContextualType: function (nodeIn, contextFlags) {
35234                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
35235                 if (!node) {
35236                     return undefined;
35237                 }
35238                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
35239                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
35240                 if (contextFlags & 4 /* Completions */ && containingCall) {
35241                     var toMarkSkip = node;
35242                     do {
35243                         getNodeLinks(toMarkSkip).skipDirectInference = true;
35244                         toMarkSkip = toMarkSkip.parent;
35245                     } while (toMarkSkip && toMarkSkip !== containingCall);
35246                     getNodeLinks(containingCall).resolvedSignature = undefined;
35247                 }
35248                 var result = getContextualType(node, contextFlags);
35249                 if (contextFlags & 4 /* Completions */ && containingCall) {
35250                     var toMarkSkip = node;
35251                     do {
35252                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
35253                         toMarkSkip = toMarkSkip.parent;
35254                     } while (toMarkSkip && toMarkSkip !== containingCall);
35255                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
35256                 }
35257                 return result;
35258             },
35259             getContextualTypeForObjectLiteralElement: function (nodeIn) {
35260                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
35261                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
35262             },
35263             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
35264                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35265                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
35266             },
35267             getContextualTypeForJsxAttribute: function (nodeIn) {
35268                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
35269                 return node && getContextualTypeForJsxAttribute(node);
35270             },
35271             isContextSensitive: isContextSensitive,
35272             getFullyQualifiedName: getFullyQualifiedName,
35273             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
35274                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
35275             },
35276             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
35277                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
35278             },
35279             getExpandedParameters: getExpandedParameters,
35280             hasEffectiveRestParameter: hasEffectiveRestParameter,
35281             getConstantValue: function (nodeIn) {
35282                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
35283                 return node ? getConstantValue(node) : undefined;
35284             },
35285             isValidPropertyAccess: function (nodeIn, propertyName) {
35286                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
35287                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
35288             },
35289             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
35290                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
35291                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
35292             },
35293             getSignatureFromDeclaration: function (declarationIn) {
35294                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
35295                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
35296             },
35297             isImplementationOfOverload: function (node) {
35298                 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
35299                 return parsed ? isImplementationOfOverload(parsed) : undefined;
35300             },
35301             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
35302             getAliasedSymbol: resolveAlias,
35303             getEmitResolver: getEmitResolver,
35304             getExportsOfModule: getExportsOfModuleAsArray,
35305             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
35306             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
35307             getAmbientModules: getAmbientModules,
35308             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
35309             isOptionalParameter: function (nodeIn) {
35310                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
35311                 return node ? isOptionalParameter(node) : false;
35312             },
35313             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
35314             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
35315             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
35316                 // we deliberately exclude augmentations
35317                 // since we are only interested in declarations of the module itself
35318                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
35319             },
35320             getApparentType: getApparentType,
35321             getUnionType: getUnionType,
35322             isTypeAssignableTo: isTypeAssignableTo,
35323             createAnonymousType: createAnonymousType,
35324             createSignature: createSignature,
35325             createSymbol: createSymbol,
35326             createIndexInfo: createIndexInfo,
35327             getAnyType: function () { return anyType; },
35328             getStringType: function () { return stringType; },
35329             getNumberType: function () { return numberType; },
35330             createPromiseType: createPromiseType,
35331             createArrayType: createArrayType,
35332             getElementTypeOfArrayType: getElementTypeOfArrayType,
35333             getBooleanType: function () { return booleanType; },
35334             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
35335             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
35336             getVoidType: function () { return voidType; },
35337             getUndefinedType: function () { return undefinedType; },
35338             getNullType: function () { return nullType; },
35339             getESSymbolType: function () { return esSymbolType; },
35340             getNeverType: function () { return neverType; },
35341             getOptionalType: function () { return optionalType; },
35342             isSymbolAccessible: isSymbolAccessible,
35343             isArrayType: isArrayType,
35344             isTupleType: isTupleType,
35345             isArrayLikeType: isArrayLikeType,
35346             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
35347             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
35348             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
35349             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
35350             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35351             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35352             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
35353             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
35354             getBaseConstraintOfType: getBaseConstraintOfType,
35355             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
35356             resolveName: function (name, location, meaning, excludeGlobals) {
35357                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
35358             },
35359             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
35360             getAccessibleSymbolChain: getAccessibleSymbolChain,
35361             getTypePredicateOfSignature: getTypePredicateOfSignature,
35362             resolveExternalModuleName: function (moduleSpecifier) {
35363                 return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
35364             },
35365             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
35366             tryGetThisTypeAt: function (node, includeGlobalThis) {
35367                 node = ts.getParseTreeNode(node);
35368                 return node && tryGetThisTypeAt(node, includeGlobalThis);
35369             },
35370             getTypeArgumentConstraint: function (nodeIn) {
35371                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35372                 return node && getTypeArgumentConstraint(node);
35373             },
35374             getSuggestionDiagnostics: function (file, ct) {
35375                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
35376                     return ts.emptyArray;
35377                 }
35378                 var diagnostics;
35379                 try {
35380                     // Record the cancellation token so it can be checked later on during checkSourceElement.
35381                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
35382                     // this call is done.
35383                     cancellationToken = ct;
35384                     // Ensure file is type checked
35385                     checkSourceFile(file);
35386                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
35387                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
35388                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
35389                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
35390                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
35391                         }
35392                     });
35393                     return diagnostics || ts.emptyArray;
35394                 }
35395                 finally {
35396                     cancellationToken = undefined;
35397                 }
35398             },
35399             runWithCancellationToken: function (token, callback) {
35400                 try {
35401                     cancellationToken = token;
35402                     return callback(checker);
35403                 }
35404                 finally {
35405                     cancellationToken = undefined;
35406                 }
35407             },
35408             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
35409             isDeclarationVisible: isDeclarationVisible,
35410         };
35411         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
35412             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35413             apparentArgumentCount = argumentCount;
35414             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
35415             apparentArgumentCount = undefined;
35416             return res;
35417         }
35418         var tupleTypes = ts.createMap();
35419         var unionTypes = ts.createMap();
35420         var intersectionTypes = ts.createMap();
35421         var literalTypes = ts.createMap();
35422         var indexedAccessTypes = ts.createMap();
35423         var substitutionTypes = ts.createMap();
35424         var evolvingArrayTypes = [];
35425         var undefinedProperties = ts.createMap();
35426         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
35427         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
35428         var anyType = createIntrinsicType(1 /* Any */, "any");
35429         var autoType = createIntrinsicType(1 /* Any */, "any");
35430         var wildcardType = createIntrinsicType(1 /* Any */, "any");
35431         var errorType = createIntrinsicType(1 /* Any */, "error");
35432         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
35433         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
35434         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
35435         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
35436         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
35437         var nullType = createIntrinsicType(65536 /* Null */, "null");
35438         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
35439         var stringType = createIntrinsicType(4 /* String */, "string");
35440         var numberType = createIntrinsicType(8 /* Number */, "number");
35441         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
35442         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35443         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35444         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35445         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35446         trueType.regularType = regularTrueType;
35447         trueType.freshType = trueType;
35448         regularTrueType.regularType = regularTrueType;
35449         regularTrueType.freshType = trueType;
35450         falseType.regularType = regularFalseType;
35451         falseType.freshType = falseType;
35452         regularFalseType.regularType = regularFalseType;
35453         regularFalseType.freshType = falseType;
35454         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
35455         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
35456         // (The union is cached, so simply doing the marking here is sufficient)
35457         createBooleanType([regularFalseType, trueType]);
35458         createBooleanType([falseType, regularTrueType]);
35459         createBooleanType([falseType, trueType]);
35460         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
35461         var voidType = createIntrinsicType(16384 /* Void */, "void");
35462         var neverType = createIntrinsicType(131072 /* Never */, "never");
35463         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
35464         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
35465         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
35466         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
35467         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
35468         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
35469         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
35470         var numberOrBigIntType = getUnionType([numberType, bigintType]);
35471         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
35472         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
35473         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35474         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35475         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
35476         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
35477         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
35478         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35479         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35480         emptyGenericType.instantiations = ts.createMap();
35481         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35482         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
35483         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
35484         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
35485         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35486         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35487         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35488         var markerSuperType = createTypeParameter();
35489         var markerSubType = createTypeParameter();
35490         markerSubType.constraint = markerSuperType;
35491         var markerOtherType = createTypeParameter();
35492         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
35493         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35494         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35495         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35496         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35497         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
35498         var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
35499         var noIterationTypes = {
35500             get yieldType() { return ts.Debug.fail("Not supported"); },
35501             get returnType() { return ts.Debug.fail("Not supported"); },
35502             get nextType() { return ts.Debug.fail("Not supported"); },
35503         };
35504         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
35505         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
35506         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
35507         var asyncIterationTypesResolver = {
35508             iterableCacheKey: "iterationTypesOfAsyncIterable",
35509             iteratorCacheKey: "iterationTypesOfAsyncIterator",
35510             iteratorSymbolName: "asyncIterator",
35511             getGlobalIteratorType: getGlobalAsyncIteratorType,
35512             getGlobalIterableType: getGlobalAsyncIterableType,
35513             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
35514             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
35515             resolveIterationType: getAwaitedType,
35516             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
35517             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
35518             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,
35519         };
35520         var syncIterationTypesResolver = {
35521             iterableCacheKey: "iterationTypesOfIterable",
35522             iteratorCacheKey: "iterationTypesOfIterator",
35523             iteratorSymbolName: "iterator",
35524             getGlobalIteratorType: getGlobalIteratorType,
35525             getGlobalIterableType: getGlobalIterableType,
35526             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
35527             getGlobalGeneratorType: getGlobalGeneratorType,
35528             resolveIterationType: function (type, _errorNode) { return type; },
35529             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
35530             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
35531             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
35532         };
35533         /** Key is "/path/to/a.ts|/path/to/b.ts". */
35534         var amalgamatedDuplicates;
35535         var reverseMappedCache = ts.createMap();
35536         var ambientModulesCache;
35537         /**
35538          * List of every ambient module with a "*" wildcard.
35539          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
35540          * This is only used if there is no exact match.
35541          */
35542         var patternAmbientModules;
35543         var patternAmbientModuleAugmentations;
35544         var globalObjectType;
35545         var globalFunctionType;
35546         var globalCallableFunctionType;
35547         var globalNewableFunctionType;
35548         var globalArrayType;
35549         var globalReadonlyArrayType;
35550         var globalStringType;
35551         var globalNumberType;
35552         var globalBooleanType;
35553         var globalRegExpType;
35554         var globalThisType;
35555         var anyArrayType;
35556         var autoArrayType;
35557         var anyReadonlyArrayType;
35558         var deferredGlobalNonNullableTypeAlias;
35559         // The library files are only loaded when the feature is used.
35560         // This allows users to just specify library files they want to used through --lib
35561         // and they will not get an error from not having unrelated library files
35562         var deferredGlobalESSymbolConstructorSymbol;
35563         var deferredGlobalESSymbolType;
35564         var deferredGlobalTypedPropertyDescriptorType;
35565         var deferredGlobalPromiseType;
35566         var deferredGlobalPromiseLikeType;
35567         var deferredGlobalPromiseConstructorSymbol;
35568         var deferredGlobalPromiseConstructorLikeType;
35569         var deferredGlobalIterableType;
35570         var deferredGlobalIteratorType;
35571         var deferredGlobalIterableIteratorType;
35572         var deferredGlobalGeneratorType;
35573         var deferredGlobalIteratorYieldResultType;
35574         var deferredGlobalIteratorReturnResultType;
35575         var deferredGlobalAsyncIterableType;
35576         var deferredGlobalAsyncIteratorType;
35577         var deferredGlobalAsyncIterableIteratorType;
35578         var deferredGlobalAsyncGeneratorType;
35579         var deferredGlobalTemplateStringsArrayType;
35580         var deferredGlobalImportMetaType;
35581         var deferredGlobalExtractSymbol;
35582         var deferredGlobalOmitSymbol;
35583         var deferredGlobalBigIntType;
35584         var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
35585         var flowLoopStart = 0;
35586         var flowLoopCount = 0;
35587         var sharedFlowCount = 0;
35588         var flowAnalysisDisabled = false;
35589         var flowInvocationCount = 0;
35590         var lastFlowNode;
35591         var lastFlowNodeReachable;
35592         var flowTypeCache;
35593         var emptyStringType = getLiteralType("");
35594         var zeroType = getLiteralType(0);
35595         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
35596         var resolutionTargets = [];
35597         var resolutionResults = [];
35598         var resolutionPropertyNames = [];
35599         var suggestionCount = 0;
35600         var maximumSuggestionCount = 10;
35601         var mergedSymbols = [];
35602         var symbolLinks = [];
35603         var nodeLinks = [];
35604         var flowLoopCaches = [];
35605         var flowLoopNodes = [];
35606         var flowLoopKeys = [];
35607         var flowLoopTypes = [];
35608         var sharedFlowNodes = [];
35609         var sharedFlowTypes = [];
35610         var flowNodeReachable = [];
35611         var potentialThisCollisions = [];
35612         var potentialNewTargetCollisions = [];
35613         var potentialWeakMapCollisions = [];
35614         var awaitedTypeStack = [];
35615         var diagnostics = ts.createDiagnosticCollection();
35616         var suggestionDiagnostics = ts.createDiagnosticCollection();
35617         var typeofTypesByName = ts.createMapFromTemplate({
35618             string: stringType,
35619             number: numberType,
35620             bigint: bigintType,
35621             boolean: booleanType,
35622             symbol: esSymbolType,
35623             undefined: undefinedType
35624         });
35625         var typeofType = createTypeofType();
35626         var _jsxNamespace;
35627         var _jsxFactoryEntity;
35628         var outofbandVarianceMarkerHandler;
35629         var subtypeRelation = ts.createMap();
35630         var strictSubtypeRelation = ts.createMap();
35631         var assignableRelation = ts.createMap();
35632         var comparableRelation = ts.createMap();
35633         var identityRelation = ts.createMap();
35634         var enumRelation = ts.createMap();
35635         var builtinGlobals = ts.createSymbolTable();
35636         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
35637         initializeTypeChecker();
35638         return checker;
35639         function getJsxNamespace(location) {
35640             if (location) {
35641                 var file = ts.getSourceFileOfNode(location);
35642                 if (file) {
35643                     if (file.localJsxNamespace) {
35644                         return file.localJsxNamespace;
35645                     }
35646                     var jsxPragma = file.pragmas.get("jsx");
35647                     if (jsxPragma) {
35648                         var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
35649                         file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
35650                         ts.visitNode(file.localJsxFactory, markAsSynthetic);
35651                         if (file.localJsxFactory) {
35652                             return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
35653                         }
35654                     }
35655                 }
35656             }
35657             if (!_jsxNamespace) {
35658                 _jsxNamespace = "React";
35659                 if (compilerOptions.jsxFactory) {
35660                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
35661                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
35662                     if (_jsxFactoryEntity) {
35663                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
35664                     }
35665                 }
35666                 else if (compilerOptions.reactNamespace) {
35667                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
35668                 }
35669             }
35670             if (!_jsxFactoryEntity) {
35671                 _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
35672             }
35673             return _jsxNamespace;
35674             function markAsSynthetic(node) {
35675                 node.pos = -1;
35676                 node.end = -1;
35677                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
35678             }
35679         }
35680         function getEmitResolver(sourceFile, cancellationToken) {
35681             // Ensure we have all the type information in place for this file so that all the
35682             // emitter questions of this resolver will return the right information.
35683             getDiagnostics(sourceFile, cancellationToken);
35684             return emitResolver;
35685         }
35686         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
35687             var diagnostic = location
35688                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35689                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35690             var existing = diagnostics.lookup(diagnostic);
35691             if (existing) {
35692                 return existing;
35693             }
35694             else {
35695                 diagnostics.add(diagnostic);
35696                 return diagnostic;
35697             }
35698         }
35699         function error(location, message, arg0, arg1, arg2, arg3) {
35700             var diagnostic = location
35701                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35702                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35703             diagnostics.add(diagnostic);
35704             return diagnostic;
35705         }
35706         function addErrorOrSuggestion(isError, diagnostic) {
35707             if (isError) {
35708                 diagnostics.add(diagnostic);
35709             }
35710             else {
35711                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
35712             }
35713         }
35714         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
35715             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
35716         }
35717         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
35718             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
35719             if (maybeMissingAwait) {
35720                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
35721                 ts.addRelatedInfo(diagnostic, related);
35722             }
35723             return diagnostic;
35724         }
35725         function createSymbol(flags, name, checkFlags) {
35726             symbolCount++;
35727             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
35728             symbol.checkFlags = checkFlags || 0;
35729             return symbol;
35730         }
35731         function getExcludedSymbolFlags(flags) {
35732             var result = 0;
35733             if (flags & 2 /* BlockScopedVariable */)
35734                 result |= 111551 /* BlockScopedVariableExcludes */;
35735             if (flags & 1 /* FunctionScopedVariable */)
35736                 result |= 111550 /* FunctionScopedVariableExcludes */;
35737             if (flags & 4 /* Property */)
35738                 result |= 0 /* PropertyExcludes */;
35739             if (flags & 8 /* EnumMember */)
35740                 result |= 900095 /* EnumMemberExcludes */;
35741             if (flags & 16 /* Function */)
35742                 result |= 110991 /* FunctionExcludes */;
35743             if (flags & 32 /* Class */)
35744                 result |= 899503 /* ClassExcludes */;
35745             if (flags & 64 /* Interface */)
35746                 result |= 788872 /* InterfaceExcludes */;
35747             if (flags & 256 /* RegularEnum */)
35748                 result |= 899327 /* RegularEnumExcludes */;
35749             if (flags & 128 /* ConstEnum */)
35750                 result |= 899967 /* ConstEnumExcludes */;
35751             if (flags & 512 /* ValueModule */)
35752                 result |= 110735 /* ValueModuleExcludes */;
35753             if (flags & 8192 /* Method */)
35754                 result |= 103359 /* MethodExcludes */;
35755             if (flags & 32768 /* GetAccessor */)
35756                 result |= 46015 /* GetAccessorExcludes */;
35757             if (flags & 65536 /* SetAccessor */)
35758                 result |= 78783 /* SetAccessorExcludes */;
35759             if (flags & 262144 /* TypeParameter */)
35760                 result |= 526824 /* TypeParameterExcludes */;
35761             if (flags & 524288 /* TypeAlias */)
35762                 result |= 788968 /* TypeAliasExcludes */;
35763             if (flags & 2097152 /* Alias */)
35764                 result |= 2097152 /* AliasExcludes */;
35765             return result;
35766         }
35767         function recordMergedSymbol(target, source) {
35768             if (!source.mergeId) {
35769                 source.mergeId = nextMergeId;
35770                 nextMergeId++;
35771             }
35772             mergedSymbols[source.mergeId] = target;
35773         }
35774         function cloneSymbol(symbol) {
35775             var result = createSymbol(symbol.flags, symbol.escapedName);
35776             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
35777             result.parent = symbol.parent;
35778             if (symbol.valueDeclaration)
35779                 result.valueDeclaration = symbol.valueDeclaration;
35780             if (symbol.constEnumOnlyModule)
35781                 result.constEnumOnlyModule = true;
35782             if (symbol.members)
35783                 result.members = ts.cloneMap(symbol.members);
35784             if (symbol.exports)
35785                 result.exports = ts.cloneMap(symbol.exports);
35786             recordMergedSymbol(result, symbol);
35787             return result;
35788         }
35789         /**
35790          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
35791          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
35792          */
35793         function mergeSymbol(target, source, unidirectional) {
35794             if (unidirectional === void 0) { unidirectional = false; }
35795             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
35796                 (source.flags | target.flags) & 67108864 /* Assignment */) {
35797                 if (source === target) {
35798                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
35799                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
35800                     return target;
35801                 }
35802                 if (!(target.flags & 33554432 /* Transient */)) {
35803                     var resolvedTarget = resolveSymbol(target);
35804                     if (resolvedTarget === unknownSymbol) {
35805                         return source;
35806                     }
35807                     target = cloneSymbol(resolvedTarget);
35808                 }
35809                 // Javascript static-property-assignment declarations always merge, even though they are also values
35810                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
35811                     // reset flag when merging instantiated module into value module that has only const enums
35812                     target.constEnumOnlyModule = false;
35813                 }
35814                 target.flags |= source.flags;
35815                 if (source.valueDeclaration) {
35816                     ts.setValueDeclaration(target, source.valueDeclaration);
35817                 }
35818                 ts.addRange(target.declarations, source.declarations);
35819                 if (source.members) {
35820                     if (!target.members)
35821                         target.members = ts.createSymbolTable();
35822                     mergeSymbolTable(target.members, source.members, unidirectional);
35823                 }
35824                 if (source.exports) {
35825                     if (!target.exports)
35826                         target.exports = ts.createSymbolTable();
35827                     mergeSymbolTable(target.exports, source.exports, unidirectional);
35828                 }
35829                 if (!unidirectional) {
35830                     recordMergedSymbol(target, source);
35831                 }
35832             }
35833             else if (target.flags & 1024 /* NamespaceModule */) {
35834                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
35835                 // as we will already report a "Declaration name conflicts..." error, and this error
35836                 // won't make much sense.
35837                 if (target !== globalThisSymbol) {
35838                     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));
35839                 }
35840             }
35841             else { // error
35842                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
35843                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
35844                 var message = isEitherEnum
35845                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
35846                     : isEitherBlockScoped_1
35847                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
35848                         : ts.Diagnostics.Duplicate_identifier_0;
35849                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
35850                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
35851                 var symbolName_1 = symbolToString(source);
35852                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
35853                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
35854                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
35855                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
35856                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
35857                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
35858                     });
35859                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
35860                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
35861                     });
35862                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
35863                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
35864                 }
35865                 else {
35866                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
35867                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
35868                 }
35869             }
35870             return target;
35871             function addDuplicateLocations(locs, symbol) {
35872                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35873                     var decl = _a[_i];
35874                     ts.pushIfUnique(locs, decl);
35875                 }
35876             }
35877         }
35878         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
35879             ts.forEach(target.declarations, function (node) {
35880                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
35881             });
35882         }
35883         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
35884             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
35885             var err = lookupOrIssueError(errorNode, message, symbolName);
35886             var _loop_6 = function (relatedNode) {
35887                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
35888                 if (adjustedNode === errorNode)
35889                     return "continue";
35890                 err.relatedInformation = err.relatedInformation || [];
35891                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
35892                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
35893                 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 */; }))
35894                     return "continue";
35895                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
35896             };
35897             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
35898                 var relatedNode = _a[_i];
35899                 _loop_6(relatedNode);
35900             }
35901         }
35902         function combineSymbolTables(first, second) {
35903             if (!ts.hasEntries(first))
35904                 return second;
35905             if (!ts.hasEntries(second))
35906                 return first;
35907             var combined = ts.createSymbolTable();
35908             mergeSymbolTable(combined, first);
35909             mergeSymbolTable(combined, second);
35910             return combined;
35911         }
35912         function mergeSymbolTable(target, source, unidirectional) {
35913             if (unidirectional === void 0) { unidirectional = false; }
35914             source.forEach(function (sourceSymbol, id) {
35915                 var targetSymbol = target.get(id);
35916                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
35917             });
35918         }
35919         function mergeModuleAugmentation(moduleName) {
35920             var _a, _b;
35921             var moduleAugmentation = moduleName.parent;
35922             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
35923                 // this is a combined symbol for multiple augmentations within the same file.
35924                 // its symbol already has accumulated information for all declarations
35925                 // so we need to add it just once - do the work only for first declaration
35926                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
35927                 return;
35928             }
35929             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
35930                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
35931             }
35932             else {
35933                 // find a module that about to be augmented
35934                 // do not validate names of augmentations that are defined in ambient context
35935                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
35936                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
35937                     : undefined;
35938                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
35939                 if (!mainModule_1) {
35940                     return;
35941                 }
35942                 // obtain item referenced by 'export='
35943                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
35944                 if (mainModule_1.flags & 1920 /* Namespace */) {
35945                     // If we're merging an augmentation to a pattern ambient module, we want to
35946                     // perform the merge unidirectionally from the augmentation ('a.foo') to
35947                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
35948                     // all the exports both from the pattern and from the augmentation, but
35949                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
35950                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
35951                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
35952                         if (!patternAmbientModuleAugmentations) {
35953                             patternAmbientModuleAugmentations = ts.createMap();
35954                         }
35955                         // moduleName will be a StringLiteral since this is not `declare global`.
35956                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
35957                     }
35958                     else {
35959                         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)) {
35960                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
35961                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
35962                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
35963                                 var _d = _c[_i], key = _d[0], value = _d[1];
35964                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
35965                                     mergeSymbol(resolvedExports.get(key), value);
35966                                 }
35967                             }
35968                         }
35969                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
35970                     }
35971                 }
35972                 else {
35973                     // moduleName will be a StringLiteral since this is not `declare global`.
35974                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
35975                 }
35976             }
35977         }
35978         function addToSymbolTable(target, source, message) {
35979             source.forEach(function (sourceSymbol, id) {
35980                 var targetSymbol = target.get(id);
35981                 if (targetSymbol) {
35982                     // Error on redeclarations
35983                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
35984                 }
35985                 else {
35986                     target.set(id, sourceSymbol);
35987                 }
35988             });
35989             function addDeclarationDiagnostic(id, message) {
35990                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
35991             }
35992         }
35993         function getSymbolLinks(symbol) {
35994             if (symbol.flags & 33554432 /* Transient */)
35995                 return symbol;
35996             var id = getSymbolId(symbol);
35997             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
35998         }
35999         function getNodeLinks(node) {
36000             var nodeId = getNodeId(node);
36001             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
36002         }
36003         function isGlobalSourceFile(node) {
36004             return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
36005         }
36006         function getSymbol(symbols, name, meaning) {
36007             if (meaning) {
36008                 var symbol = getMergedSymbol(symbols.get(name));
36009                 if (symbol) {
36010                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
36011                     if (symbol.flags & meaning) {
36012                         return symbol;
36013                     }
36014                     if (symbol.flags & 2097152 /* Alias */) {
36015                         var target = resolveAlias(symbol);
36016                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
36017                         if (target === unknownSymbol || target.flags & meaning) {
36018                             return symbol;
36019                         }
36020                     }
36021                 }
36022             }
36023             // return undefined if we can't find a symbol.
36024         }
36025         /**
36026          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
36027          * @param parameter a parameterDeclaration node
36028          * @param parameterName a name of the parameter to get the symbols for.
36029          * @return a tuple of two symbols
36030          */
36031         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
36032             var constructorDeclaration = parameter.parent;
36033             var classDeclaration = parameter.parent.parent;
36034             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
36035             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
36036             if (parameterSymbol && propertySymbol) {
36037                 return [parameterSymbol, propertySymbol];
36038             }
36039             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
36040         }
36041         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
36042             var declarationFile = ts.getSourceFileOfNode(declaration);
36043             var useFile = ts.getSourceFileOfNode(usage);
36044             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
36045             if (declarationFile !== useFile) {
36046                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
36047                     (!compilerOptions.outFile && !compilerOptions.out) ||
36048                     isInTypeQuery(usage) ||
36049                     declaration.flags & 8388608 /* Ambient */) {
36050                     // nodes are in different files and order cannot be determined
36051                     return true;
36052                 }
36053                 // declaration is after usage
36054                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
36055                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
36056                     return true;
36057                 }
36058                 var sourceFiles = host.getSourceFiles();
36059                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
36060             }
36061             if (declaration.pos <= usage.pos) {
36062                 // declaration is before usage
36063                 if (declaration.kind === 191 /* BindingElement */) {
36064                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
36065                     var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
36066                     if (errorBindingElement) {
36067                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
36068                             declaration.pos < errorBindingElement.pos;
36069                     }
36070                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
36071                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
36072                 }
36073                 else if (declaration.kind === 242 /* VariableDeclaration */) {
36074                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
36075                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
36076                 }
36077                 else if (ts.isClassDeclaration(declaration)) {
36078                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
36079                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
36080                 }
36081                 else if (ts.isPropertyDeclaration(declaration)) {
36082                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
36083                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
36084                 }
36085                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
36086                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
36087                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
36088                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
36089                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
36090                 }
36091                 return true;
36092             }
36093             // declaration is after usage, but it can still be legal if usage is deferred:
36094             // 1. inside an export specifier
36095             // 2. inside a function
36096             // 3. inside an instance property initializer, a reference to a non-instance property
36097             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
36098             // 4. inside a static property initializer, a reference to a static method in the same class
36099             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
36100             // or if usage is in a type context:
36101             // 1. inside a type query (typeof in type position)
36102             // 2. inside a jsdoc comment
36103             if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
36104                 // export specifiers do not use the variable, they only make it available for use
36105                 return true;
36106             }
36107             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
36108             if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
36109                 return true;
36110             }
36111             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
36112                 return true;
36113             }
36114             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
36115                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
36116                     && ts.getContainingClass(declaration)
36117                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
36118                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
36119                 }
36120                 else {
36121                     return true;
36122                 }
36123             }
36124             return false;
36125             function usageInTypeDeclaration() {
36126                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
36127             }
36128             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
36129                 switch (declaration.parent.parent.kind) {
36130                     case 225 /* VariableStatement */:
36131                     case 230 /* ForStatement */:
36132                     case 232 /* ForOfStatement */:
36133                         // variable statement/for/for-of statement case,
36134                         // use site should not be inside variable declaration (initializer of declaration or binding element)
36135                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
36136                             return true;
36137                         }
36138                         break;
36139                 }
36140                 // ForIn/ForOf case - use site should not be used in expression part
36141                 var grandparent = declaration.parent.parent;
36142                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
36143             }
36144             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
36145                 return !!ts.findAncestor(usage, function (current) {
36146                     if (current === declContainer) {
36147                         return "quit";
36148                     }
36149                     if (ts.isFunctionLike(current)) {
36150                         return true;
36151                     }
36152                     var initializerOfProperty = current.parent &&
36153                         current.parent.kind === 159 /* PropertyDeclaration */ &&
36154                         current.parent.initializer === current;
36155                     if (initializerOfProperty) {
36156                         if (ts.hasModifier(current.parent, 32 /* Static */)) {
36157                             if (declaration.kind === 161 /* MethodDeclaration */) {
36158                                 return true;
36159                             }
36160                         }
36161                         else {
36162                             var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
36163                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
36164                                 return true;
36165                             }
36166                         }
36167                     }
36168                     return false;
36169                 });
36170             }
36171             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
36172             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
36173                 // always legal if usage is after declaration
36174                 if (usage.end > declaration.end) {
36175                     return false;
36176                 }
36177                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
36178                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
36179                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
36180                     if (node === declaration) {
36181                         return "quit";
36182                     }
36183                     switch (node.kind) {
36184                         case 202 /* ArrowFunction */:
36185                             return true;
36186                         case 159 /* PropertyDeclaration */:
36187                             // even when stopping at any property declaration, they need to come from the same class
36188                             return stopAtAnyPropertyDeclaration &&
36189                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
36190                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
36191                                 ? "quit" : true;
36192                         case 223 /* Block */:
36193                             switch (node.parent.kind) {
36194                                 case 163 /* GetAccessor */:
36195                                 case 161 /* MethodDeclaration */:
36196                                 case 164 /* SetAccessor */:
36197                                     return true;
36198                                 default:
36199                                     return false;
36200                             }
36201                         default:
36202                             return false;
36203                     }
36204                 });
36205                 return ancestorChangingReferenceScope === undefined;
36206             }
36207         }
36208         function useOuterVariableScopeInParameter(result, location, lastLocation) {
36209             var target = ts.getEmitScriptTarget(compilerOptions);
36210             var functionLocation = location;
36211             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
36212                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
36213                 // - static field in a class expression
36214                 // - optional chaining pre-es2020
36215                 // - nullish coalesce pre-es2020
36216                 // - spread assignment in binding pattern pre-es2017
36217                 if (target >= 2 /* ES2015 */) {
36218                     var links = getNodeLinks(functionLocation);
36219                     if (links.declarationRequiresScopeChange === undefined) {
36220                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
36221                     }
36222                     return !links.declarationRequiresScopeChange;
36223                 }
36224             }
36225             return false;
36226             function requiresScopeChange(node) {
36227                 return requiresScopeChangeWorker(node.name)
36228                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
36229             }
36230             function requiresScopeChangeWorker(node) {
36231                 switch (node.kind) {
36232                     case 202 /* ArrowFunction */:
36233                     case 201 /* FunctionExpression */:
36234                     case 244 /* FunctionDeclaration */:
36235                     case 162 /* Constructor */:
36236                         // do not descend into these
36237                         return false;
36238                     case 161 /* MethodDeclaration */:
36239                     case 163 /* GetAccessor */:
36240                     case 164 /* SetAccessor */:
36241                     case 281 /* PropertyAssignment */:
36242                         return requiresScopeChangeWorker(node.name);
36243                     case 159 /* PropertyDeclaration */:
36244                         // static properties in classes introduce temporary variables
36245                         if (ts.hasStaticModifier(node)) {
36246                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
36247                         }
36248                         return requiresScopeChangeWorker(node.name);
36249                     default:
36250                         // null coalesce and optional chain pre-es2020 produce temporary variables
36251                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
36252                             return target < 7 /* ES2020 */;
36253                         }
36254                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
36255                             return target < 4 /* ES2017 */;
36256                         }
36257                         if (ts.isTypeNode(node))
36258                             return false;
36259                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
36260                 }
36261             }
36262         }
36263         /**
36264          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
36265          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
36266          * the given name can be found.
36267          *
36268          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
36269          */
36270         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
36271             if (excludeGlobals === void 0) { excludeGlobals = false; }
36272             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
36273         }
36274         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
36275             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
36276             var result;
36277             var lastLocation;
36278             var lastSelfReferenceLocation;
36279             var propertyWithInvalidInitializer;
36280             var associatedDeclarationForContainingInitializerOrBindingName;
36281             var withinDeferredContext = false;
36282             var errorLocation = location;
36283             var grandparent;
36284             var isInExternalModule = false;
36285             loop: while (location) {
36286                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
36287                 if (location.locals && !isGlobalSourceFile(location)) {
36288                     if (result = lookup(location.locals, name, meaning)) {
36289                         var useResult = true;
36290                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
36291                             // symbol lookup restrictions for function-like declarations
36292                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
36293                             //   list and return type. However, local types are only in scope in the function body.
36294                             // - parameters are only in the scope of function body
36295                             // This restriction does not apply to JSDoc comment types because they are parented
36296                             // at a higher level than type parameters would normally be
36297                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
36298                                 useResult = result.flags & 262144 /* TypeParameter */
36299                                     // type parameters are visible in parameter list, return type and type parameter list
36300                                     ? lastLocation === location.type ||
36301                                         lastLocation.kind === 156 /* Parameter */ ||
36302                                         lastLocation.kind === 155 /* TypeParameter */
36303                                     // local types not visible outside the function body
36304                                     : false;
36305                             }
36306                             if (meaning & result.flags & 3 /* Variable */) {
36307                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
36308                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
36309                                     useResult = false;
36310                                 }
36311                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
36312                                     // parameters are visible only inside function body, parameter list and return type
36313                                     // technically for parameter list case here we might mix parameters and variables declared in function,
36314                                     // however it is detected separately when checking initializers of parameters
36315                                     // to make sure that they reference no variables declared after them.
36316                                     useResult =
36317                                         lastLocation.kind === 156 /* Parameter */ ||
36318                                             (lastLocation === location.type &&
36319                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
36320                                 }
36321                             }
36322                         }
36323                         else if (location.kind === 180 /* ConditionalType */) {
36324                             // A type parameter declared using 'infer T' in a conditional type is visible only in
36325                             // the true branch of the conditional type.
36326                             useResult = lastLocation === location.trueType;
36327                         }
36328                         if (useResult) {
36329                             break loop;
36330                         }
36331                         else {
36332                             result = undefined;
36333                         }
36334                     }
36335                 }
36336                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
36337                 switch (location.kind) {
36338                     case 290 /* SourceFile */:
36339                         if (!ts.isExternalOrCommonJsModule(location))
36340                             break;
36341                         isInExternalModule = true;
36342                     // falls through
36343                     case 249 /* ModuleDeclaration */:
36344                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
36345                         if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
36346                             // It's an external module. First see if the module has an export default and if the local
36347                             // name of that export default matches.
36348                             if (result = moduleExports.get("default" /* Default */)) {
36349                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
36350                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
36351                                     break loop;
36352                                 }
36353                                 result = undefined;
36354                             }
36355                             // Because of module/namespace merging, a module's exports are in scope,
36356                             // yet we never want to treat an export specifier as putting a member in scope.
36357                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
36358                             // Two things to note about this:
36359                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
36360                             //        on an export specifier is that it might find the export specifier itself, and try to
36361                             //        resolve it as an alias. This will cause the checker to consider the export specifier
36362                             //        a circular alias reference when it might not be.
36363                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
36364                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
36365                             //        which is not the desired behavior.
36366                             var moduleExport = moduleExports.get(name);
36367                             if (moduleExport &&
36368                                 moduleExport.flags === 2097152 /* Alias */ &&
36369                                 (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
36370                                 break;
36371                             }
36372                         }
36373                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
36374                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
36375                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
36376                                 result = undefined;
36377                             }
36378                             else {
36379                                 break loop;
36380                             }
36381                         }
36382                         break;
36383                     case 248 /* EnumDeclaration */:
36384                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
36385                             break loop;
36386                         }
36387                         break;
36388                     case 159 /* PropertyDeclaration */:
36389                         // TypeScript 1.0 spec (April 2014): 8.4.1
36390                         // Initializer expressions for instance member variables are evaluated in the scope
36391                         // of the class constructor body but are not permitted to reference parameters or
36392                         // local variables of the constructor. This effectively means that entities from outer scopes
36393                         // by the same name as a constructor parameter or local variable are inaccessible
36394                         // in initializer expressions for instance member variables.
36395                         if (!ts.hasModifier(location, 32 /* Static */)) {
36396                             var ctor = findConstructorDeclaration(location.parent);
36397                             if (ctor && ctor.locals) {
36398                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
36399                                     // Remember the property node, it will be used later to report appropriate error
36400                                     propertyWithInvalidInitializer = location;
36401                                 }
36402                             }
36403                         }
36404                         break;
36405                     case 245 /* ClassDeclaration */:
36406                     case 214 /* ClassExpression */:
36407                     case 246 /* InterfaceDeclaration */:
36408                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
36409                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
36410                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
36411                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
36412                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
36413                                 // ignore type parameters not declared in this container
36414                                 result = undefined;
36415                                 break;
36416                             }
36417                             if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
36418                                 // TypeScript 1.0 spec (April 2014): 3.4.1
36419                                 // The scope of a type parameter extends over the entire declaration with which the type
36420                                 // parameter list is associated, with the exception of static member declarations in classes.
36421                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
36422                                 return undefined;
36423                             }
36424                             break loop;
36425                         }
36426                         if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
36427                             var className = location.name;
36428                             if (className && name === className.escapedText) {
36429                                 result = location.symbol;
36430                                 break loop;
36431                             }
36432                         }
36433                         break;
36434                     case 216 /* ExpressionWithTypeArguments */:
36435                         // The type parameters of a class are not in scope in the base class expression.
36436                         if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
36437                             var container = location.parent.parent;
36438                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
36439                                 if (nameNotFoundMessage) {
36440                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
36441                                 }
36442                                 return undefined;
36443                             }
36444                         }
36445                         break;
36446                     // It is not legal to reference a class's own type parameters from a computed property name that
36447                     // belongs to the class. For example:
36448                     //
36449                     //   function foo<T>() { return '' }
36450                     //   class C<T> { // <-- Class's own type parameter T
36451                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
36452                     //   }
36453                     //
36454                     case 154 /* ComputedPropertyName */:
36455                         grandparent = location.parent.parent;
36456                         if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
36457                             // A reference to this grandparent's type parameters would be an error
36458                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
36459                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
36460                                 return undefined;
36461                             }
36462                         }
36463                         break;
36464                     case 202 /* ArrowFunction */:
36465                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
36466                         // for lower compile targets the resolved symbol is used to emit an error
36467                         if (compilerOptions.target >= 2 /* ES2015 */) {
36468                             break;
36469                         }
36470                     // falls through
36471                     case 161 /* MethodDeclaration */:
36472                     case 162 /* Constructor */:
36473                     case 163 /* GetAccessor */:
36474                     case 164 /* SetAccessor */:
36475                     case 244 /* FunctionDeclaration */:
36476                         if (meaning & 3 /* Variable */ && name === "arguments") {
36477                             result = argumentsSymbol;
36478                             break loop;
36479                         }
36480                         break;
36481                     case 201 /* FunctionExpression */:
36482                         if (meaning & 3 /* Variable */ && name === "arguments") {
36483                             result = argumentsSymbol;
36484                             break loop;
36485                         }
36486                         if (meaning & 16 /* Function */) {
36487                             var functionName = location.name;
36488                             if (functionName && name === functionName.escapedText) {
36489                                 result = location.symbol;
36490                                 break loop;
36491                             }
36492                         }
36493                         break;
36494                     case 157 /* Decorator */:
36495                         // Decorators are resolved at the class declaration. Resolving at the parameter
36496                         // or member would result in looking up locals in the method.
36497                         //
36498                         //   function y() {}
36499                         //   class C {
36500                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
36501                         //   }
36502                         //
36503                         if (location.parent && location.parent.kind === 156 /* Parameter */) {
36504                             location = location.parent;
36505                         }
36506                         //
36507                         //   function y() {}
36508                         //   class C {
36509                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
36510                         //   }
36511                         //
36512                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
36513                         //
36514                         //   type T = number;
36515                         //   declare function y(x: T): any;
36516                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
36517                         //   class C<T> {}
36518                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
36519                             location = location.parent;
36520                         }
36521                         break;
36522                     case 322 /* JSDocTypedefTag */:
36523                     case 315 /* JSDocCallbackTag */:
36524                     case 316 /* JSDocEnumTag */:
36525                         // js type aliases do not resolve names from their host, so skip past it
36526                         location = ts.getJSDocHost(location);
36527                         break;
36528                     case 156 /* Parameter */:
36529                         if (lastLocation && (lastLocation === location.initializer ||
36530                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36531                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
36532                                 associatedDeclarationForContainingInitializerOrBindingName = location;
36533                             }
36534                         }
36535                         break;
36536                     case 191 /* BindingElement */:
36537                         if (lastLocation && (lastLocation === location.initializer ||
36538                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36539                             var root = ts.getRootDeclaration(location);
36540                             if (root.kind === 156 /* Parameter */) {
36541                                 if (!associatedDeclarationForContainingInitializerOrBindingName) {
36542                                     associatedDeclarationForContainingInitializerOrBindingName = location;
36543                                 }
36544                             }
36545                         }
36546                         break;
36547                 }
36548                 if (isSelfReferenceLocation(location)) {
36549                     lastSelfReferenceLocation = location;
36550                 }
36551                 lastLocation = location;
36552                 location = location.parent;
36553             }
36554             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
36555             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
36556             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
36557             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
36558                 result.isReferenced |= meaning;
36559             }
36560             if (!result) {
36561                 if (lastLocation) {
36562                     ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
36563                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
36564                         return lastLocation.symbol;
36565                     }
36566                 }
36567                 if (!excludeGlobals) {
36568                     result = lookup(globals, name, meaning);
36569                 }
36570             }
36571             if (!result) {
36572                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
36573                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
36574                         return requireSymbol;
36575                     }
36576                 }
36577             }
36578             if (!result) {
36579                 if (nameNotFoundMessage) {
36580                     if (!errorLocation ||
36581                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
36582                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
36583                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
36584                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
36585                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
36586                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
36587                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
36588                         var suggestion = void 0;
36589                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
36590                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
36591                             if (suggestion) {
36592                                 var suggestionName = symbolToString(suggestion);
36593                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
36594                                 if (suggestion.valueDeclaration) {
36595                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
36596                                 }
36597                             }
36598                         }
36599                         if (!suggestion) {
36600                             error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
36601                         }
36602                         suggestionCount++;
36603                     }
36604                 }
36605                 return undefined;
36606             }
36607             // Perform extra checks only if error reporting was requested
36608             if (nameNotFoundMessage) {
36609                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
36610                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
36611                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
36612                     // with ESNext+useDefineForClassFields because the scope semantics are different.
36613                     var propertyName = propertyWithInvalidInitializer.name;
36614                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
36615                     return undefined;
36616                 }
36617                 // Only check for block-scoped variable if we have an error location and are looking for the
36618                 // name with variable meaning
36619                 //      For example,
36620                 //          declare module foo {
36621                 //              interface bar {}
36622                 //          }
36623                 //      const foo/*1*/: foo/*2*/.bar;
36624                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
36625                 // block-scoped variable and namespace module. However, only when we
36626                 // try to resolve name in /*1*/ which is used in variable position,
36627                 // we want to check for block-scoped
36628                 if (errorLocation &&
36629                     (meaning & 2 /* BlockScopedVariable */ ||
36630                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
36631                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
36632                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
36633                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
36634                     }
36635                 }
36636                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
36637                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
36638                     var merged = getMergedSymbol(result);
36639                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
36640                         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));
36641                     }
36642                 }
36643                 // 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
36644                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
36645                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
36646                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
36647                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
36648                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
36649                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
36650                     }
36651                     // And it cannot refer to any declarations which come after it
36652                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
36653                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
36654                     }
36655                 }
36656                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
36657                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
36658                 }
36659             }
36660             return result;
36661         }
36662         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
36663             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
36664                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
36665                 if (typeOnlyDeclaration) {
36666                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36667                     var message = isExport
36668                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
36669                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
36670                     var relatedMessage = isExport
36671                         ? ts.Diagnostics._0_was_exported_here
36672                         : ts.Diagnostics._0_was_imported_here;
36673                     var unescapedName = ts.unescapeLeadingUnderscores(name);
36674                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
36675                 }
36676             }
36677         }
36678         function getIsDeferredContext(location, lastLocation) {
36679             if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
36680                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
36681                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
36682                     (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
36683             }
36684             if (lastLocation && lastLocation === location.name) {
36685                 return false;
36686             }
36687             // generator functions and async functions are not inlined in control flow when immediately invoked
36688             if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
36689                 return true;
36690             }
36691             return !ts.getImmediatelyInvokedFunctionExpression(location);
36692         }
36693         function isSelfReferenceLocation(node) {
36694             switch (node.kind) {
36695                 case 244 /* FunctionDeclaration */:
36696                 case 245 /* ClassDeclaration */:
36697                 case 246 /* InterfaceDeclaration */:
36698                 case 248 /* EnumDeclaration */:
36699                 case 247 /* TypeAliasDeclaration */:
36700                 case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
36701                     return true;
36702                 default:
36703                     return false;
36704             }
36705         }
36706         function diagnosticName(nameArg) {
36707             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
36708         }
36709         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
36710             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36711                 var decl = _a[_i];
36712                 if (decl.kind === 155 /* TypeParameter */) {
36713                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
36714                     if (parent === container) {
36715                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
36716                     }
36717                 }
36718             }
36719             return false;
36720         }
36721         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
36722             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
36723                 return false;
36724             }
36725             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
36726             var location = container;
36727             while (location) {
36728                 if (ts.isClassLike(location.parent)) {
36729                     var classSymbol = getSymbolOfNode(location.parent);
36730                     if (!classSymbol) {
36731                         break;
36732                     }
36733                     // Check to see if a static member exists.
36734                     var constructorType = getTypeOfSymbol(classSymbol);
36735                     if (getPropertyOfType(constructorType, name)) {
36736                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
36737                         return true;
36738                     }
36739                     // No static member is present.
36740                     // Check if we're in an instance method and look for a relevant instance member.
36741                     if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
36742                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
36743                         if (getPropertyOfType(instanceType, name)) {
36744                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
36745                             return true;
36746                         }
36747                     }
36748                 }
36749                 location = location.parent;
36750             }
36751             return false;
36752         }
36753         function checkAndReportErrorForExtendingInterface(errorLocation) {
36754             var expression = getEntityNameForExtendingInterface(errorLocation);
36755             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
36756                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
36757                 return true;
36758             }
36759             return false;
36760         }
36761         /**
36762          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
36763          * but returns undefined if that expression is not an EntityNameExpression.
36764          */
36765         function getEntityNameForExtendingInterface(node) {
36766             switch (node.kind) {
36767                 case 75 /* Identifier */:
36768                 case 194 /* PropertyAccessExpression */:
36769                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
36770                 case 216 /* ExpressionWithTypeArguments */:
36771                     if (ts.isEntityNameExpression(node.expression)) {
36772                         return node.expression;
36773                     }
36774                 // falls through
36775                 default:
36776                     return undefined;
36777             }
36778         }
36779         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
36780             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
36781             if (meaning === namespaceMeaning) {
36782                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36783                 var parent = errorLocation.parent;
36784                 if (symbol) {
36785                     if (ts.isQualifiedName(parent)) {
36786                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
36787                         var propName = parent.right.escapedText;
36788                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
36789                         if (propType) {
36790                             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));
36791                             return true;
36792                         }
36793                     }
36794                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
36795                     return true;
36796                 }
36797             }
36798             return false;
36799         }
36800         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
36801             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
36802                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36803                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
36804                     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));
36805                     return true;
36806                 }
36807             }
36808             return false;
36809         }
36810         function isPrimitiveTypeName(name) {
36811             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
36812         }
36813         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
36814             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
36815                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
36816                 return true;
36817             }
36818             return false;
36819         }
36820         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
36821             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
36822                 if (isPrimitiveTypeName(name)) {
36823                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
36824                     return true;
36825                 }
36826                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36827                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
36828                     var message = isES2015OrLaterConstructorName(name)
36829                         ? 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
36830                         : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
36831                     error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
36832                     return true;
36833                 }
36834             }
36835             return false;
36836         }
36837         function isES2015OrLaterConstructorName(n) {
36838             switch (n) {
36839                 case "Promise":
36840                 case "Symbol":
36841                 case "Map":
36842                 case "WeakMap":
36843                 case "Set":
36844                 case "WeakSet":
36845                     return true;
36846             }
36847             return false;
36848         }
36849         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
36850             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
36851                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36852                 if (symbol) {
36853                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
36854                     return true;
36855                 }
36856             }
36857             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
36858                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36859                 if (symbol) {
36860                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
36861                     return true;
36862                 }
36863             }
36864             return false;
36865         }
36866         function checkResolvedBlockScopedVariable(result, errorLocation) {
36867             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
36868             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
36869                 // constructor functions aren't block scoped
36870                 return;
36871             }
36872             // Block-scoped variables cannot be used before their definition
36873             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
36874             if (declaration === undefined)
36875                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
36876             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
36877                 var diagnosticMessage = void 0;
36878                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
36879                 if (result.flags & 2 /* BlockScopedVariable */) {
36880                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
36881                 }
36882                 else if (result.flags & 32 /* Class */) {
36883                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36884                 }
36885                 else if (result.flags & 256 /* RegularEnum */) {
36886                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
36887                 }
36888                 else {
36889                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
36890                     if (compilerOptions.preserveConstEnums) {
36891                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36892                     }
36893                 }
36894                 if (diagnosticMessage) {
36895                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
36896                 }
36897             }
36898         }
36899         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
36900          * If at any point current node is equal to 'parent' node - return true.
36901          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
36902          */
36903         function isSameScopeDescendentOf(initial, parent, stopAt) {
36904             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
36905         }
36906         function getAnyImportSyntax(node) {
36907             switch (node.kind) {
36908                 case 253 /* ImportEqualsDeclaration */:
36909                     return node;
36910                 case 255 /* ImportClause */:
36911                     return node.parent;
36912                 case 256 /* NamespaceImport */:
36913                     return node.parent.parent;
36914                 case 258 /* ImportSpecifier */:
36915                     return node.parent.parent.parent;
36916                 default:
36917                     return undefined;
36918             }
36919         }
36920         function getDeclarationOfAliasSymbol(symbol) {
36921             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
36922         }
36923         /**
36924          * An alias symbol is created by one of the following declarations:
36925          * import <symbol> = ...
36926          * import <symbol> from ...
36927          * import * as <symbol> from ...
36928          * import { x as <symbol> } from ...
36929          * export { x as <symbol> } from ...
36930          * export * as ns <symbol> from ...
36931          * export = <EntityNameExpression>
36932          * export default <EntityNameExpression>
36933          * module.exports = <EntityNameExpression>
36934          * {<Identifier>}
36935          * {name: <EntityNameExpression>}
36936          */
36937         function isAliasSymbolDeclaration(node) {
36938             return node.kind === 253 /* ImportEqualsDeclaration */ ||
36939                 node.kind === 252 /* NamespaceExportDeclaration */ ||
36940                 node.kind === 255 /* ImportClause */ && !!node.name ||
36941                 node.kind === 256 /* NamespaceImport */ ||
36942                 node.kind === 262 /* NamespaceExport */ ||
36943                 node.kind === 258 /* ImportSpecifier */ ||
36944                 node.kind === 263 /* ExportSpecifier */ ||
36945                 node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
36946                 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
36947                 ts.isPropertyAccessExpression(node)
36948                     && ts.isBinaryExpression(node.parent)
36949                     && node.parent.left === node
36950                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
36951                     && isAliasableOrJsExpression(node.parent.right) ||
36952                 node.kind === 282 /* ShorthandPropertyAssignment */ ||
36953                 node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
36954         }
36955         function isAliasableOrJsExpression(e) {
36956             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
36957         }
36958         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
36959             if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
36960                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
36961                 var resolved_4 = resolveExternalModuleSymbol(immediate);
36962                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
36963                 return resolved_4;
36964             }
36965             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
36966             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
36967             return resolved;
36968         }
36969         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
36970             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
36971                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
36972                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36973                 var message = isExport
36974                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
36975                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
36976                 var relatedMessage = isExport
36977                     ? ts.Diagnostics._0_was_exported_here
36978                     : ts.Diagnostics._0_was_imported_here;
36979                 // Non-null assertion is safe because the optionality comes from ImportClause,
36980                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
36981                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
36982                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
36983             }
36984         }
36985         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
36986             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
36987             if (exportValue) {
36988                 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
36989             }
36990             var exportSymbol = moduleSymbol.exports.get(name);
36991             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36992             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
36993             return resolved;
36994         }
36995         function isSyntacticDefault(node) {
36996             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
36997         }
36998         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
36999             if (!allowSyntheticDefaultImports) {
37000                 return false;
37001             }
37002             // Declaration files (and ambient modules)
37003             if (!file || file.isDeclarationFile) {
37004                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
37005                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
37006                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
37007                     return false;
37008                 }
37009                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
37010                 // So we check a bit more,
37011                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
37012                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
37013                     // it definitely is a module and does not have a synthetic default
37014                     return false;
37015                 }
37016                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
37017                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
37018                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
37019                 return true;
37020             }
37021             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
37022             if (!ts.isSourceFileJS(file)) {
37023                 return hasExportAssignmentSymbol(moduleSymbol);
37024             }
37025             // 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
37026             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
37027         }
37028         function getTargetOfImportClause(node, dontResolveAlias) {
37029             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
37030             if (moduleSymbol) {
37031                 var exportDefaultSymbol = void 0;
37032                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
37033                     exportDefaultSymbol = moduleSymbol;
37034                 }
37035                 else {
37036                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
37037                 }
37038                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37039                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
37040                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
37041                     if (hasExportAssignmentSymbol(moduleSymbol)) {
37042                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
37043                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
37044                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
37045                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
37046                         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));
37047                     }
37048                     else {
37049                         reportNonDefaultExport(moduleSymbol, node);
37050                     }
37051                 }
37052                 else if (hasSyntheticDefault) {
37053                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
37054                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37055                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
37056                     return resolved;
37057                 }
37058                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
37059                 return exportDefaultSymbol;
37060             }
37061         }
37062         function reportNonDefaultExport(moduleSymbol, node) {
37063             var _a, _b;
37064             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
37065                 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));
37066             }
37067             else {
37068                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
37069                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
37070                 if (exportStar) {
37071                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
37072                         var _a, _b;
37073                         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 */)));
37074                     });
37075                     if (defaultExport) {
37076                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
37077                     }
37078                 }
37079             }
37080         }
37081         function getTargetOfNamespaceImport(node, dontResolveAlias) {
37082             var moduleSpecifier = node.parent.parent.moduleSpecifier;
37083             var immediate = resolveExternalModuleName(node, moduleSpecifier);
37084             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
37085             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
37086             return resolved;
37087         }
37088         function getTargetOfNamespaceExport(node, dontResolveAlias) {
37089             var moduleSpecifier = node.parent.moduleSpecifier;
37090             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
37091             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
37092             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
37093             return resolved;
37094         }
37095         // This function creates a synthetic symbol that combines the value side of one symbol with the
37096         // type/namespace side of another symbol. Consider this example:
37097         //
37098         //   declare module graphics {
37099         //       interface Point {
37100         //           x: number;
37101         //           y: number;
37102         //       }
37103         //   }
37104         //   declare var graphics: {
37105         //       Point: new (x: number, y: number) => graphics.Point;
37106         //   }
37107         //   declare module "graphics" {
37108         //       export = graphics;
37109         //   }
37110         //
37111         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
37112         // property with the type/namespace side interface 'Point'.
37113         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
37114             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
37115                 return unknownSymbol;
37116             }
37117             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
37118                 return valueSymbol;
37119             }
37120             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
37121             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
37122             result.parent = valueSymbol.parent || typeSymbol.parent;
37123             if (valueSymbol.valueDeclaration)
37124                 result.valueDeclaration = valueSymbol.valueDeclaration;
37125             if (typeSymbol.members)
37126                 result.members = ts.cloneMap(typeSymbol.members);
37127             if (valueSymbol.exports)
37128                 result.exports = ts.cloneMap(valueSymbol.exports);
37129             return result;
37130         }
37131         function getExportOfModule(symbol, specifier, dontResolveAlias) {
37132             var _a;
37133             if (symbol.flags & 1536 /* Module */) {
37134                 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
37135                 var exportSymbol = getExportsOfSymbol(symbol).get(name);
37136                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
37137                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
37138                 return resolved;
37139             }
37140         }
37141         function getPropertyOfVariable(symbol, name) {
37142             if (symbol.flags & 3 /* Variable */) {
37143                 var typeAnnotation = symbol.valueDeclaration.type;
37144                 if (typeAnnotation) {
37145                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
37146                 }
37147             }
37148         }
37149         function getExternalModuleMember(node, specifier, dontResolveAlias) {
37150             var _a;
37151             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
37152             var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
37153             var name = specifier.propertyName || specifier.name;
37154             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
37155             var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
37156             if (targetSymbol) {
37157                 if (name.escapedText) {
37158                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
37159                         return moduleSymbol;
37160                     }
37161                     var symbolFromVariable = void 0;
37162                     // First check if module was specified with "export=". If so, get the member from the resolved type
37163                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
37164                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
37165                     }
37166                     else {
37167                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
37168                     }
37169                     // if symbolFromVariable is export - get its final target
37170                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
37171                     var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
37172                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
37173                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37174                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
37175                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37176                         }
37177                     }
37178                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
37179                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
37180                         symbolFromModule || symbolFromVariable;
37181                     if (!symbol) {
37182                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
37183                         var declarationName = ts.declarationNameToString(name);
37184                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
37185                         if (suggestion !== undefined) {
37186                             var suggestionName = symbolToString(suggestion);
37187                             var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
37188                             if (suggestion.valueDeclaration) {
37189                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
37190                             }
37191                         }
37192                         else {
37193                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
37194                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
37195                             }
37196                             else {
37197                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
37198                             }
37199                         }
37200                     }
37201                     return symbol;
37202                 }
37203             }
37204         }
37205         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
37206             var _a;
37207             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
37208             var exports = moduleSymbol.exports;
37209             if (localSymbol) {
37210                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
37211                 if (exportedEqualsSymbol) {
37212                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
37213                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37214                 }
37215                 else {
37216                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
37217                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
37218                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
37219                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
37220                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
37221                     })));
37222                 }
37223             }
37224             else {
37225                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37226             }
37227         }
37228         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
37229             if (moduleKind >= ts.ModuleKind.ES2015) {
37230                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
37231                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37232                 error(name, message, declarationName);
37233             }
37234             else {
37235                 if (ts.isInJSFile(node)) {
37236                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
37237                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37238                     error(name, message, declarationName);
37239                 }
37240                 else {
37241                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
37242                         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;
37243                     error(name, message, declarationName, declarationName, moduleName);
37244                 }
37245             }
37246         }
37247         function getTargetOfImportSpecifier(node, dontResolveAlias) {
37248             var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
37249             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37250             return resolved;
37251         }
37252         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
37253             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
37254             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37255             return resolved;
37256         }
37257         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
37258             var resolved = node.parent.parent.moduleSpecifier ?
37259                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
37260                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
37261             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37262             return resolved;
37263         }
37264         function getTargetOfExportAssignment(node, dontResolveAlias) {
37265             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
37266             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
37267             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37268             return resolved;
37269         }
37270         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
37271             if (ts.isClassExpression(expression)) {
37272                 return checkExpressionCached(expression).symbol;
37273             }
37274             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
37275                 return undefined;
37276             }
37277             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
37278             if (aliasLike) {
37279                 return aliasLike;
37280             }
37281             checkExpressionCached(expression);
37282             return getNodeLinks(expression).resolvedSymbol;
37283         }
37284         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
37285             var expression = node.initializer;
37286             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
37287         }
37288         function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
37289             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
37290                 return undefined;
37291             }
37292             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
37293         }
37294         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
37295             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
37296             switch (node.kind) {
37297                 case 253 /* ImportEqualsDeclaration */:
37298                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
37299                 case 255 /* ImportClause */:
37300                     return getTargetOfImportClause(node, dontRecursivelyResolve);
37301                 case 256 /* NamespaceImport */:
37302                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
37303                 case 262 /* NamespaceExport */:
37304                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
37305                 case 258 /* ImportSpecifier */:
37306                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
37307                 case 263 /* ExportSpecifier */:
37308                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
37309                 case 259 /* ExportAssignment */:
37310                 case 209 /* BinaryExpression */:
37311                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
37312                 case 252 /* NamespaceExportDeclaration */:
37313                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
37314                 case 282 /* ShorthandPropertyAssignment */:
37315                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
37316                 case 281 /* PropertyAssignment */:
37317                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
37318                 case 194 /* PropertyAccessExpression */:
37319                     return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
37320                 default:
37321                     return ts.Debug.fail();
37322             }
37323         }
37324         /**
37325          * Indicates that a symbol is an alias that does not merge with a local declaration.
37326          * OR Is a JSContainer which may merge an alias with a local declaration
37327          */
37328         function isNonLocalAlias(symbol, excludes) {
37329             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
37330             if (!symbol)
37331                 return false;
37332             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
37333         }
37334         function resolveSymbol(symbol, dontResolveAlias) {
37335             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
37336         }
37337         function resolveAlias(symbol) {
37338             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
37339             var links = getSymbolLinks(symbol);
37340             if (!links.target) {
37341                 links.target = resolvingSymbol;
37342                 var node = getDeclarationOfAliasSymbol(symbol);
37343                 if (!node)
37344                     return ts.Debug.fail();
37345                 var target = getTargetOfAliasDeclaration(node);
37346                 if (links.target === resolvingSymbol) {
37347                     links.target = target || unknownSymbol;
37348                 }
37349                 else {
37350                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
37351                 }
37352             }
37353             else if (links.target === resolvingSymbol) {
37354                 links.target = unknownSymbol;
37355             }
37356             return links.target;
37357         }
37358         function tryResolveAlias(symbol) {
37359             var links = getSymbolLinks(symbol);
37360             if (links.target !== resolvingSymbol) {
37361                 return resolveAlias(symbol);
37362             }
37363             return undefined;
37364         }
37365         /**
37366          * Marks a symbol as type-only if its declaration is syntactically type-only.
37367          * If it is not itself marked type-only, but resolves to a type-only alias
37368          * somewhere in its resolution chain, save a reference to the type-only alias declaration
37369          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
37370          *
37371          * This function is called on each alias declaration that could be type-only or resolve to
37372          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
37373          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
37374          * and issue an error if so.
37375          *
37376          * @param aliasDeclaration The alias declaration not marked as type-only
37377          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
37378          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
37379          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
37380          * must still be checked for a type-only marker, overwriting the previous negative result if found.
37381          * @param immediateTarget The symbol to which the alias declaration immediately resolves
37382          * @param finalTarget The symbol to which the alias declaration ultimately resolves
37383          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
37384          */
37385         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
37386             if (!aliasDeclaration)
37387                 return false;
37388             // If the declaration itself is type-only, mark it and return.
37389             // No need to check what it resolves to.
37390             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
37391             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
37392                 var links_1 = getSymbolLinks(sourceSymbol);
37393                 links_1.typeOnlyDeclaration = aliasDeclaration;
37394                 return true;
37395             }
37396             var links = getSymbolLinks(sourceSymbol);
37397             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
37398                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
37399         }
37400         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
37401             var _a, _b, _c;
37402             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
37403                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
37404                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
37405                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
37406             }
37407             return !!aliasDeclarationLinks.typeOnlyDeclaration;
37408         }
37409         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
37410         function getTypeOnlyAliasDeclaration(symbol) {
37411             if (!(symbol.flags & 2097152 /* Alias */)) {
37412                 return undefined;
37413             }
37414             var links = getSymbolLinks(symbol);
37415             return links.typeOnlyDeclaration || undefined;
37416         }
37417         function markExportAsReferenced(node) {
37418             var symbol = getSymbolOfNode(node);
37419             var target = resolveAlias(symbol);
37420             if (target) {
37421                 var markAlias = target === unknownSymbol ||
37422                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
37423                 if (markAlias) {
37424                     markAliasSymbolAsReferenced(symbol);
37425                 }
37426             }
37427         }
37428         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
37429         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
37430         // the alias as an expression (which recursively takes us back here if the target references another alias).
37431         function markAliasSymbolAsReferenced(symbol) {
37432             var links = getSymbolLinks(symbol);
37433             if (!links.referenced) {
37434                 links.referenced = true;
37435                 var node = getDeclarationOfAliasSymbol(symbol);
37436                 if (!node)
37437                     return ts.Debug.fail();
37438                 // We defer checking of the reference of an `import =` until the import itself is referenced,
37439                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
37440                 // position.
37441                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
37442                     var target = resolveSymbol(symbol);
37443                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
37444                         // import foo = <symbol>
37445                         checkExpressionCached(node.moduleReference);
37446                     }
37447                 }
37448             }
37449         }
37450         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
37451         // but their usage in value positions must be tracked to determine if the import can be type-only.
37452         function markConstEnumAliasAsReferenced(symbol) {
37453             var links = getSymbolLinks(symbol);
37454             if (!links.constEnumReferenced) {
37455                 links.constEnumReferenced = true;
37456             }
37457         }
37458         // This function is only for imports with entity names
37459         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
37460             // There are three things we might try to look for. In the following examples,
37461             // the search term is enclosed in |...|:
37462             //
37463             //     import a = |b|; // Namespace
37464             //     import a = |b.c|; // Value, type, namespace
37465             //     import a = |b.c|.d; // Namespace
37466             if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
37467                 entityName = entityName.parent;
37468             }
37469             // Check for case 1 and 3 in the above example
37470             if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
37471                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37472             }
37473             else {
37474                 // Case 2 in above example
37475                 // entityName.kind could be a QualifiedName or a Missing identifier
37476                 ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
37477                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37478             }
37479         }
37480         function getFullyQualifiedName(symbol, containingLocation) {
37481             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
37482         }
37483         /**
37484          * Resolves a qualified name and any involved aliases.
37485          */
37486         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
37487             if (ts.nodeIsMissing(name)) {
37488                 return undefined;
37489             }
37490             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
37491             var symbol;
37492             if (name.kind === 75 /* Identifier */) {
37493                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
37494                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
37495                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
37496                 if (!symbol) {
37497                     return getMergedSymbol(symbolFromJSPrototype);
37498                 }
37499             }
37500             else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
37501                 var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
37502                 var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
37503                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
37504                 if (!namespace || ts.nodeIsMissing(right)) {
37505                     return undefined;
37506                 }
37507                 else if (namespace === unknownSymbol) {
37508                     return namespace;
37509                 }
37510                 if (ts.isInJSFile(name)) {
37511                     if (namespace.valueDeclaration &&
37512                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
37513                         namespace.valueDeclaration.initializer &&
37514                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
37515                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
37516                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
37517                         if (moduleSym) {
37518                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
37519                             if (resolvedModuleSymbol) {
37520                                 namespace = resolvedModuleSymbol;
37521                             }
37522                         }
37523                     }
37524                 }
37525                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
37526                 if (!symbol) {
37527                     if (!ignoreErrors) {
37528                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
37529                     }
37530                     return undefined;
37531                 }
37532             }
37533             else {
37534                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
37535             }
37536             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
37537             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
37538                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
37539             }
37540             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
37541         }
37542         /**
37543          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
37544          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
37545          * name resolution won't work either.
37546          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
37547          */
37548         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
37549             if (isJSDocTypeReference(name.parent)) {
37550                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
37551                 if (secondaryLocation) {
37552                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
37553                 }
37554             }
37555         }
37556         function getAssignmentDeclarationLocation(node) {
37557             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
37558             if (typeAlias) {
37559                 return;
37560             }
37561             var host = ts.getJSDocHost(node);
37562             if (ts.isExpressionStatement(host) &&
37563                 ts.isBinaryExpression(host.expression) &&
37564                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
37565                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
37566                 var symbol = getSymbolOfNode(host.expression.left);
37567                 if (symbol) {
37568                     return getDeclarationOfJSPrototypeContainer(symbol);
37569                 }
37570             }
37571             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
37572                 ts.isBinaryExpression(host.parent.parent) &&
37573                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
37574                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
37575                 var symbol = getSymbolOfNode(host.parent.parent.left);
37576                 if (symbol) {
37577                     return getDeclarationOfJSPrototypeContainer(symbol);
37578                 }
37579             }
37580             var sig = ts.getEffectiveJSDocHost(node);
37581             if (sig && ts.isFunctionLike(sig)) {
37582                 var symbol = getSymbolOfNode(sig);
37583                 return symbol && symbol.valueDeclaration;
37584             }
37585         }
37586         function getDeclarationOfJSPrototypeContainer(symbol) {
37587             var decl = symbol.parent.valueDeclaration;
37588             if (!decl) {
37589                 return undefined;
37590             }
37591             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
37592                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
37593                     undefined;
37594             return initializer || decl;
37595         }
37596         /**
37597          * Get the real symbol of a declaration with an expando initializer.
37598          *
37599          * Normally, declarations have an associated symbol, but when a declaration has an expando
37600          * initializer, the expando's symbol is the one that has all the members merged into it.
37601          */
37602         function getExpandoSymbol(symbol) {
37603             var decl = symbol.valueDeclaration;
37604             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
37605                 return undefined;
37606             }
37607             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
37608             if (init) {
37609                 var initSymbol = getSymbolOfNode(init);
37610                 if (initSymbol) {
37611                     return mergeJSSymbols(initSymbol, symbol);
37612                 }
37613             }
37614         }
37615         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
37616             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
37617         }
37618         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
37619             if (isForAugmentation === void 0) { isForAugmentation = false; }
37620             return ts.isStringLiteralLike(moduleReferenceExpression)
37621                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
37622                 : undefined;
37623         }
37624         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
37625             if (isForAugmentation === void 0) { isForAugmentation = false; }
37626             if (ts.startsWith(moduleReference, "@types/")) {
37627                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
37628                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
37629                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
37630             }
37631             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
37632             if (ambientModule) {
37633                 return ambientModule;
37634             }
37635             var currentSourceFile = ts.getSourceFileOfNode(location);
37636             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
37637             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
37638             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
37639             if (sourceFile) {
37640                 if (sourceFile.symbol) {
37641                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
37642                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
37643                     }
37644                     // merged symbol is module declaration symbol combined with all augmentations
37645                     return getMergedSymbol(sourceFile.symbol);
37646                 }
37647                 if (moduleNotFoundError) {
37648                     // report errors only if it was requested
37649                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
37650                 }
37651                 return undefined;
37652             }
37653             if (patternAmbientModules) {
37654                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
37655                 if (pattern) {
37656                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
37657                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
37658                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
37659                     // from a.foo.
37660                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
37661                     if (augmentation) {
37662                         return getMergedSymbol(augmentation);
37663                     }
37664                     return getMergedSymbol(pattern.symbol);
37665                 }
37666             }
37667             // May be an untyped module. If so, ignore resolutionDiagnostic.
37668             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) {
37669                 if (isForAugmentation) {
37670                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
37671                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
37672                 }
37673                 else {
37674                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
37675                 }
37676                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
37677                 return undefined;
37678             }
37679             if (moduleNotFoundError) {
37680                 // See if this was possibly a projectReference redirect
37681                 if (resolvedModule) {
37682                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
37683                     if (redirect) {
37684                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
37685                         return undefined;
37686                     }
37687                 }
37688                 if (resolutionDiagnostic) {
37689                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
37690                 }
37691                 else {
37692                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
37693                     if (tsExtension) {
37694                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
37695                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
37696                     }
37697                     else if (!compilerOptions.resolveJsonModule &&
37698                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
37699                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
37700                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
37701                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
37702                     }
37703                     else {
37704                         error(errorNode, moduleNotFoundError, moduleReference);
37705                     }
37706                 }
37707             }
37708             return undefined;
37709         }
37710         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
37711             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
37712             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
37713                 ? typesPackageExists(packageId.name)
37714                     ? ts.chainDiagnosticMessages(
37715                     /*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))
37716                     : ts.chainDiagnosticMessages(
37717                     /*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))
37718                 : undefined;
37719             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));
37720         }
37721         function typesPackageExists(packageName) {
37722             return getPackagesSet().has(ts.getTypesPackageName(packageName));
37723         }
37724         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
37725             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
37726                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
37727                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
37728                 return getMergedSymbol(exported) || moduleSymbol;
37729             }
37730             return undefined;
37731         }
37732         function getCommonJsExportEquals(exported, moduleSymbol) {
37733             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
37734                 return exported;
37735             }
37736             var links = getSymbolLinks(exported);
37737             if (links.cjsExportMerged) {
37738                 return links.cjsExportMerged;
37739             }
37740             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
37741             merged.flags = merged.flags | 512 /* ValueModule */;
37742             if (merged.exports === undefined) {
37743                 merged.exports = ts.createSymbolTable();
37744             }
37745             moduleSymbol.exports.forEach(function (s, name) {
37746                 if (name === "export=" /* ExportEquals */)
37747                     return;
37748                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
37749             });
37750             getSymbolLinks(merged).cjsExportMerged = merged;
37751             return links.cjsExportMerged = merged;
37752         }
37753         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
37754         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
37755         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
37756         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
37757             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
37758             if (!dontResolveAlias && symbol) {
37759                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
37760                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
37761                         ? "allowSyntheticDefaultImports"
37762                         : "esModuleInterop";
37763                     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);
37764                     return symbol;
37765                 }
37766                 if (compilerOptions.esModuleInterop) {
37767                     var referenceParent = referencingLocation.parent;
37768                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
37769                         ts.isImportCall(referenceParent)) {
37770                         var type = getTypeOfSymbol(symbol);
37771                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
37772                         if (!sigs || !sigs.length) {
37773                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
37774                         }
37775                         if (sigs && sigs.length) {
37776                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
37777                             // Create a new symbol which has the module's type less the call and construct signatures
37778                             var result = createSymbol(symbol.flags, symbol.escapedName);
37779                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
37780                             result.parent = symbol.parent;
37781                             result.target = symbol;
37782                             result.originatingImport = referenceParent;
37783                             if (symbol.valueDeclaration)
37784                                 result.valueDeclaration = symbol.valueDeclaration;
37785                             if (symbol.constEnumOnlyModule)
37786                                 result.constEnumOnlyModule = true;
37787                             if (symbol.members)
37788                                 result.members = ts.cloneMap(symbol.members);
37789                             if (symbol.exports)
37790                                 result.exports = ts.cloneMap(symbol.exports);
37791                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
37792                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
37793                             return result;
37794                         }
37795                     }
37796                 }
37797             }
37798             return symbol;
37799         }
37800         function hasExportAssignmentSymbol(moduleSymbol) {
37801             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
37802         }
37803         function getExportsOfModuleAsArray(moduleSymbol) {
37804             return symbolsToArray(getExportsOfModule(moduleSymbol));
37805         }
37806         function getExportsAndPropertiesOfModule(moduleSymbol) {
37807             var exports = getExportsOfModuleAsArray(moduleSymbol);
37808             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37809             if (exportEquals !== moduleSymbol) {
37810                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
37811             }
37812             return exports;
37813         }
37814         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
37815             var symbolTable = getExportsOfModule(moduleSymbol);
37816             if (symbolTable) {
37817                 return symbolTable.get(memberName);
37818             }
37819         }
37820         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
37821             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
37822             if (symbol) {
37823                 return symbol;
37824             }
37825             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37826             if (exportEquals === moduleSymbol) {
37827                 return undefined;
37828             }
37829             var type = getTypeOfSymbol(exportEquals);
37830             return type.flags & 131068 /* Primitive */ ||
37831                 ts.getObjectFlags(type) & 1 /* Class */ ||
37832                 isArrayOrTupleLikeType(type)
37833                 ? undefined
37834                 : getPropertyOfType(type, memberName);
37835         }
37836         function getExportsOfSymbol(symbol) {
37837             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
37838                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
37839                     symbol.exports || emptySymbols;
37840         }
37841         function getExportsOfModule(moduleSymbol) {
37842             var links = getSymbolLinks(moduleSymbol);
37843             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
37844         }
37845         /**
37846          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
37847          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
37848          */
37849         function extendExportSymbols(target, source, lookupTable, exportNode) {
37850             if (!source)
37851                 return;
37852             source.forEach(function (sourceSymbol, id) {
37853                 if (id === "default" /* Default */)
37854                     return;
37855                 var targetSymbol = target.get(id);
37856                 if (!targetSymbol) {
37857                     target.set(id, sourceSymbol);
37858                     if (lookupTable && exportNode) {
37859                         lookupTable.set(id, {
37860                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
37861                         });
37862                     }
37863                 }
37864                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
37865                     var collisionTracker = lookupTable.get(id);
37866                     if (!collisionTracker.exportsWithDuplicate) {
37867                         collisionTracker.exportsWithDuplicate = [exportNode];
37868                     }
37869                     else {
37870                         collisionTracker.exportsWithDuplicate.push(exportNode);
37871                     }
37872                 }
37873             });
37874         }
37875         function getExportsOfModuleWorker(moduleSymbol) {
37876             var visitedSymbols = [];
37877             // A module defined by an 'export=' consists of one export that needs to be resolved
37878             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
37879             return visit(moduleSymbol) || emptySymbols;
37880             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
37881             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
37882             function visit(symbol) {
37883                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
37884                     return;
37885                 }
37886                 var symbols = ts.cloneMap(symbol.exports);
37887                 // All export * declarations are collected in an __export symbol by the binder
37888                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
37889                 if (exportStars) {
37890                     var nestedSymbols = ts.createSymbolTable();
37891                     var lookupTable_1 = ts.createMap();
37892                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
37893                         var node = _a[_i];
37894                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
37895                         var exportedSymbols = visit(resolvedModule);
37896                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
37897                     }
37898                     lookupTable_1.forEach(function (_a, id) {
37899                         var exportsWithDuplicate = _a.exportsWithDuplicate;
37900                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
37901                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
37902                             return;
37903                         }
37904                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
37905                             var node = exportsWithDuplicate_1[_i];
37906                             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)));
37907                         }
37908                     });
37909                     extendExportSymbols(symbols, nestedSymbols);
37910                 }
37911                 return symbols;
37912             }
37913         }
37914         function getMergedSymbol(symbol) {
37915             var merged;
37916             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
37917         }
37918         function getSymbolOfNode(node) {
37919             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
37920         }
37921         function getParentOfSymbol(symbol) {
37922             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
37923         }
37924         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
37925             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
37926             var id = "" + getNodeId(containingFile);
37927             var links = getSymbolLinks(symbol);
37928             var results;
37929             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
37930                 return results;
37931             }
37932             if (containingFile && containingFile.imports) {
37933                 // Try to make an import using an import already in the enclosing file, if possible
37934                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
37935                     var importRef = _a[_i];
37936                     if (ts.nodeIsSynthesized(importRef))
37937                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
37938                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
37939                     if (!resolvedModule)
37940                         continue;
37941                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
37942                     if (!ref)
37943                         continue;
37944                     results = ts.append(results, resolvedModule);
37945                 }
37946                 if (ts.length(results)) {
37947                     (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
37948                     return results;
37949                 }
37950             }
37951             if (links.extendedContainers) {
37952                 return links.extendedContainers;
37953             }
37954             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
37955             var otherFiles = host.getSourceFiles();
37956             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
37957                 var file = otherFiles_1[_b];
37958                 if (!ts.isExternalModule(file))
37959                     continue;
37960                 var sym = getSymbolOfNode(file);
37961                 var ref = getAliasForSymbolInContainer(sym, symbol);
37962                 if (!ref)
37963                     continue;
37964                 results = ts.append(results, sym);
37965             }
37966             return links.extendedContainers = results || ts.emptyArray;
37967         }
37968         /**
37969          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
37970          * is just its' `.parent`, but for locals, this value is `undefined`
37971          */
37972         function getContainersOfSymbol(symbol, enclosingDeclaration) {
37973             var container = getParentOfSymbol(symbol);
37974             // Type parameters end up in the `members` lists but are not externally visible
37975             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
37976                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
37977                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
37978                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
37979                     return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
37980                 }
37981                 var res = ts.append(additionalContainers, container);
37982                 return ts.concatenate(res, reexportContainers);
37983             }
37984             var candidates = ts.mapDefined(symbol.declarations, function (d) {
37985                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
37986                     return getSymbolOfNode(d.parent);
37987                 }
37988                 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)) {
37989                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
37990                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
37991                     }
37992                     checkExpressionCached(d.parent.left.expression);
37993                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
37994                 }
37995             });
37996             if (!ts.length(candidates)) {
37997                 return undefined;
37998             }
37999             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
38000             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
38001                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
38002             }
38003         }
38004         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
38005             var fileSymbol = getExternalModuleContainer(d);
38006             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
38007             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
38008         }
38009         function getAliasForSymbolInContainer(container, symbol) {
38010             if (container === getParentOfSymbol(symbol)) {
38011                 // fast path, `symbol` is either already the alias or isn't aliased
38012                 return symbol;
38013             }
38014             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
38015             // the container itself as the alias for the symbol
38016             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
38017             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
38018                 return container;
38019             }
38020             var exports = getExportsOfSymbol(container);
38021             var quick = exports.get(symbol.escapedName);
38022             if (quick && getSymbolIfSameReference(quick, symbol)) {
38023                 return quick;
38024             }
38025             return ts.forEachEntry(exports, function (exported) {
38026                 if (getSymbolIfSameReference(exported, symbol)) {
38027                     return exported;
38028                 }
38029             });
38030         }
38031         /**
38032          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
38033          */
38034         function getSymbolIfSameReference(s1, s2) {
38035             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
38036                 return s1;
38037             }
38038         }
38039         function getExportSymbolOfValueSymbolIfExported(symbol) {
38040             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
38041         }
38042         function symbolIsValue(symbol) {
38043             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
38044         }
38045         function findConstructorDeclaration(node) {
38046             var members = node.members;
38047             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
38048                 var member = members_3[_i];
38049                 if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
38050                     return member;
38051                 }
38052             }
38053         }
38054         function createType(flags) {
38055             var result = new Type(checker, flags);
38056             typeCount++;
38057             result.id = typeCount;
38058             return result;
38059         }
38060         function createIntrinsicType(kind, intrinsicName, objectFlags) {
38061             if (objectFlags === void 0) { objectFlags = 0; }
38062             var type = createType(kind);
38063             type.intrinsicName = intrinsicName;
38064             type.objectFlags = objectFlags;
38065             return type;
38066         }
38067         function createBooleanType(trueFalseTypes) {
38068             var type = getUnionType(trueFalseTypes);
38069             type.flags |= 16 /* Boolean */;
38070             type.intrinsicName = "boolean";
38071             return type;
38072         }
38073         function createObjectType(objectFlags, symbol) {
38074             var type = createType(524288 /* Object */);
38075             type.objectFlags = objectFlags;
38076             type.symbol = symbol;
38077             type.members = undefined;
38078             type.properties = undefined;
38079             type.callSignatures = undefined;
38080             type.constructSignatures = undefined;
38081             type.stringIndexInfo = undefined;
38082             type.numberIndexInfo = undefined;
38083             return type;
38084         }
38085         function createTypeofType() {
38086             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
38087         }
38088         function createTypeParameter(symbol) {
38089             var type = createType(262144 /* TypeParameter */);
38090             if (symbol)
38091                 type.symbol = symbol;
38092             return type;
38093         }
38094         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
38095         // @, or #. A third underscore indicates an escaped form of an identifier that started
38096         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
38097         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
38098         function isReservedMemberName(name) {
38099             return name.charCodeAt(0) === 95 /* _ */ &&
38100                 name.charCodeAt(1) === 95 /* _ */ &&
38101                 name.charCodeAt(2) !== 95 /* _ */ &&
38102                 name.charCodeAt(2) !== 64 /* at */ &&
38103                 name.charCodeAt(2) !== 35 /* hash */;
38104         }
38105         function getNamedMembers(members) {
38106             var result;
38107             members.forEach(function (symbol, id) {
38108                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
38109                     (result || (result = [])).push(symbol);
38110                 }
38111             });
38112             return result || ts.emptyArray;
38113         }
38114         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
38115             type.members = members;
38116             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
38117             type.callSignatures = callSignatures;
38118             type.constructSignatures = constructSignatures;
38119             type.stringIndexInfo = stringIndexInfo;
38120             type.numberIndexInfo = numberIndexInfo;
38121             return type;
38122         }
38123         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
38124             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
38125         }
38126         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
38127             var result;
38128             var _loop_7 = function (location) {
38129                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
38130                 if (location.locals && !isGlobalSourceFile(location)) {
38131                     if (result = callback(location.locals)) {
38132                         return { value: result };
38133                     }
38134                 }
38135                 switch (location.kind) {
38136                     case 290 /* SourceFile */:
38137                         if (!ts.isExternalOrCommonJsModule(location)) {
38138                             break;
38139                         }
38140                     // falls through
38141                     case 249 /* ModuleDeclaration */:
38142                         var sym = getSymbolOfNode(location);
38143                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
38144                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
38145                         // to one another anyway)
38146                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
38147                             return { value: result };
38148                         }
38149                         break;
38150                     case 245 /* ClassDeclaration */:
38151                     case 214 /* ClassExpression */:
38152                     case 246 /* InterfaceDeclaration */:
38153                         // Type parameters are bound into `members` lists so they can merge across declarations
38154                         // This is troublesome, since in all other respects, they behave like locals :cries:
38155                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
38156                         // lookup logic in terms of `resolveName` would be nice
38157                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
38158                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
38159                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
38160                         var table_1;
38161                         // TODO: Should this filtered table be cached in some way?
38162                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
38163                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
38164                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
38165                             }
38166                         });
38167                         if (table_1 && (result = callback(table_1))) {
38168                             return { value: result };
38169                         }
38170                         break;
38171                 }
38172             };
38173             for (var location = enclosingDeclaration; location; location = location.parent) {
38174                 var state_2 = _loop_7(location);
38175                 if (typeof state_2 === "object")
38176                     return state_2.value;
38177             }
38178             return callback(globals);
38179         }
38180         function getQualifiedLeftMeaning(rightMeaning) {
38181             // If we are looking in value space, the parent meaning is value, other wise it is namespace
38182             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
38183         }
38184         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
38185             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
38186             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
38187                 return undefined;
38188             }
38189             var id = "" + getSymbolId(symbol);
38190             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
38191             if (!visitedSymbolTables) {
38192                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
38193             }
38194             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
38195             /**
38196              * @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)
38197              */
38198             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
38199                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
38200                     return undefined;
38201                 }
38202                 var result = trySymbolTable(symbols, ignoreQualification);
38203                 visitedSymbolTables.pop();
38204                 return result;
38205             }
38206             function canQualifySymbol(symbolFromSymbolTable, meaning) {
38207                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
38208                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
38209                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
38210                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
38211             }
38212             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
38213                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
38214                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
38215                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
38216                     // check the symbol can be qualified, it is only then this symbol is accessible
38217                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
38218                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
38219             }
38220             function trySymbolTable(symbols, ignoreQualification) {
38221                 // If symbol is directly available by its name in the symbol table
38222                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
38223                     return [symbol];
38224                 }
38225                 // Check if symbol is any of the aliases in scope
38226                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
38227                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
38228                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
38229                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
38230                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
38231                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
38232                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
38233                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
38234                         // See similar comment in `resolveName` for details
38235                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
38236                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
38237                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
38238                         if (candidate) {
38239                             return candidate;
38240                         }
38241                     }
38242                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
38243                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
38244                             return [symbol];
38245                         }
38246                     }
38247                 });
38248                 // 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
38249                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
38250             }
38251             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
38252                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
38253                     return [symbolFromSymbolTable];
38254                 }
38255                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
38256                 // but only if the symbolFromSymbolTable can be qualified
38257                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
38258                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
38259                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
38260                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
38261                 }
38262             }
38263         }
38264         function needsQualification(symbol, enclosingDeclaration, meaning) {
38265             var qualify = false;
38266             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
38267                 // If symbol of this name is not available in the symbol table we are ok
38268                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
38269                 if (!symbolFromSymbolTable) {
38270                     // Continue to the next symbol table
38271                     return false;
38272                 }
38273                 // If the symbol with this name is present it should refer to the symbol
38274                 if (symbolFromSymbolTable === symbol) {
38275                     // No need to qualify
38276                     return true;
38277                 }
38278                 // Qualify if the symbol from symbol table has same meaning as expected
38279                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
38280                 if (symbolFromSymbolTable.flags & meaning) {
38281                     qualify = true;
38282                     return true;
38283                 }
38284                 // Continue to the next symbol table
38285                 return false;
38286             });
38287             return qualify;
38288         }
38289         function isPropertyOrMethodDeclarationSymbol(symbol) {
38290             if (symbol.declarations && symbol.declarations.length) {
38291                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
38292                     var declaration = _a[_i];
38293                     switch (declaration.kind) {
38294                         case 159 /* PropertyDeclaration */:
38295                         case 161 /* MethodDeclaration */:
38296                         case 163 /* GetAccessor */:
38297                         case 164 /* SetAccessor */:
38298                             continue;
38299                         default:
38300                             return false;
38301                     }
38302                 }
38303                 return true;
38304             }
38305             return false;
38306         }
38307         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
38308             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
38309             return access.accessibility === 0 /* Accessible */;
38310         }
38311         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
38312             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
38313             return access.accessibility === 0 /* Accessible */;
38314         }
38315         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
38316             if (!ts.length(symbols))
38317                 return;
38318             var hadAccessibleChain;
38319             var earlyModuleBail = false;
38320             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
38321                 var symbol = _a[_i];
38322                 // Symbol is accessible if it by itself is accessible
38323                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
38324                 if (accessibleSymbolChain) {
38325                     hadAccessibleChain = symbol;
38326                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
38327                     if (hasAccessibleDeclarations) {
38328                         return hasAccessibleDeclarations;
38329                     }
38330                 }
38331                 else {
38332                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
38333                         if (shouldComputeAliasesToMakeVisible) {
38334                             earlyModuleBail = true;
38335                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
38336                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
38337                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
38338                             // all other visibility options (in order to capture the possible aliases used to reference the module)
38339                             continue;
38340                         }
38341                         // Any meaning of a module symbol is always accessible via an `import` type
38342                         return {
38343                             accessibility: 0 /* Accessible */
38344                         };
38345                     }
38346                 }
38347                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
38348                 // It could be a qualified symbol and hence verify the path
38349                 // e.g.:
38350                 // module m {
38351                 //     export class c {
38352                 //     }
38353                 // }
38354                 // const x: typeof m.c
38355                 // In the above example when we start with checking if typeof m.c symbol is accessible,
38356                 // we are going to see if c can be accessed in scope directly.
38357                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
38358                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
38359                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
38360                 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
38361                 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
38362                 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
38363                 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
38364                 if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
38365                     if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
38366                         containers = [getSymbolOfNode(firstDecl.parent)];
38367                     }
38368                 }
38369                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
38370                 if (parentResult) {
38371                     return parentResult;
38372                 }
38373             }
38374             if (earlyModuleBail) {
38375                 return {
38376                     accessibility: 0 /* Accessible */
38377                 };
38378             }
38379             if (hadAccessibleChain) {
38380                 return {
38381                     accessibility: 1 /* NotAccessible */,
38382                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
38383                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
38384                 };
38385             }
38386         }
38387         /**
38388          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
38389          *
38390          * @param symbol a Symbol to check if accessible
38391          * @param enclosingDeclaration a Node containing reference to the symbol
38392          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
38393          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
38394          */
38395         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
38396             if (symbol && enclosingDeclaration) {
38397                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
38398                 if (result) {
38399                     return result;
38400                 }
38401                 // This could be a symbol that is not exported in the external module
38402                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
38403                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
38404                 if (symbolExternalModule) {
38405                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
38406                     if (symbolExternalModule !== enclosingExternalModule) {
38407                         // name from different external module that is not visible
38408                         return {
38409                             accessibility: 2 /* CannotBeNamed */,
38410                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38411                             errorModuleName: symbolToString(symbolExternalModule)
38412                         };
38413                     }
38414                 }
38415                 // Just a local name that is not accessible
38416                 return {
38417                     accessibility: 1 /* NotAccessible */,
38418                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38419                 };
38420             }
38421             return { accessibility: 0 /* Accessible */ };
38422         }
38423         function getExternalModuleContainer(declaration) {
38424             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
38425             return node && getSymbolOfNode(node);
38426         }
38427         function hasExternalModuleSymbol(declaration) {
38428             return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38429         }
38430         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
38431             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38432         }
38433         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
38434             var aliasesToMakeVisible;
38435             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
38436                 return undefined;
38437             }
38438             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
38439             function getIsDeclarationVisible(declaration) {
38440                 if (!isDeclarationVisible(declaration)) {
38441                     // Mark the unexported alias as visible if its parent is visible
38442                     // because these kind of aliases can be used to name types in declaration file
38443                     var anyImportSyntax = getAnyImportSyntax(declaration);
38444                     if (anyImportSyntax &&
38445                         !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
38446                         isDeclarationVisible(anyImportSyntax.parent)) {
38447                         return addVisibleAlias(declaration, anyImportSyntax);
38448                     }
38449                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
38450                         !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
38451                         isDeclarationVisible(declaration.parent.parent.parent)) {
38452                         return addVisibleAlias(declaration, declaration.parent.parent);
38453                     }
38454                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
38455                         && !ts.hasModifier(declaration, 1 /* Export */)
38456                         && isDeclarationVisible(declaration.parent)) {
38457                         return addVisibleAlias(declaration, declaration);
38458                     }
38459                     // Declaration is not visible
38460                     return false;
38461                 }
38462                 return true;
38463             }
38464             function addVisibleAlias(declaration, aliasingStatement) {
38465                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
38466                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
38467                 // since we will do the emitting later in trackSymbol.
38468                 if (shouldComputeAliasToMakeVisible) {
38469                     getNodeLinks(declaration).isVisible = true;
38470                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
38471                 }
38472                 return true;
38473             }
38474         }
38475         function isEntityNameVisible(entityName, enclosingDeclaration) {
38476             // get symbol of the first identifier of the entityName
38477             var meaning;
38478             if (entityName.parent.kind === 172 /* TypeQuery */ ||
38479                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
38480                 entityName.parent.kind === 154 /* ComputedPropertyName */) {
38481                 // Typeof value
38482                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
38483             }
38484             else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
38485                 entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
38486                 // Left identifier from type reference or TypeAlias
38487                 // Entity name of the import declaration
38488                 meaning = 1920 /* Namespace */;
38489             }
38490             else {
38491                 // Type Reference or TypeAlias entity = Identifier
38492                 meaning = 788968 /* Type */;
38493             }
38494             var firstIdentifier = ts.getFirstIdentifier(entityName);
38495             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
38496             // Verify if the symbol is accessible
38497             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
38498                 accessibility: 1 /* NotAccessible */,
38499                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
38500                 errorNode: firstIdentifier
38501             };
38502         }
38503         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
38504             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
38505             var nodeFlags = 70221824 /* IgnoreErrors */;
38506             if (flags & 2 /* UseOnlyExternalAliasing */) {
38507                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
38508             }
38509             if (flags & 1 /* WriteTypeParametersOrArguments */) {
38510                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
38511             }
38512             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
38513                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
38514             }
38515             if (flags & 16 /* DoNotIncludeSymbolChain */) {
38516                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
38517             }
38518             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
38519             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
38520             function symbolToStringWorker(writer) {
38521                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
38522                 var printer = ts.createPrinter({ removeComments: true });
38523                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38524                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
38525                 return writer;
38526             }
38527         }
38528         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
38529             if (flags === void 0) { flags = 0 /* None */; }
38530             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
38531             function signatureToStringWorker(writer) {
38532                 var sigOutput;
38533                 if (flags & 262144 /* WriteArrowStyleSignature */) {
38534                     sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
38535                 }
38536                 else {
38537                     sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
38538                 }
38539                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
38540                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
38541                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38542                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
38543                 return writer;
38544             }
38545         }
38546         function typeToString(type, enclosingDeclaration, flags, writer) {
38547             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
38548             if (writer === void 0) { writer = ts.createTextWriter(""); }
38549             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
38550             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
38551             if (typeNode === undefined)
38552                 return ts.Debug.fail("should always get typenode");
38553             var options = { removeComments: true };
38554             var printer = ts.createPrinter(options);
38555             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38556             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
38557             var result = writer.getText();
38558             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
38559             if (maxLength && result && result.length >= maxLength) {
38560                 return result.substr(0, maxLength - "...".length) + "...";
38561             }
38562             return result;
38563         }
38564         function getTypeNamesForErrorDisplay(left, right) {
38565             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
38566             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
38567             if (leftStr === rightStr) {
38568                 leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38569                 rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38570             }
38571             return [leftStr, rightStr];
38572         }
38573         function symbolValueDeclarationIsContextSensitive(symbol) {
38574             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
38575         }
38576         function toNodeBuilderFlags(flags) {
38577             if (flags === void 0) { flags = 0 /* None */; }
38578             return flags & 814775659 /* NodeBuilderFlagsMask */;
38579         }
38580         function createNodeBuilder() {
38581             return {
38582                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
38583                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
38584                 },
38585                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
38586                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
38587                 },
38588                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
38589                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
38590                 },
38591                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38592                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
38593                 },
38594                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38595                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
38596                 },
38597                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
38598                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
38599                 },
38600                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
38601                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
38602                 },
38603                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
38604                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
38605                 },
38606                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
38607                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
38608                 },
38609             };
38610             function withContext(enclosingDeclaration, flags, tracker, cb) {
38611                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
38612                 var context = {
38613                     enclosingDeclaration: enclosingDeclaration,
38614                     flags: flags || 0 /* None */,
38615                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
38616                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
38617                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
38618                             getSourceFiles: function () { return host.getSourceFiles(); },
38619                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
38620                             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
38621                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
38622                             redirectTargetsMap: host.redirectTargetsMap,
38623                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
38624                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
38625                             fileExists: function (fileName) { return host.fileExists(fileName); },
38626                         } : undefined },
38627                     encounteredError: false,
38628                     visitedTypes: undefined,
38629                     symbolDepth: undefined,
38630                     inferTypeParameters: undefined,
38631                     approximateLength: 0
38632                 };
38633                 var resultingNode = cb(context);
38634                 return context.encounteredError ? undefined : resultingNode;
38635             }
38636             function checkTruncationLength(context) {
38637                 if (context.truncating)
38638                     return context.truncating;
38639                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
38640             }
38641             function typeToTypeNodeHelper(type, context) {
38642                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
38643                     cancellationToken.throwIfCancellationRequested();
38644                 }
38645                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
38646                 context.flags &= ~8388608 /* InTypeAlias */;
38647                 if (!type) {
38648                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38649                         context.encounteredError = true;
38650                         return undefined; // TODO: GH#18217
38651                     }
38652                     context.approximateLength += 3;
38653                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38654                 }
38655                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
38656                     type = getReducedType(type);
38657                 }
38658                 if (type.flags & 1 /* Any */) {
38659                     context.approximateLength += 3;
38660                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38661                 }
38662                 if (type.flags & 2 /* Unknown */) {
38663                     return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
38664                 }
38665                 if (type.flags & 4 /* String */) {
38666                     context.approximateLength += 6;
38667                     return ts.createKeywordTypeNode(143 /* StringKeyword */);
38668                 }
38669                 if (type.flags & 8 /* Number */) {
38670                     context.approximateLength += 6;
38671                     return ts.createKeywordTypeNode(140 /* NumberKeyword */);
38672                 }
38673                 if (type.flags & 64 /* BigInt */) {
38674                     context.approximateLength += 6;
38675                     return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
38676                 }
38677                 if (type.flags & 16 /* Boolean */) {
38678                     context.approximateLength += 7;
38679                     return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
38680                 }
38681                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
38682                     var parentSymbol = getParentOfSymbol(type.symbol);
38683                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
38684                     var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
38685                         ? parentName
38686                         : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
38687                     return enumLiteralName;
38688                 }
38689                 if (type.flags & 1056 /* EnumLike */) {
38690                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
38691                 }
38692                 if (type.flags & 128 /* StringLiteral */) {
38693                     context.approximateLength += (type.value.length + 2);
38694                     return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
38695                 }
38696                 if (type.flags & 256 /* NumberLiteral */) {
38697                     var value = type.value;
38698                     context.approximateLength += ("" + value).length;
38699                     return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
38700                 }
38701                 if (type.flags & 2048 /* BigIntLiteral */) {
38702                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
38703                     return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
38704                 }
38705                 if (type.flags & 512 /* BooleanLiteral */) {
38706                     context.approximateLength += type.intrinsicName.length;
38707                     return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
38708                 }
38709                 if (type.flags & 8192 /* UniqueESSymbol */) {
38710                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
38711                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38712                             context.approximateLength += 6;
38713                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
38714                         }
38715                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
38716                             context.tracker.reportInaccessibleUniqueSymbolError();
38717                         }
38718                     }
38719                     context.approximateLength += 13;
38720                     return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
38721                 }
38722                 if (type.flags & 16384 /* Void */) {
38723                     context.approximateLength += 4;
38724                     return ts.createKeywordTypeNode(110 /* VoidKeyword */);
38725                 }
38726                 if (type.flags & 32768 /* Undefined */) {
38727                     context.approximateLength += 9;
38728                     return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
38729                 }
38730                 if (type.flags & 65536 /* Null */) {
38731                     context.approximateLength += 4;
38732                     return ts.createKeywordTypeNode(100 /* NullKeyword */);
38733                 }
38734                 if (type.flags & 131072 /* Never */) {
38735                     context.approximateLength += 5;
38736                     return ts.createKeywordTypeNode(137 /* NeverKeyword */);
38737                 }
38738                 if (type.flags & 4096 /* ESSymbol */) {
38739                     context.approximateLength += 6;
38740                     return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
38741                 }
38742                 if (type.flags & 67108864 /* NonPrimitive */) {
38743                     context.approximateLength += 6;
38744                     return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
38745                 }
38746                 if (isThisTypeParameter(type)) {
38747                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
38748                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
38749                             context.encounteredError = true;
38750                         }
38751                         if (context.tracker.reportInaccessibleThisError) {
38752                             context.tracker.reportInaccessibleThisError();
38753                         }
38754                     }
38755                     context.approximateLength += 4;
38756                     return ts.createThis();
38757                 }
38758                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
38759                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
38760                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
38761                         return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
38762                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
38763                 }
38764                 var objectFlags = ts.getObjectFlags(type);
38765                 if (objectFlags & 4 /* Reference */) {
38766                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38767                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
38768                 }
38769                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
38770                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
38771                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
38772                         return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
38773                     }
38774                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
38775                         type.flags & 262144 /* TypeParameter */ &&
38776                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38777                         var name = typeParameterToName(type, context);
38778                         context.approximateLength += ts.idText(name).length;
38779                         return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
38780                     }
38781                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
38782                     return type.symbol
38783                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
38784                         : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
38785                 }
38786                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
38787                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
38788                     if (ts.length(types) === 1) {
38789                         return typeToTypeNodeHelper(types[0], context);
38790                     }
38791                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
38792                     if (typeNodes && typeNodes.length > 0) {
38793                         var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
38794                         return unionOrIntersectionTypeNode;
38795                     }
38796                     else {
38797                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38798                             context.encounteredError = true;
38799                         }
38800                         return undefined; // TODO: GH#18217
38801                     }
38802                 }
38803                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
38804                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38805                     // The type is an object literal type.
38806                     return createAnonymousTypeNode(type);
38807                 }
38808                 if (type.flags & 4194304 /* Index */) {
38809                     var indexedType = type.type;
38810                     context.approximateLength += 6;
38811                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
38812                     return ts.createTypeOperatorNode(indexTypeNode);
38813                 }
38814                 if (type.flags & 8388608 /* IndexedAccess */) {
38815                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
38816                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
38817                     context.approximateLength += 2;
38818                     return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
38819                 }
38820                 if (type.flags & 16777216 /* Conditional */) {
38821                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
38822                     var saveInferTypeParameters = context.inferTypeParameters;
38823                     context.inferTypeParameters = type.root.inferTypeParameters;
38824                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
38825                     context.inferTypeParameters = saveInferTypeParameters;
38826                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
38827                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
38828                     context.approximateLength += 15;
38829                     return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
38830                 }
38831                 if (type.flags & 33554432 /* Substitution */) {
38832                     return typeToTypeNodeHelper(type.baseType, context);
38833                 }
38834                 return ts.Debug.fail("Should be unreachable.");
38835                 function typeToTypeNodeOrCircularityElision(type) {
38836                     var _a, _b;
38837                     if (type.flags & 1048576 /* Union */) {
38838                         if (context.visitedTypes && context.visitedTypes.has("" + getTypeId(type))) {
38839                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
38840                                 context.encounteredError = true;
38841                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportCyclicStructureError) === null || _b === void 0 ? void 0 : _b.call(_a);
38842                             }
38843                             return createElidedInformationPlaceholder(context);
38844                         }
38845                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
38846                     }
38847                     return typeToTypeNodeHelper(type, context);
38848                 }
38849                 function createMappedTypeNodeFromType(type) {
38850                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38851                     var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
38852                     var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
38853                     var appropriateConstraintTypeNode;
38854                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
38855                         // We have a { [P in keyof T]: X }
38856                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
38857                         appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
38858                     }
38859                     else {
38860                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
38861                     }
38862                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
38863                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
38864                     var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
38865                     context.approximateLength += 10;
38866                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
38867                 }
38868                 function createAnonymousTypeNode(type) {
38869                     var typeId = "" + type.id;
38870                     var symbol = type.symbol;
38871                     if (symbol) {
38872                         if (isJSConstructor(symbol.valueDeclaration)) {
38873                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
38874                             var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
38875                             return symbolToTypeNode(symbol, context, isInstanceType);
38876                         }
38877                         // Always use 'typeof T' for type of class, enum, and module objects
38878                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
38879                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
38880                             shouldWriteTypeOfFunctionSymbol()) {
38881                             return symbolToTypeNode(symbol, context, 111551 /* Value */);
38882                         }
38883                         else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
38884                             // If type is an anonymous type literal in a type alias declaration, use type alias name
38885                             var typeAlias = getTypeAliasForTypeLiteral(type);
38886                             if (typeAlias) {
38887                                 // The specified symbol flags need to be reinterpreted as type flags
38888                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
38889                             }
38890                             else {
38891                                 return createElidedInformationPlaceholder(context);
38892                             }
38893                         }
38894                         else {
38895                             return visitAndTransformType(type, createTypeNodeFromObjectType);
38896                         }
38897                     }
38898                     else {
38899                         // Anonymous types without a symbol are never circular.
38900                         return createTypeNodeFromObjectType(type);
38901                     }
38902                     function shouldWriteTypeOfFunctionSymbol() {
38903                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
38904                             ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
38905                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
38906                             (symbol.parent || // is exported function symbol
38907                                 ts.forEach(symbol.declarations, function (declaration) {
38908                                     return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
38909                                 }));
38910                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
38911                             // typeof is allowed only for static/non local functions
38912                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
38913                                 (!(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
38914                         }
38915                     }
38916                 }
38917                 function visitAndTransformType(type, transform) {
38918                     var typeId = "" + type.id;
38919                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
38920                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
38921                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
38922                             undefined;
38923                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
38924                     // of types allows us to catch circular references to instantiations of the same anonymous type
38925                     if (!context.visitedTypes) {
38926                         context.visitedTypes = ts.createMap();
38927                     }
38928                     if (id && !context.symbolDepth) {
38929                         context.symbolDepth = ts.createMap();
38930                     }
38931                     var depth;
38932                     if (id) {
38933                         depth = context.symbolDepth.get(id) || 0;
38934                         if (depth > 10) {
38935                             return createElidedInformationPlaceholder(context);
38936                         }
38937                         context.symbolDepth.set(id, depth + 1);
38938                     }
38939                     context.visitedTypes.set(typeId, true);
38940                     var result = transform(type);
38941                     context.visitedTypes.delete(typeId);
38942                     if (id) {
38943                         context.symbolDepth.set(id, depth);
38944                     }
38945                     return result;
38946                 }
38947                 function createTypeNodeFromObjectType(type) {
38948                     if (isGenericMappedType(type)) {
38949                         return createMappedTypeNodeFromType(type);
38950                     }
38951                     var resolved = resolveStructuredTypeMembers(type);
38952                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
38953                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
38954                             context.approximateLength += 2;
38955                             return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
38956                         }
38957                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
38958                             var signature = resolved.callSignatures[0];
38959                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
38960                             return signatureNode;
38961                         }
38962                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
38963                             var signature = resolved.constructSignatures[0];
38964                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
38965                             return signatureNode;
38966                         }
38967                     }
38968                     var savedFlags = context.flags;
38969                     context.flags |= 4194304 /* InObjectTypeLiteral */;
38970                     var members = createTypeNodesFromResolvedType(resolved);
38971                     context.flags = savedFlags;
38972                     var typeLiteralNode = ts.createTypeLiteralNode(members);
38973                     context.approximateLength += 2;
38974                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
38975                 }
38976                 function typeReferenceToTypeNode(type) {
38977                     var typeArguments = getTypeArguments(type);
38978                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
38979                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
38980                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
38981                             return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
38982                         }
38983                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
38984                         var arrayType = ts.createArrayTypeNode(elementType);
38985                         return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
38986                     }
38987                     else if (type.target.objectFlags & 8 /* Tuple */) {
38988                         if (typeArguments.length > 0) {
38989                             var arity = getTypeReferenceArity(type);
38990                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
38991                             var hasRestElement = type.target.hasRestElement;
38992                             if (tupleConstituentNodes) {
38993                                 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
38994                                     tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
38995                                         ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
38996                                         ts.createOptionalTypeNode(tupleConstituentNodes[i]);
38997                                 }
38998                                 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
38999                                 return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
39000                             }
39001                         }
39002                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
39003                             var tupleTypeNode = ts.createTupleTypeNode([]);
39004                             return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
39005                         }
39006                         context.encounteredError = true;
39007                         return undefined; // TODO: GH#18217
39008                     }
39009                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
39010                         type.symbol.valueDeclaration &&
39011                         ts.isClassLike(type.symbol.valueDeclaration) &&
39012                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
39013                         return createAnonymousTypeNode(type);
39014                     }
39015                     else {
39016                         var outerTypeParameters = type.target.outerTypeParameters;
39017                         var i = 0;
39018                         var resultType = void 0;
39019                         if (outerTypeParameters) {
39020                             var length_2 = outerTypeParameters.length;
39021                             while (i < length_2) {
39022                                 // Find group of type arguments for type parameters with the same declaring container.
39023                                 var start = i;
39024                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
39025                                 do {
39026                                     i++;
39027                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
39028                                 // When type parameters are their own type arguments for the whole group (i.e. we have
39029                                 // the default outer type arguments), we don't show the group.
39030                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
39031                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
39032                                     var flags_2 = context.flags;
39033                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
39034                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
39035                                     context.flags = flags_2;
39036                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
39037                                 }
39038                             }
39039                         }
39040                         var typeArgumentNodes = void 0;
39041                         if (typeArguments.length > 0) {
39042                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
39043                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
39044                         }
39045                         var flags = context.flags;
39046                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
39047                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
39048                         context.flags = flags;
39049                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
39050                     }
39051                 }
39052                 function appendReferenceToType(root, ref) {
39053                     if (ts.isImportTypeNode(root)) {
39054                         // first shift type arguments
39055                         var innerParams = root.typeArguments;
39056                         if (root.qualifier) {
39057                             (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
39058                         }
39059                         root.typeArguments = ref.typeArguments;
39060                         // then move qualifiers
39061                         var ids = getAccessStack(ref);
39062                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
39063                             var id = ids_1[_i];
39064                             root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
39065                         }
39066                         return root;
39067                     }
39068                     else {
39069                         // first shift type arguments
39070                         var innerParams = root.typeArguments;
39071                         (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
39072                         root.typeArguments = ref.typeArguments;
39073                         // then move qualifiers
39074                         var ids = getAccessStack(ref);
39075                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
39076                             var id = ids_2[_a];
39077                             root.typeName = ts.createQualifiedName(root.typeName, id);
39078                         }
39079                         return root;
39080                     }
39081                 }
39082                 function getAccessStack(ref) {
39083                     var state = ref.typeName;
39084                     var ids = [];
39085                     while (!ts.isIdentifier(state)) {
39086                         ids.unshift(state.right);
39087                         state = state.left;
39088                     }
39089                     ids.unshift(state);
39090                     return ids;
39091                 }
39092                 function createTypeNodesFromResolvedType(resolvedType) {
39093                     if (checkTruncationLength(context)) {
39094                         return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
39095                     }
39096                     var typeElements = [];
39097                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
39098                         var signature = _a[_i];
39099                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
39100                     }
39101                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
39102                         var signature = _c[_b];
39103                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
39104                     }
39105                     if (resolvedType.stringIndexInfo) {
39106                         var indexSignature = void 0;
39107                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
39108                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
39109                             indexSignature.type = createElidedInformationPlaceholder(context);
39110                         }
39111                         else {
39112                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
39113                         }
39114                         typeElements.push(indexSignature);
39115                     }
39116                     if (resolvedType.numberIndexInfo) {
39117                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
39118                     }
39119                     var properties = resolvedType.properties;
39120                     if (!properties) {
39121                         return typeElements;
39122                     }
39123                     var i = 0;
39124                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
39125                         var propertySymbol = properties_1[_d];
39126                         i++;
39127                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
39128                             if (propertySymbol.flags & 4194304 /* Prototype */) {
39129                                 continue;
39130                             }
39131                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
39132                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
39133                             }
39134                         }
39135                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
39136                             typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
39137                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
39138                             break;
39139                         }
39140                         addPropertyToElementList(propertySymbol, context, typeElements);
39141                     }
39142                     return typeElements.length ? typeElements : undefined;
39143                 }
39144             }
39145             function createElidedInformationPlaceholder(context) {
39146                 context.approximateLength += 3;
39147                 if (!(context.flags & 1 /* NoTruncation */)) {
39148                     return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
39149                 }
39150                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39151             }
39152             function addPropertyToElementList(propertySymbol, context, typeElements) {
39153                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
39154                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
39155                     anyType : getTypeOfSymbol(propertySymbol);
39156                 var saveEnclosingDeclaration = context.enclosingDeclaration;
39157                 context.enclosingDeclaration = undefined;
39158                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
39159                     var decl = ts.first(propertySymbol.declarations);
39160                     if (hasLateBindableName(decl)) {
39161                         if (ts.isBinaryExpression(decl)) {
39162                             var name = ts.getNameOfDeclaration(decl);
39163                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
39164                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
39165                             }
39166                         }
39167                         else {
39168                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
39169                         }
39170                     }
39171                 }
39172                 context.enclosingDeclaration = saveEnclosingDeclaration;
39173                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
39174                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
39175                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
39176                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
39177                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
39178                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
39179                         var signature = signatures_1[_i];
39180                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
39181                         methodDeclaration.name = propertyName;
39182                         methodDeclaration.questionToken = optionalToken;
39183                         typeElements.push(preserveCommentsOn(methodDeclaration));
39184                     }
39185                 }
39186                 else {
39187                     var savedFlags = context.flags;
39188                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
39189                     var propertyTypeNode = void 0;
39190                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
39191                         propertyTypeNode = createElidedInformationPlaceholder(context);
39192                     }
39193                     else {
39194                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
39195                     }
39196                     context.flags = savedFlags;
39197                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
39198                     if (modifiers) {
39199                         context.approximateLength += 9;
39200                     }
39201                     var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
39202                     /*initializer*/ undefined);
39203                     typeElements.push(preserveCommentsOn(propertySignature));
39204                 }
39205                 function preserveCommentsOn(node) {
39206                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) {
39207                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; });
39208                         var commentText = d.comment;
39209                         if (commentText) {
39210                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
39211                         }
39212                     }
39213                     else if (propertySymbol.valueDeclaration) {
39214                         // Copy comments to node for declaration emit
39215                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
39216                     }
39217                     return node;
39218                 }
39219             }
39220             function mapToTypeNodes(types, context, isBareList) {
39221                 if (ts.some(types)) {
39222                     if (checkTruncationLength(context)) {
39223                         if (!isBareList) {
39224                             return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
39225                         }
39226                         else if (types.length > 2) {
39227                             return [
39228                                 typeToTypeNodeHelper(types[0], context),
39229                                 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
39230                                 typeToTypeNodeHelper(types[types.length - 1], context)
39231                             ];
39232                         }
39233                     }
39234                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
39235                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
39236                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
39237                     var result_3 = [];
39238                     var i = 0;
39239                     for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
39240                         var type = types_1[_i];
39241                         i++;
39242                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
39243                             result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
39244                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
39245                             if (typeNode_1) {
39246                                 result_3.push(typeNode_1);
39247                             }
39248                             break;
39249                         }
39250                         context.approximateLength += 2; // Account for whitespace + separator
39251                         var typeNode = typeToTypeNodeHelper(type, context);
39252                         if (typeNode) {
39253                             result_3.push(typeNode);
39254                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
39255                                 seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]);
39256                             }
39257                         }
39258                     }
39259                     if (seenNames) {
39260                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
39261                         // occurrences of the same name actually come from different
39262                         // namespaces, go through the single-identifier type reference nodes
39263                         // we just generated, and see if any names were generated more than
39264                         // once while referring to different types. If so, regenerate the
39265                         // type node for each entry by that name with the
39266                         // `UseFullyQualifiedType` flag enabled.
39267                         var saveContextFlags = context.flags;
39268                         context.flags |= 64 /* UseFullyQualifiedType */;
39269                         seenNames.forEach(function (types) {
39270                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
39271                                 var a = _a[0];
39272                                 var b = _b[0];
39273                                 return typesAreSameReference(a, b);
39274                             })) {
39275                                 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
39276                                     var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
39277                                     result_3[resultIndex] = typeToTypeNodeHelper(type, context);
39278                                 }
39279                             }
39280                         });
39281                         context.flags = saveContextFlags;
39282                     }
39283                     return result_3;
39284                 }
39285             }
39286             function typesAreSameReference(a, b) {
39287                 return a === b
39288                     || !!a.symbol && a.symbol === b.symbol
39289                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
39290             }
39291             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
39292                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
39293                 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
39294                 var indexingParameter = ts.createParameter(
39295                 /*decorators*/ undefined, 
39296                 /*modifiers*/ undefined, 
39297                 /*dotDotDotToken*/ undefined, name, 
39298                 /*questionToken*/ undefined, indexerTypeNode, 
39299                 /*initializer*/ undefined);
39300                 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
39301                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
39302                     context.encounteredError = true;
39303                 }
39304                 context.approximateLength += (name.length + 4);
39305                 return ts.createIndexSignature(
39306                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
39307             }
39308             function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) {
39309                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
39310                 if (suppressAny)
39311                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
39312                 var typeParameters;
39313                 var typeArguments;
39314                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
39315                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
39316                 }
39317                 else {
39318                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
39319                 }
39320                 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); });
39321                 if (signature.thisParameter) {
39322                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
39323                     parameters.unshift(thisParameter);
39324                 }
39325                 var returnTypeNode;
39326                 var typePredicate = getTypePredicateOfSignature(signature);
39327                 if (typePredicate) {
39328                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39329                         ts.createToken(124 /* AssertsKeyword */) :
39330                         undefined;
39331                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39332                         ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
39333                         ts.createThisTypeNode();
39334                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
39335                     returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
39336                 }
39337                 else {
39338                     var returnType = getReturnTypeOfSignature(signature);
39339                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
39340                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports);
39341                     }
39342                     else if (!suppressAny) {
39343                         returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
39344                     }
39345                 }
39346                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
39347                 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
39348             }
39349             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
39350                 var savedContextFlags = context.flags;
39351                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
39352                 var name = typeParameterToName(type, context);
39353                 var defaultParameter = getDefaultFromTypeParameter(type);
39354                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
39355                 context.flags = savedContextFlags;
39356                 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
39357             }
39358             function typeParameterToDeclaration(type, context, constraint) {
39359                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
39360                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
39361                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
39362             }
39363             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
39364                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
39365                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
39366                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */);
39367                 }
39368                 var parameterType = getTypeOfSymbol(parameterSymbol);
39369                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
39370                     parameterType = getOptionalType(parameterType);
39371                 }
39372                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
39373                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
39374                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
39375                 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
39376                 var name = parameterDeclaration ? parameterDeclaration.name ?
39377                     parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
39378                         parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
39379                             cloneBindingName(parameterDeclaration.name) :
39380                     ts.symbolName(parameterSymbol) :
39381                     ts.symbolName(parameterSymbol);
39382                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
39383                 var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
39384                 var parameterNode = ts.createParameter(
39385                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
39386                 /*initializer*/ undefined);
39387                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
39388                 return parameterNode;
39389                 function cloneBindingName(node) {
39390                     return elideInitializerAndSetEmitFlags(node);
39391                     function elideInitializerAndSetEmitFlags(node) {
39392                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
39393                             trackComputedName(node.expression, context.enclosingDeclaration, context);
39394                         }
39395                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
39396                         var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
39397                         if (clone.kind === 191 /* BindingElement */) {
39398                             clone.initializer = undefined;
39399                         }
39400                         return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
39401                     }
39402                 }
39403             }
39404             function trackComputedName(accessExpression, enclosingDeclaration, context) {
39405                 if (!context.tracker.trackSymbol)
39406                     return;
39407                 // get symbol of the first identifier of the entityName
39408                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
39409                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
39410                 if (name) {
39411                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
39412                 }
39413             }
39414             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
39415                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
39416                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
39417             }
39418             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
39419                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
39420                 var chain;
39421                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
39422                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
39423                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
39424                     ts.Debug.assert(chain && chain.length > 0);
39425                 }
39426                 else {
39427                     chain = [symbol];
39428                 }
39429                 return chain;
39430                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
39431                 function getSymbolChain(symbol, meaning, endOfChain) {
39432                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
39433                     var parentSpecifiers;
39434                     if (!accessibleSymbolChain ||
39435                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
39436                         // Go up and add our parent.
39437                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
39438                         if (ts.length(parents_1)) {
39439                             parentSpecifiers = parents_1.map(function (symbol) {
39440                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
39441                                     ? getSpecifierForModuleSymbol(symbol, context)
39442                                     : undefined;
39443                             });
39444                             var indices = parents_1.map(function (_, i) { return i; });
39445                             indices.sort(sortByBestName);
39446                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
39447                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
39448                                 var parent = sortedParents_1[_i];
39449                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
39450                                 if (parentChain) {
39451                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
39452                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
39453                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
39454                                         // No need to lookup an alias for the symbol in itself
39455                                         accessibleSymbolChain = parentChain;
39456                                         break;
39457                                     }
39458                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
39459                                     break;
39460                                 }
39461                             }
39462                         }
39463                     }
39464                     if (accessibleSymbolChain) {
39465                         return accessibleSymbolChain;
39466                     }
39467                     if (
39468                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
39469                     endOfChain ||
39470                         // If a parent symbol is an anonymous type, don't write it.
39471                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
39472                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
39473                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39474                             return;
39475                         }
39476                         return [symbol];
39477                     }
39478                     function sortByBestName(a, b) {
39479                         var specifierA = parentSpecifiers[a];
39480                         var specifierB = parentSpecifiers[b];
39481                         if (specifierA && specifierB) {
39482                             var isBRelative = ts.pathIsRelative(specifierB);
39483                             if (ts.pathIsRelative(specifierA) === isBRelative) {
39484                                 // Both relative or both non-relative, sort by number of parts
39485                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
39486                             }
39487                             if (isBRelative) {
39488                                 // A is non-relative, B is relative: prefer A
39489                                 return -1;
39490                             }
39491                             // A is relative, B is non-relative: prefer B
39492                             return 1;
39493                         }
39494                         return 0;
39495                     }
39496                 }
39497             }
39498             function typeParametersToTypeParameterDeclarations(symbol, context) {
39499                 var typeParameterNodes;
39500                 var targetSymbol = getTargetSymbol(symbol);
39501                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
39502                     typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
39503                 }
39504                 return typeParameterNodes;
39505             }
39506             function lookupTypeParameterNodes(chain, index, context) {
39507                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
39508                 var symbol = chain[index];
39509                 var symbolId = "" + getSymbolId(symbol);
39510                 if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
39511                     return undefined;
39512                 }
39513                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
39514                 var typeParameterNodes;
39515                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
39516                     var parentSymbol = symbol;
39517                     var nextSymbol_1 = chain[index + 1];
39518                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
39519                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
39520                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
39521                     }
39522                     else {
39523                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
39524                     }
39525                 }
39526                 return typeParameterNodes;
39527             }
39528             /**
39529              * Given A[B][C][D], finds A[B]
39530              */
39531             function getTopmostIndexedAccessType(top) {
39532                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
39533                     return getTopmostIndexedAccessType(top.objectType);
39534                 }
39535                 return top;
39536             }
39537             function getSpecifierForModuleSymbol(symbol, context) {
39538                 var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
39539                 if (!file) {
39540                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
39541                     if (equivalentFileSymbol) {
39542                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */);
39543                     }
39544                 }
39545                 if (file && file.moduleName !== undefined) {
39546                     // Use the amd name if it is available
39547                     return file.moduleName;
39548                 }
39549                 if (!file) {
39550                     if (context.tracker.trackReferencedAmbientModule) {
39551                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
39552                         if (ts.length(ambientDecls)) {
39553                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
39554                                 var decl = ambientDecls_1[_i];
39555                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
39556                             }
39557                         }
39558                     }
39559                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39560                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39561                     }
39562                 }
39563                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
39564                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
39565                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39566                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39567                     }
39568                     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
39569                 }
39570                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
39571                 var links = getSymbolLinks(symbol);
39572                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
39573                 if (!specifier) {
39574                     var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
39575                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
39576                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
39577                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
39578                     // specifier preference
39579                     var moduleResolverHost = context.tracker.moduleResolverHost;
39580                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
39581                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
39582                     links.specifierCache = links.specifierCache || ts.createMap();
39583                     links.specifierCache.set(contextFile.path, specifier);
39584                 }
39585                 return specifier;
39586             }
39587             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
39588                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
39589                 var isTypeOf = meaning === 111551 /* Value */;
39590                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39591                     // module is root, must use `ImportTypeNode`
39592                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
39593                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
39594                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
39595                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
39596                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
39597                         // since declaration files with these kinds of references are liable to fail when published :(
39598                         context.encounteredError = true;
39599                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
39600                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
39601                         }
39602                     }
39603                     var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
39604                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
39605                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
39606                     context.approximateLength += specifier.length + 10; // specifier + import("")
39607                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
39608                         if (nonRootParts) {
39609                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
39610                             lastId.typeArguments = undefined;
39611                         }
39612                         return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
39613                     }
39614                     else {
39615                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
39616                         var qualifier = splitNode.objectType.typeName;
39617                         return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
39618                     }
39619                 }
39620                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
39621                 if (ts.isIndexedAccessTypeNode(entityName)) {
39622                     return entityName; // Indexed accesses can never be `typeof`
39623                 }
39624                 if (isTypeOf) {
39625                     return ts.createTypeQueryNode(entityName);
39626                 }
39627                 else {
39628                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
39629                     var lastTypeArgs = lastId.typeArguments;
39630                     lastId.typeArguments = undefined;
39631                     return ts.createTypeReferenceNode(entityName, lastTypeArgs);
39632                 }
39633                 function createAccessFromSymbolChain(chain, index, stopper) {
39634                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
39635                     var symbol = chain[index];
39636                     var parent = chain[index - 1];
39637                     var symbolName;
39638                     if (index === 0) {
39639                         context.flags |= 16777216 /* InInitialEntityName */;
39640                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39641                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
39642                         context.flags ^= 16777216 /* InInitialEntityName */;
39643                     }
39644                     else {
39645                         if (parent && getExportsOfSymbol(parent)) {
39646                             var exports_1 = getExportsOfSymbol(parent);
39647                             ts.forEachEntry(exports_1, function (ex, name) {
39648                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
39649                                     symbolName = ts.unescapeLeadingUnderscores(name);
39650                                     return true;
39651                                 }
39652                             });
39653                         }
39654                     }
39655                     if (!symbolName) {
39656                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39657                     }
39658                     context.approximateLength += symbolName.length + 1;
39659                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
39660                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
39661                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
39662                         // Should use an indexed access
39663                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39664                         if (ts.isIndexedAccessTypeNode(LHS)) {
39665                             return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39666                         }
39667                         else {
39668                             return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39669                         }
39670                     }
39671                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39672                     identifier.symbol = symbol;
39673                     if (index > stopper) {
39674                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39675                         if (!ts.isEntityName(LHS)) {
39676                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
39677                         }
39678                         return ts.createQualifiedName(LHS, identifier);
39679                     }
39680                     return identifier;
39681                 }
39682             }
39683             function typeParameterShadowsNameInScope(escapedName, context, type) {
39684                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
39685                 if (result) {
39686                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
39687                         return false;
39688                     }
39689                     return true;
39690                 }
39691                 return false;
39692             }
39693             function typeParameterToName(type, context) {
39694                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
39695                     var cached = context.typeParameterNames.get("" + getTypeId(type));
39696                     if (cached) {
39697                         return cached;
39698                     }
39699                 }
39700                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
39701                 if (!(result.kind & 75 /* Identifier */)) {
39702                     return ts.createIdentifier("(Missing type parameter)");
39703                 }
39704                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
39705                     var rawtext = result.escapedText;
39706                     var i = 0;
39707                     var text = rawtext;
39708                     while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) {
39709                         i++;
39710                         text = rawtext + "_" + i;
39711                     }
39712                     if (text !== rawtext) {
39713                         result = ts.createIdentifier(text, result.typeArguments);
39714                     }
39715                     (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
39716                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
39717                 }
39718                 return result;
39719             }
39720             function symbolToName(symbol, context, meaning, expectsIdentifier) {
39721                 var chain = lookupSymbolChain(symbol, context, meaning);
39722                 if (expectsIdentifier && chain.length !== 1
39723                     && !context.encounteredError
39724                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
39725                     context.encounteredError = true;
39726                 }
39727                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
39728                 function createEntityNameFromSymbolChain(chain, index) {
39729                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39730                     var symbol = chain[index];
39731                     if (index === 0) {
39732                         context.flags |= 16777216 /* InInitialEntityName */;
39733                     }
39734                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39735                     if (index === 0) {
39736                         context.flags ^= 16777216 /* InInitialEntityName */;
39737                     }
39738                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39739                     identifier.symbol = symbol;
39740                     return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
39741                 }
39742             }
39743             function symbolToExpression(symbol, context, meaning) {
39744                 var chain = lookupSymbolChain(symbol, context, meaning);
39745                 return createExpressionFromSymbolChain(chain, chain.length - 1);
39746                 function createExpressionFromSymbolChain(chain, index) {
39747                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39748                     var symbol = chain[index];
39749                     if (index === 0) {
39750                         context.flags |= 16777216 /* InInitialEntityName */;
39751                     }
39752                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39753                     if (index === 0) {
39754                         context.flags ^= 16777216 /* InInitialEntityName */;
39755                     }
39756                     var firstChar = symbolName.charCodeAt(0);
39757                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39758                         return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
39759                     }
39760                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
39761                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
39762                         ts.isIdentifierStart(firstChar, languageVersion);
39763                     if (index === 0 || canUsePropertyAccess) {
39764                         var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39765                         identifier.symbol = symbol;
39766                         return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
39767                     }
39768                     else {
39769                         if (firstChar === 91 /* openBracket */) {
39770                             symbolName = symbolName.substring(1, symbolName.length - 1);
39771                             firstChar = symbolName.charCodeAt(0);
39772                         }
39773                         var expression = void 0;
39774                         if (ts.isSingleOrDoubleQuote(firstChar)) {
39775                             expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
39776                             expression.singleQuote = firstChar === 39 /* singleQuote */;
39777                         }
39778                         else if (("" + +symbolName) === symbolName) {
39779                             expression = ts.createLiteral(+symbolName);
39780                         }
39781                         if (!expression) {
39782                             expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39783                             expression.symbol = symbol;
39784                         }
39785                         return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
39786                     }
39787                 }
39788             }
39789             function isSingleQuotedStringNamed(d) {
39790                 var name = ts.getNameOfDeclaration(d);
39791                 if (name && ts.isStringLiteral(name) && (name.singleQuote ||
39792                     (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
39793                     return true;
39794                 }
39795                 return false;
39796             }
39797             function getPropertyNameNodeForSymbol(symbol, context) {
39798                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
39799                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
39800                 if (fromNameType) {
39801                     return fromNameType;
39802                 }
39803                 if (ts.isKnownSymbol(symbol)) {
39804                     return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
39805                 }
39806                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
39807                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
39808             }
39809             // See getNameForSymbolFromNameType for a stringy equivalent
39810             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
39811                 var nameType = getSymbolLinks(symbol).nameType;
39812                 if (nameType) {
39813                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
39814                         var name = "" + nameType.value;
39815                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
39816                             return ts.createLiteral(name, !!singleQuote);
39817                         }
39818                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
39819                             return ts.createComputedPropertyName(ts.createLiteral(+name));
39820                         }
39821                         return createPropertyNameNodeForIdentifierOrLiteral(name);
39822                     }
39823                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
39824                         return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
39825                     }
39826                 }
39827             }
39828             function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
39829                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote);
39830             }
39831             function cloneNodeBuilderContext(context) {
39832                 var initial = __assign({}, context);
39833                 // Make type parameters created within this context not consume the name outside this context
39834                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
39835                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
39836                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
39837                 // were multiple generic overloads with similar generated type parameter names
39838                 // The effect:
39839                 // When we write out
39840                 // export const x: <T>(x: T) => T
39841                 // export const y: <T>(x: T) => T
39842                 // we write it out like that, rather than as
39843                 // export const x: <T>(x: T) => T
39844                 // export const y: <T_1>(x: T_1) => T_1
39845                 if (initial.typeParameterNames) {
39846                     initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
39847                 }
39848                 if (initial.typeParameterNamesByText) {
39849                     initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
39850                 }
39851                 if (initial.typeParameterSymbolList) {
39852                     initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
39853                 }
39854                 return initial;
39855             }
39856             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
39857                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
39858             }
39859             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
39860                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
39861             }
39862             /**
39863              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
39864              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
39865              */
39866             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
39867                 if (type !== errorType && enclosingDeclaration) {
39868                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
39869                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
39870                         // try to reuse the existing annotation
39871                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
39872                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
39873                             var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
39874                             if (result_4) {
39875                                 return result_4;
39876                             }
39877                         }
39878                     }
39879                 }
39880                 var oldFlags = context.flags;
39881                 if (type.flags & 8192 /* UniqueESSymbol */ &&
39882                     type.symbol === symbol) {
39883                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
39884                 }
39885                 var result = typeToTypeNodeHelper(type, context);
39886                 context.flags = oldFlags;
39887                 return result;
39888             }
39889             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
39890                 if (type !== errorType && context.enclosingDeclaration) {
39891                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
39892                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
39893                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
39894                         if (result) {
39895                             return result;
39896                         }
39897                     }
39898                 }
39899                 return typeToTypeNodeHelper(type, context);
39900             }
39901             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
39902                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
39903                     cancellationToken.throwIfCancellationRequested();
39904                 }
39905                 var hadError = false;
39906                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
39907                 if (hadError) {
39908                     return undefined;
39909                 }
39910                 return transformed === existing ? ts.getMutableClone(existing) : transformed;
39911                 function visitExistingNodeTreeSymbols(node) {
39912                     var _a, _b;
39913                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
39914                     if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) {
39915                         return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39916                     }
39917                     if (ts.isJSDocUnknownType(node)) {
39918                         return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
39919                     }
39920                     if (ts.isJSDocNullableType(node)) {
39921                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
39922                     }
39923                     if (ts.isJSDocOptionalType(node)) {
39924                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
39925                     }
39926                     if (ts.isJSDocNonNullableType(node)) {
39927                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
39928                     }
39929                     if (ts.isJSDocVariadicType(node)) {
39930                         return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39931                     }
39932                     if (ts.isJSDocTypeLiteral(node)) {
39933                         return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
39934                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
39935                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
39936                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
39937                             return ts.createPropertySignature(
39938                             /*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 */), 
39939                             /*initializer*/ undefined);
39940                         }));
39941                     }
39942                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
39943                         return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node);
39944                     }
39945                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
39946                         return ts.createTypeLiteralNode([ts.createIndexSignature(
39947                             /*decorators*/ undefined, 
39948                             /*modifiers*/ undefined, [ts.createParameter(
39949                                 /*decorators*/ undefined, 
39950                                 /*modifiers*/ undefined, 
39951                                 /*dotdotdotToken*/ undefined, "x", 
39952                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
39953                     }
39954                     if (ts.isJSDocFunctionType(node)) {
39955                         if (ts.isJSDocConstructSignature(node)) {
39956                             var newTypeNode_1;
39957                             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(
39958                             /*decorators*/ undefined, 
39959                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39960                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
39961                         }
39962                         else {
39963                             return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
39964                             /*decorators*/ undefined, 
39965                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39966                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39967                         }
39968                     }
39969                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
39970                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
39971                     }
39972                     if (ts.isLiteralImportTypeNode(node)) {
39973                         return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
39974                     }
39975                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
39976                         var leftmost = ts.getFirstIdentifier(node);
39977                         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)))) {
39978                             hadError = true;
39979                             return node;
39980                         }
39981                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
39982                         if (sym) {
39983                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
39984                                 hadError = true;
39985                             }
39986                             else {
39987                                 (_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 */);
39988                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
39989                             }
39990                             if (ts.isIdentifier(node)) {
39991                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node);
39992                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
39993                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
39994                             }
39995                         }
39996                     }
39997                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
39998                     function getEffectiveDotDotDotForParameter(p) {
39999                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined);
40000                     }
40001                     function rewriteModuleSpecifier(parent, lit) {
40002                         if (bundled) {
40003                             if (context.tracker && context.tracker.moduleResolverHost) {
40004                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
40005                                 if (targetFile) {
40006                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
40007                                     var resolverHost = {
40008                                         getCanonicalFileName: getCanonicalFileName,
40009                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
40010                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
40011                                     };
40012                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
40013                                     return ts.createLiteral(newName);
40014                                 }
40015                             }
40016                         }
40017                         else {
40018                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
40019                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
40020                                 if (moduleSym) {
40021                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
40022                                 }
40023                             }
40024                         }
40025                         return lit;
40026                     }
40027                 }
40028             }
40029             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
40030                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
40031                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
40032                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
40033                 // declaration mapping
40034                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
40035                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
40036                 // we're trying to emit from later on)
40037                 var enclosingDeclaration = context.enclosingDeclaration;
40038                 var results = [];
40039                 var visitedSymbols = ts.createMap();
40040                 var deferredPrivates;
40041                 var oldcontext = context;
40042                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
40043                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
40044                             if (accessibleResult.accessibility === 0 /* Accessible */) {
40045                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
40046                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
40047                                 if (!(sym.flags & 4 /* Property */)) {
40048                                     includePrivateSymbol(chain[0]);
40049                                 }
40050                             }
40051                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
40052                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
40053                             }
40054                         } }) });
40055                 if (oldcontext.usedSymbolNames) {
40056                     oldcontext.usedSymbolNames.forEach(function (_, name) {
40057                         context.usedSymbolNames.set(name, true);
40058                     });
40059                 }
40060                 ts.forEachEntry(symbolTable, function (symbol, name) {
40061                     var baseName = ts.unescapeLeadingUnderscores(name);
40062                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
40063                 });
40064                 var addingDeclare = !bundled;
40065                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
40066                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
40067                     symbolTable = ts.createSymbolTable();
40068                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
40069                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
40070                 }
40071                 visitSymbolTable(symbolTable);
40072                 return mergeRedundantStatements(results);
40073                 function isIdentifierAndNotUndefined(node) {
40074                     return !!node && node.kind === 75 /* Identifier */;
40075                 }
40076                 function getNamesOfDeclaration(statement) {
40077                     if (ts.isVariableStatement(statement)) {
40078                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
40079                     }
40080                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
40081                 }
40082                 function flattenExportAssignedNamespace(statements) {
40083                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
40084                     var ns = ts.find(statements, ts.isModuleDeclaration);
40085                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
40086                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
40087                         ns.body && ts.isModuleBlock(ns.body)) {
40088                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
40089                         //  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
40090                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
40091                         if (ts.length(excessExports)) {
40092                             ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
40093                                 /*decorators*/ undefined, 
40094                                 /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })), 
40095                                 /*moduleSpecifier*/ undefined)]));
40096                         }
40097                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
40098                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
40099                             results = [];
40100                             ts.forEach(ns.body.statements, function (s) {
40101                                 addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
40102                             });
40103                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
40104                         }
40105                     }
40106                     return statements;
40107                 }
40108                 function mergeExportDeclarations(statements) {
40109                     // Pass 2: Combine all `export {}` declarations
40110                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
40111                     if (ts.length(exports) > 1) {
40112                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
40113                         statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
40114                             /*decorators*/ undefined, 
40115                             /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
40116                             /*moduleSpecifier*/ undefined)]);
40117                     }
40118                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
40119                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
40120                     if (ts.length(reexports) > 1) {
40121                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
40122                         if (groups.length !== reexports.length) {
40123                             var _loop_8 = function (group_1) {
40124                                 if (group_1.length > 1) {
40125                                     // remove group members from statements and then merge group members and add back to statements
40126                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
40127                                         ts.createExportDeclaration(
40128                                         /*decorators*/ undefined, 
40129                                         /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
40130                                     ]);
40131                                 }
40132                             };
40133                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
40134                                 var group_1 = groups_1[_i];
40135                                 _loop_8(group_1);
40136                             }
40137                         }
40138                     }
40139                     return statements;
40140                 }
40141                 function inlineExportModifiers(statements) {
40142                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
40143                     var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
40144                     if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
40145                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
40146                             if (!e.propertyName) {
40147                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
40148                                 var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
40149                                 if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
40150                                     ts.forEach(associated, addExportModifier);
40151                                     return undefined;
40152                                 }
40153                             }
40154                             return e;
40155                         });
40156                         if (!ts.length(replacements)) {
40157                             // all clauses removed, filter the export declaration
40158                             statements = ts.filter(statements, function (s) { return s !== exportDecl; });
40159                         }
40160                         else {
40161                             // some items filtered, others not - update the export declaration
40162                             // (mutating because why not, we're building a whole new tree here anyway)
40163                             exportDecl.exportClause.elements = ts.createNodeArray(replacements);
40164                         }
40165                     }
40166                     return statements;
40167                 }
40168                 function mergeRedundantStatements(statements) {
40169                     statements = flattenExportAssignedNamespace(statements);
40170                     statements = mergeExportDeclarations(statements);
40171                     statements = inlineExportModifiers(statements);
40172                     // 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
40173                     // declaration privacy is respected.
40174                     if (enclosingDeclaration &&
40175                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
40176                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
40177                         statements.push(ts.createEmptyExports());
40178                     }
40179                     return statements;
40180                 }
40181                 function canHaveExportModifier(node) {
40182                     return ts.isEnumDeclaration(node) ||
40183                         ts.isVariableStatement(node) ||
40184                         ts.isFunctionDeclaration(node) ||
40185                         ts.isClassDeclaration(node) ||
40186                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
40187                         ts.isInterfaceDeclaration(node) ||
40188                         isTypeDeclaration(node);
40189                 }
40190                 function addExportModifier(statement) {
40191                     var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
40192                     statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
40193                     statement.modifierFlagsCache = 0;
40194                 }
40195                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
40196                     var oldDeferredPrivates = deferredPrivates;
40197                     if (!suppressNewPrivateContext) {
40198                         deferredPrivates = ts.createMap();
40199                     }
40200                     symbolTable.forEach(function (symbol) {
40201                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
40202                     });
40203                     if (!suppressNewPrivateContext) {
40204                         // deferredPrivates will be filled up by visiting the symbol table
40205                         // And will continue to iterate as elements are added while visited `deferredPrivates`
40206                         // (As that's how a map iterator is defined to work)
40207                         deferredPrivates.forEach(function (symbol) {
40208                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
40209                         });
40210                     }
40211                     deferredPrivates = oldDeferredPrivates;
40212                 }
40213                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
40214                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
40215                     // still skip reserializing it if we encounter the merged product later on
40216                     var visitedSym = getMergedSymbol(symbol);
40217                     if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
40218                         return; // Already printed
40219                     }
40220                     visitedSymbols.set("" + getSymbolId(visitedSym), true);
40221                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
40222                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
40223                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
40224                         var oldContext = context;
40225                         context = cloneNodeBuilderContext(context);
40226                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
40227                         context = oldContext;
40228                         return result;
40229                     }
40230                 }
40231                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
40232                 // or a merge of some number of those.
40233                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
40234                 // each symbol in only one of the representations
40235                 // Also, synthesizing a default export of some kind
40236                 // If it's an alias: emit `export default ref`
40237                 // If it's a property: emit `export default _default` with a `_default` prop
40238                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
40239                 // These forms can merge, eg (`export default 12; export default interface A {}`)
40240                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
40241                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
40242                     var isDefault = symbol.escapedName === "default" /* Default */;
40243                     if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
40244                         // 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` :(
40245                         context.encounteredError = true;
40246                         // TODO: Issue error via symbol tracker?
40247                         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
40248                     }
40249                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
40250                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
40251                     if (needsPostExportDefault) {
40252                         isPrivate = true;
40253                     }
40254                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
40255                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
40256                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
40257                         symbol.escapedName !== "export=" /* ExportEquals */;
40258                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
40259                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
40260                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40261                     }
40262                     if (symbol.flags & 524288 /* TypeAlias */) {
40263                         serializeTypeAlias(symbol, symbolName, modifierFlags);
40264                     }
40265                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
40266                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
40267                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
40268                         && symbol.escapedName !== "export=" /* ExportEquals */
40269                         && !(symbol.flags & 4194304 /* Prototype */)
40270                         && !(symbol.flags & 32 /* Class */)
40271                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
40272                         serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
40273                     }
40274                     if (symbol.flags & 384 /* Enum */) {
40275                         serializeEnum(symbol, symbolName, modifierFlags);
40276                     }
40277                     if (symbol.flags & 32 /* Class */) {
40278                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
40279                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
40280                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
40281                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
40282                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40283                         }
40284                         else {
40285                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40286                         }
40287                     }
40288                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
40289                         serializeModule(symbol, symbolName, modifierFlags);
40290                     }
40291                     if (symbol.flags & 64 /* Interface */) {
40292                         serializeInterface(symbol, symbolName, modifierFlags);
40293                     }
40294                     if (symbol.flags & 2097152 /* Alias */) {
40295                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40296                     }
40297                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
40298                         serializeMaybeAliasAssignment(symbol);
40299                     }
40300                     if (symbol.flags & 8388608 /* ExportStar */) {
40301                         // synthesize export * from "moduleReference"
40302                         // Straightforward - only one thing to do - make an export declaration
40303                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
40304                             var node = _a[_i];
40305                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
40306                             if (!resolvedModule)
40307                                 continue;
40308                             addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
40309                         }
40310                     }
40311                     if (needsPostExportDefault) {
40312                         addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
40313                     }
40314                 }
40315                 function includePrivateSymbol(symbol) {
40316                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
40317                         return;
40318                     ts.Debug.assertIsDefined(deferredPrivates);
40319                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
40320                     deferredPrivates.set("" + getSymbolId(symbol), symbol);
40321                 }
40322                 function isExportingScope(enclosingDeclaration) {
40323                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
40324                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
40325                 }
40326                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
40327                 // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
40328                 function addResult(node, additionalModifierFlags) {
40329                     var newModifierFlags = 0 /* None */;
40330                     if (additionalModifierFlags & 1 /* Export */ &&
40331                         enclosingDeclaration &&
40332                         isExportingScope(enclosingDeclaration) &&
40333                         canHaveExportModifier(node)) {
40334                         // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
40335                         newModifierFlags |= 1 /* Export */;
40336                     }
40337                     if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
40338                         (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
40339                         (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
40340                         // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
40341                         newModifierFlags |= 2 /* Ambient */;
40342                     }
40343                     if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
40344                         newModifierFlags |= 512 /* Default */;
40345                     }
40346                     if (newModifierFlags) {
40347                         node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
40348                         node.modifierFlagsCache = 0; // Reset computed flags cache
40349                     }
40350                     results.push(node);
40351                 }
40352                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
40353                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
40354                     var typeParams = getSymbolLinks(symbol).typeParameters;
40355                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
40356                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
40357                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
40358                     var oldFlags = context.flags;
40359                     context.flags |= 8388608 /* InTypeAlias */;
40360                     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);
40361                     context.flags = oldFlags;
40362                 }
40363                 function serializeInterface(symbol, symbolName, modifierFlags) {
40364                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
40365                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40366                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40367                     var baseTypes = getBaseTypes(interfaceType);
40368                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
40369                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
40370                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
40371                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
40372                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
40373                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
40374                     addResult(ts.createInterfaceDeclaration(
40375                     /*decorators*/ undefined, 
40376                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
40377                 }
40378                 function getNamespaceMembersForSerialization(symbol) {
40379                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
40380                 }
40381                 function isTypeOnlyNamespace(symbol) {
40382                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
40383                 }
40384                 function serializeModule(symbol, symbolName, modifierFlags) {
40385                     var members = getNamespaceMembersForSerialization(symbol);
40386                     // 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)
40387                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
40388                     var realMembers = locationMap.get("real") || ts.emptyArray;
40389                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
40390                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
40391                     // 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,
40392                     // so we don't even have placeholders to fill in.
40393                     if (ts.length(realMembers)) {
40394                         var localName = getInternalSymbolName(symbol, symbolName);
40395                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
40396                     }
40397                     if (ts.length(mergedMembers)) {
40398                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
40399                         var localName = getInternalSymbolName(symbol, symbolName);
40400                         var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
40401                             /*decorators*/ undefined, 
40402                             /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
40403                                 var _a, _b;
40404                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
40405                                 var localName = getInternalSymbolName(s, name);
40406                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
40407                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
40408                                     (_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);
40409                                     return undefined;
40410                                 }
40411                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40412                                 includePrivateSymbol(target || s);
40413                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
40414                                 return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
40415                             })))]);
40416                         addResult(ts.createModuleDeclaration(
40417                         /*decorators*/ undefined, 
40418                         /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
40419                     }
40420                 }
40421                 function serializeEnum(symbol, symbolName, modifierFlags) {
40422                     addResult(ts.createEnumDeclaration(
40423                     /*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) {
40424                         // TODO: Handle computed names
40425                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
40426                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
40427                         // _on the declaration_, not on the declaration's symbol...
40428                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
40429                         return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
40430                     })), modifierFlags);
40431                 }
40432                 function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
40433                     if (propertyAsAlias) {
40434                         serializeMaybeAliasAssignment(symbol);
40435                     }
40436                     else {
40437                         var type = getTypeOfSymbol(symbol);
40438                         var localName = getInternalSymbolName(symbol, symbolName);
40439                         if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
40440                             // 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
40441                             serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
40442                         }
40443                         else {
40444                             // 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!_
40445                             // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
40446                             var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
40447                                 : isConstVariable(symbol) ? 2 /* Const */
40448                                     : 1 /* Let */;
40449                             var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
40450                             var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
40451                             if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
40452                                 textRange = textRange.parent.parent;
40453                             }
40454                             var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40455                                 ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40456                             ], flags)), textRange);
40457                             addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
40458                             if (name !== localName && !isPrivate) {
40459                                 // We rename the variable declaration we generate for Property symbols since they may have a name which
40460                                 // conflicts with a local declaration. For example, given input:
40461                                 // ```
40462                                 // function g() {}
40463                                 // module.exports.g = g
40464                                 // ```
40465                                 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
40466                                 // Naively, we would emit
40467                                 // ```
40468                                 // function g() {}
40469                                 // export const g: typeof g;
40470                                 // ```
40471                                 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
40472                                 // the export declaration shadows it.
40473                                 // To work around that, we instead write
40474                                 // ```
40475                                 // function g() {}
40476                                 // const g_1: typeof g;
40477                                 // export { g_1 as g };
40478                                 // ```
40479                                 // To create an export named `g` that does _not_ shadow the local `g`
40480                                 addResult(ts.createExportDeclaration(
40481                                 /*decorators*/ undefined, 
40482                                 /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
40483                             }
40484                         }
40485                     }
40486                 }
40487                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
40488                     var signatures = getSignaturesOfType(type, 0 /* Call */);
40489                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
40490                         var sig = signatures_2[_i];
40491                         // Each overload becomes a separate function declaration, in order
40492                         var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled);
40493                         decl.name = ts.createIdentifier(localName);
40494                         // for expressions assigned to `var`s, use the `var` as the text range
40495                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
40496                     }
40497                     // Module symbol emit will take care of module-y members, provided it has exports
40498                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
40499                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
40500                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
40501                     }
40502                 }
40503                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
40504                     if (ts.length(props)) {
40505                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
40506                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
40507                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
40508                             }) ? "local" : "remote";
40509                         });
40510                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
40511                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
40512                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
40513                         // Example:
40514                         // import Foo_1 = require("./exporter");
40515                         // export namespace ns {
40516                         //     import Foo = Foo_1.Foo;
40517                         //     export { Foo };
40518                         //     export const c: number;
40519                         // }
40520                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
40521                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
40522                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
40523                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
40524                         // emit akin to the above would be needed.
40525                         // Add a namespace
40526                         var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
40527                         fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
40528                         fakespace.parent = enclosingDeclaration;
40529                         fakespace.locals = ts.createSymbolTable(props);
40530                         fakespace.symbol = props[0].parent;
40531                         var oldResults = results;
40532                         results = [];
40533                         var oldAddingDeclare = addingDeclare;
40534                         addingDeclare = false;
40535                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
40536                         var oldContext = context;
40537                         context = subcontext;
40538                         // 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
40539                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
40540                         context = oldContext;
40541                         addingDeclare = oldAddingDeclare;
40542                         var declarations = results;
40543                         results = oldResults;
40544                         fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
40545                         fakespace.parent = undefined;
40546                         fakespace.locals = undefined;
40547                         fakespace.symbol = undefined;
40548                         fakespace.body = ts.createModuleBlock(declarations);
40549                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
40550                     }
40551                 }
40552                 function isNamespaceMember(p) {
40553                     return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
40554                 }
40555                 function serializeAsClass(symbol, localName, modifierFlags) {
40556                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40557                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40558                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
40559                     var baseTypes = getBaseTypes(classType);
40560                     var implementsTypes = getImplementsTypes(classType);
40561                     var staticType = getTypeOfSymbol(symbol);
40562                     var staticBaseType = getBaseConstructorTypeOfClass(staticType);
40563                     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); }))]);
40564                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
40565                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
40566                         // `valueDeclaration` could be undefined if inherited from
40567                         // a union/intersection base type, but inherited properties
40568                         // don't matter here.
40569                         var valueDecl = s.valueDeclaration;
40570                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
40571                     });
40572                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
40573                         // `valueDeclaration` could be undefined if inherited from
40574                         // a union/intersection base type, but inherited properties
40575                         // don't matter here.
40576                         var valueDecl = s.valueDeclaration;
40577                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
40578                     });
40579                     // Boil down all private properties into a single one.
40580                     var privateProperties = hasPrivateIdentifier ?
40581                         [ts.createProperty(
40582                             /*decorators*/ undefined, 
40583                             /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
40584                             /*questionOrExclamationToken*/ undefined, 
40585                             /*type*/ undefined, 
40586                             /*initializer*/ undefined)] :
40587                         ts.emptyArray;
40588                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
40589                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
40590                     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); });
40591                     var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
40592                     for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
40593                         var c = constructors_1[_i];
40594                         // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
40595                         // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
40596                         c.type = undefined;
40597                         c.typeParameters = undefined;
40598                     }
40599                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
40600                     addResult(ts.setTextRange(ts.createClassDeclaration(
40601                     /*decorators*/ undefined, 
40602                     /*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);
40603                 }
40604                 function serializeAsAlias(symbol, localName, modifierFlags) {
40605                     // synthesize an alias, eg `export { symbolName as Name }`
40606                     // need to mark the alias `symbol` points at
40607                     // as something we need to serialize as a private declaration as well
40608                     var node = getDeclarationOfAliasSymbol(symbol);
40609                     if (!node)
40610                         return ts.Debug.fail();
40611                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
40612                     if (!target) {
40613                         return;
40614                     }
40615                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
40616                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
40617                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
40618                         verbatimTargetName = "default" /* Default */;
40619                     }
40620                     var targetName = getInternalSymbolName(target, verbatimTargetName);
40621                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
40622                     switch (node.kind) {
40623                         case 253 /* ImportEqualsDeclaration */:
40624                             // Could be a local `import localName = ns.member` or
40625                             // an external `import localName = require("whatever")`
40626                             var isLocalImport = !(target.flags & 512 /* ValueModule */);
40627                             addResult(ts.createImportEqualsDeclaration(
40628                             /*decorators*/ undefined, 
40629                             /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
40630                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
40631                                 : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
40632                             break;
40633                         case 252 /* NamespaceExportDeclaration */:
40634                             // export as namespace foo
40635                             // TODO: Not part of a file's local or export symbol tables
40636                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
40637                             addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
40638                             break;
40639                         case 255 /* ImportClause */:
40640                             addResult(ts.createImportDeclaration(
40641                             /*decorators*/ undefined, 
40642                             /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), 
40643                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
40644                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
40645                             // In such cases, the `target` refers to the module itself already
40646                             ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40647                             break;
40648                         case 256 /* NamespaceImport */:
40649                             addResult(ts.createImportDeclaration(
40650                             /*decorators*/ undefined, 
40651                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40652                             break;
40653                         case 262 /* NamespaceExport */:
40654                             addResult(ts.createExportDeclaration(
40655                             /*decorators*/ undefined, 
40656                             /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40657                             break;
40658                         case 258 /* ImportSpecifier */:
40659                             addResult(ts.createImportDeclaration(
40660                             /*decorators*/ undefined, 
40661                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
40662                                 ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
40663                             ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40664                             break;
40665                         case 263 /* ExportSpecifier */:
40666                             // does not use localName because the symbol name in this case refers to the name in the exports table,
40667                             // which we must exactly preserve
40668                             var specifier = node.parent.parent.moduleSpecifier;
40669                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
40670                             // another file
40671                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
40672                             break;
40673                         case 259 /* ExportAssignment */:
40674                             serializeMaybeAliasAssignment(symbol);
40675                             break;
40676                         case 209 /* BinaryExpression */:
40677                         case 194 /* PropertyAccessExpression */:
40678                             // Could be best encoded as though an export specifier or as though an export assignment
40679                             // If name is default or export=, do an export assignment
40680                             // Otherwise do an export specifier
40681                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
40682                                 serializeMaybeAliasAssignment(symbol);
40683                             }
40684                             else {
40685                                 serializeExportSpecifier(localName, targetName);
40686                             }
40687                             break;
40688                         default:
40689                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
40690                     }
40691                 }
40692                 function serializeExportSpecifier(localName, targetName, specifier) {
40693                     addResult(ts.createExportDeclaration(
40694                     /*decorators*/ undefined, 
40695                     /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
40696                 }
40697                 function serializeMaybeAliasAssignment(symbol) {
40698                     if (symbol.flags & 4194304 /* Prototype */) {
40699                         return;
40700                     }
40701                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
40702                     var isExportEquals = name === "export=" /* ExportEquals */;
40703                     var isDefault = name === "default" /* Default */;
40704                     var isExportAssignment = isExportEquals || isDefault;
40705                     // synthesize export = ref
40706                     // ref should refer to either be a locally scoped symbol which we need to emit, or
40707                     // a reference to another namespace/module which we may need to emit an `import` statement for
40708                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
40709                     // serialize what the alias points to, preserve the declaration's initializer
40710                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40711                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
40712                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
40713                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
40714                         // eg, `namespace A { export class B {} }; exports = A.B;`
40715                         // Technically, this is all that's required in the case where the assignment is an entity name expression
40716                         var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
40717                         var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
40718                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
40719                         if (referenced || target) {
40720                             includePrivateSymbol(referenced || target);
40721                         }
40722                         // We disable the context's symbol tracker for the duration of this name serialization
40723                         // as, by virtue of being here, the name is required to print something, and we don't want to
40724                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
40725                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
40726                         // into the containing scope anyway, so we want to skip the visibility checks.
40727                         var oldTrack = context.tracker.trackSymbol;
40728                         context.tracker.trackSymbol = ts.noop;
40729                         if (isExportAssignment) {
40730                             results.push(ts.createExportAssignment(
40731                             /*decorators*/ undefined, 
40732                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
40733                         }
40734                         else {
40735                             if (first_1 === expr) {
40736                                 // serialize as `export {target as name}`
40737                                 serializeExportSpecifier(name, ts.idText(first_1));
40738                             }
40739                             else if (ts.isClassExpression(expr)) {
40740                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
40741                             }
40742                             else {
40743                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
40744                                 var varName = getUnusedName(name, symbol);
40745                                 addResult(ts.createImportEqualsDeclaration(
40746                                 /*decorators*/ undefined, 
40747                                 /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
40748                                 serializeExportSpecifier(name, varName);
40749                             }
40750                         }
40751                         context.tracker.trackSymbol = oldTrack;
40752                     }
40753                     else {
40754                         // serialize as an anonymous property declaration
40755                         var varName = getUnusedName(name, symbol);
40756                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
40757                         // (Unwidened types can only exist in expression contexts and should never be serialized)
40758                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
40759                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
40760                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
40761                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
40762                         }
40763                         else {
40764                             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40765                                 ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40766                             ], 2 /* Const */));
40767                             addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
40768                         }
40769                         if (isExportAssignment) {
40770                             results.push(ts.createExportAssignment(
40771                             /*decorators*/ undefined, 
40772                             /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
40773                         }
40774                         else if (name !== varName) {
40775                             serializeExportSpecifier(name, varName);
40776                         }
40777                     }
40778                 }
40779                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
40780                     // Only object types which are not constructable, or indexable, whose members all come from the
40781                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
40782                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
40783                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
40784                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
40785                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
40786                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
40787                         !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
40788                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
40789                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
40790                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
40791                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
40792                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
40793                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
40794                 }
40795                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
40796                     return function serializePropertySymbol(p, isStatic, baseType) {
40797                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
40798                         var isPrivate = !!(modifierFlags & 8 /* Private */);
40799                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
40800                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
40801                             // need to be merged namespace members
40802                             return [];
40803                         }
40804                         if (p.flags & 4194304 /* Prototype */ ||
40805                             (baseType && getPropertyOfType(baseType, p.escapedName)
40806                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
40807                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
40808                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
40809                             return [];
40810                         }
40811                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
40812                         var name = getPropertyNameNodeForSymbol(p, context);
40813                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
40814                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
40815                             var result = [];
40816                             if (p.flags & 65536 /* SetAccessor */) {
40817                                 result.push(ts.setTextRange(ts.createSetAccessor(
40818                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
40819                                     /*decorators*/ undefined, 
40820                                     /*modifiers*/ undefined, 
40821                                     /*dotDotDotToken*/ undefined, "arg", 
40822                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
40823                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
40824                             }
40825                             if (p.flags & 32768 /* GetAccessor */) {
40826                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
40827                                 result.push(ts.setTextRange(ts.createGetAccessor(
40828                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40829                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
40830                             }
40831                             return result;
40832                         }
40833                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
40834                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
40835                         else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
40836                             return ts.setTextRange(createProperty(
40837                             /*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), 
40838                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
40839                             // interface members can't have initializers, however class members _can_
40840                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
40841                         }
40842                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
40843                             var type = getTypeOfSymbol(p);
40844                             var signatures = getSignaturesOfType(type, 0 /* Call */);
40845                             if (flag & 8 /* Private */) {
40846                                 return ts.setTextRange(createProperty(
40847                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, 
40848                                 /*type*/ undefined, 
40849                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
40850                             }
40851                             var results_1 = [];
40852                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
40853                                 var sig = signatures_3[_i];
40854                                 // Each overload becomes a separate method declaration, in order
40855                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
40856                                 decl.name = name; // TODO: Clone
40857                                 if (flag) {
40858                                     decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
40859                                 }
40860                                 if (p.flags & 16777216 /* Optional */) {
40861                                     decl.questionToken = ts.createToken(57 /* QuestionToken */);
40862                                 }
40863                                 results_1.push(ts.setTextRange(decl, sig.declaration));
40864                             }
40865                             return results_1;
40866                         }
40867                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
40868                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
40869                     };
40870                 }
40871                 function serializePropertySymbolForInterface(p, baseType) {
40872                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
40873                 }
40874                 function serializeSignatures(kind, input, baseType, outputKind) {
40875                     var signatures = getSignaturesOfType(input, kind);
40876                     if (kind === 1 /* Construct */) {
40877                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40878                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
40879                         }
40880                         if (baseType) {
40881                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
40882                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
40883                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40884                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
40885                             }
40886                             if (baseSigs.length === signatures.length) {
40887                                 var failed = false;
40888                                 for (var i = 0; i < baseSigs.length; i++) {
40889                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
40890                                         failed = true;
40891                                         break;
40892                                     }
40893                                 }
40894                                 if (!failed) {
40895                                     return []; // Every signature was identical - elide constructor list as it is inherited
40896                                 }
40897                             }
40898                         }
40899                         var privateProtected = 0;
40900                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
40901                             var s = signatures_4[_i];
40902                             if (s.declaration) {
40903                                 privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
40904                             }
40905                         }
40906                         if (privateProtected) {
40907                             return [ts.setTextRange(ts.createConstructor(
40908                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected), 
40909                                 /*parameters*/ [], 
40910                                 /*body*/ undefined), signatures[0].declaration)];
40911                         }
40912                     }
40913                     var results = [];
40914                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
40915                         var sig = signatures_5[_a];
40916                         // Each overload becomes a separate constructor declaration, in order
40917                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
40918                         results.push(ts.setTextRange(decl, sig.declaration));
40919                     }
40920                     return results;
40921                 }
40922                 function serializeIndexSignatures(input, baseType) {
40923                     var results = [];
40924                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
40925                         var type = _a[_i];
40926                         var info = getIndexInfoOfType(input, type);
40927                         if (info) {
40928                             if (baseType) {
40929                                 var baseInfo = getIndexInfoOfType(baseType, type);
40930                                 if (baseInfo) {
40931                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
40932                                         continue; // elide identical index signatures
40933                                     }
40934                                 }
40935                             }
40936                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
40937                         }
40938                     }
40939                     return results;
40940                 }
40941                 function serializeBaseType(t, staticType, rootName) {
40942                     var ref = trySerializeAsTypeReference(t);
40943                     if (ref) {
40944                         return ref;
40945                     }
40946                     var tempName = getUnusedName(rootName + "_base");
40947                     var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40948                         ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
40949                     ], 2 /* Const */));
40950                     addResult(statement, 0 /* None */);
40951                     return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
40952                 }
40953                 function trySerializeAsTypeReference(t) {
40954                     var typeArgs;
40955                     var reference;
40956                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
40957                     // which we can't write out in a syntactically valid way as an expression
40958                     if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40959                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
40960                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
40961                     }
40962                     else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40963                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
40964                     }
40965                     if (reference) {
40966                         return ts.createExpressionWithTypeArguments(typeArgs, reference);
40967                     }
40968                 }
40969                 function getUnusedName(input, symbol) {
40970                     if (symbol) {
40971                         if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40972                             return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40973                         }
40974                     }
40975                     if (symbol) {
40976                         input = getNameCandidateWorker(symbol, input);
40977                     }
40978                     var i = 0;
40979                     var original = input;
40980                     while (context.usedSymbolNames.has(input)) {
40981                         i++;
40982                         input = original + "_" + i;
40983                     }
40984                     context.usedSymbolNames.set(input, true);
40985                     if (symbol) {
40986                         context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
40987                     }
40988                     return input;
40989                 }
40990                 function getNameCandidateWorker(symbol, localName) {
40991                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
40992                         var flags = context.flags;
40993                         context.flags |= 16777216 /* InInitialEntityName */;
40994                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
40995                         context.flags = flags;
40996                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
40997                     }
40998                     if (localName === "default" /* Default */) {
40999                         localName = "_default";
41000                     }
41001                     else if (localName === "export=" /* ExportEquals */) {
41002                         localName = "_exports";
41003                     }
41004                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
41005                     return localName;
41006                 }
41007                 function getInternalSymbolName(symbol, localName) {
41008                     if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
41009                         return context.remappedSymbolNames.get("" + getSymbolId(symbol));
41010                     }
41011                     localName = getNameCandidateWorker(symbol, localName);
41012                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
41013                     context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
41014                     return localName;
41015                 }
41016             }
41017         }
41018         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
41019             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
41020             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
41021             function typePredicateToStringWorker(writer) {
41022                 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
41023                 );
41024                 var printer = ts.createPrinter({ removeComments: true });
41025                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
41026                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
41027                 return writer;
41028             }
41029         }
41030         function formatUnionTypes(types) {
41031             var result = [];
41032             var flags = 0;
41033             for (var i = 0; i < types.length; i++) {
41034                 var t = types[i];
41035                 flags |= t.flags;
41036                 if (!(t.flags & 98304 /* Nullable */)) {
41037                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
41038                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
41039                         if (baseType.flags & 1048576 /* Union */) {
41040                             var count = baseType.types.length;
41041                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
41042                                 result.push(baseType);
41043                                 i += count - 1;
41044                                 continue;
41045                             }
41046                         }
41047                     }
41048                     result.push(t);
41049                 }
41050             }
41051             if (flags & 65536 /* Null */)
41052                 result.push(nullType);
41053             if (flags & 32768 /* Undefined */)
41054                 result.push(undefinedType);
41055             return result || types;
41056         }
41057         function visibilityToString(flags) {
41058             if (flags === 8 /* Private */) {
41059                 return "private";
41060             }
41061             if (flags === 16 /* Protected */) {
41062                 return "protected";
41063             }
41064             return "public";
41065         }
41066         function getTypeAliasForTypeLiteral(type) {
41067             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
41068                 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
41069                 if (node.kind === 247 /* TypeAliasDeclaration */) {
41070                     return getSymbolOfNode(node);
41071                 }
41072             }
41073             return undefined;
41074         }
41075         function isTopLevelInExternalModuleAugmentation(node) {
41076             return node && node.parent &&
41077                 node.parent.kind === 250 /* ModuleBlock */ &&
41078                 ts.isExternalModuleAugmentation(node.parent.parent);
41079         }
41080         function isDefaultBindingContext(location) {
41081             return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
41082         }
41083         function getNameOfSymbolFromNameType(symbol, context) {
41084             var nameType = getSymbolLinks(symbol).nameType;
41085             if (nameType) {
41086                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
41087                     var name = "" + nameType.value;
41088                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
41089                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
41090                     }
41091                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
41092                         return "[" + name + "]";
41093                     }
41094                     return name;
41095                 }
41096                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
41097                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
41098                 }
41099             }
41100         }
41101         /**
41102          * Gets a human-readable name for a symbol.
41103          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
41104          *
41105          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
41106          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
41107          */
41108         function getNameOfSymbolAsWritten(symbol, context) {
41109             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
41110                 // If it's not the first part of an entity name, it must print as `default`
41111                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
41112                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
41113                     !symbol.declarations ||
41114                     // if not in the same binding context (source file, module declaration), it must print as `default`
41115                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
41116                 return "default";
41117             }
41118             if (symbol.declarations && symbol.declarations.length) {
41119                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
41120                 var name_2 = declaration && ts.getNameOfDeclaration(declaration);
41121                 if (declaration && name_2) {
41122                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
41123                         return ts.symbolName(symbol);
41124                     }
41125                     if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
41126                         var nameType = getSymbolLinks(symbol).nameType;
41127                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
41128                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
41129                             var result = getNameOfSymbolFromNameType(symbol, context);
41130                             if (result !== undefined) {
41131                                 return result;
41132                             }
41133                         }
41134                     }
41135                     return ts.declarationNameToString(name_2);
41136                 }
41137                 if (!declaration) {
41138                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
41139                 }
41140                 if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
41141                     return ts.declarationNameToString(declaration.parent.name);
41142                 }
41143                 switch (declaration.kind) {
41144                     case 214 /* ClassExpression */:
41145                     case 201 /* FunctionExpression */:
41146                     case 202 /* ArrowFunction */:
41147                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
41148                             context.encounteredError = true;
41149                         }
41150                         return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
41151                 }
41152             }
41153             var name = getNameOfSymbolFromNameType(symbol, context);
41154             return name !== undefined ? name : ts.symbolName(symbol);
41155         }
41156         function isDeclarationVisible(node) {
41157             if (node) {
41158                 var links = getNodeLinks(node);
41159                 if (links.isVisible === undefined) {
41160                     links.isVisible = !!determineIfDeclarationIsVisible();
41161                 }
41162                 return links.isVisible;
41163             }
41164             return false;
41165             function determineIfDeclarationIsVisible() {
41166                 switch (node.kind) {
41167                     case 315 /* JSDocCallbackTag */:
41168                     case 322 /* JSDocTypedefTag */:
41169                     case 316 /* JSDocEnumTag */:
41170                         // Top-level jsdoc type aliases are considered exported
41171                         // 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
41172                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
41173                     case 191 /* BindingElement */:
41174                         return isDeclarationVisible(node.parent.parent);
41175                     case 242 /* VariableDeclaration */:
41176                         if (ts.isBindingPattern(node.name) &&
41177                             !node.name.elements.length) {
41178                             // If the binding pattern is empty, this variable declaration is not visible
41179                             return false;
41180                         }
41181                     // falls through
41182                     case 249 /* ModuleDeclaration */:
41183                     case 245 /* ClassDeclaration */:
41184                     case 246 /* InterfaceDeclaration */:
41185                     case 247 /* TypeAliasDeclaration */:
41186                     case 244 /* FunctionDeclaration */:
41187                     case 248 /* EnumDeclaration */:
41188                     case 253 /* ImportEqualsDeclaration */:
41189                         // external module augmentation is always visible
41190                         if (ts.isExternalModuleAugmentation(node)) {
41191                             return true;
41192                         }
41193                         var parent = getDeclarationContainer(node);
41194                         // If the node is not exported or it is not ambient module element (except import declaration)
41195                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
41196                             !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
41197                             return isGlobalSourceFile(parent);
41198                         }
41199                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
41200                         return isDeclarationVisible(parent);
41201                     case 159 /* PropertyDeclaration */:
41202                     case 158 /* PropertySignature */:
41203                     case 163 /* GetAccessor */:
41204                     case 164 /* SetAccessor */:
41205                     case 161 /* MethodDeclaration */:
41206                     case 160 /* MethodSignature */:
41207                         if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
41208                             // Private/protected properties/methods are not visible
41209                             return false;
41210                         }
41211                     // Public properties/methods are visible if its parents are visible, so:
41212                     // falls through
41213                     case 162 /* Constructor */:
41214                     case 166 /* ConstructSignature */:
41215                     case 165 /* CallSignature */:
41216                     case 167 /* IndexSignature */:
41217                     case 156 /* Parameter */:
41218                     case 250 /* ModuleBlock */:
41219                     case 170 /* FunctionType */:
41220                     case 171 /* ConstructorType */:
41221                     case 173 /* TypeLiteral */:
41222                     case 169 /* TypeReference */:
41223                     case 174 /* ArrayType */:
41224                     case 175 /* TupleType */:
41225                     case 178 /* UnionType */:
41226                     case 179 /* IntersectionType */:
41227                     case 182 /* ParenthesizedType */:
41228                         return isDeclarationVisible(node.parent);
41229                     // Default binding, import specifier and namespace import is visible
41230                     // only on demand so by default it is not visible
41231                     case 255 /* ImportClause */:
41232                     case 256 /* NamespaceImport */:
41233                     case 258 /* ImportSpecifier */:
41234                         return false;
41235                     // Type parameters are always visible
41236                     case 155 /* TypeParameter */:
41237                     // Source file and namespace export are always visible
41238                     // falls through
41239                     case 290 /* SourceFile */:
41240                     case 252 /* NamespaceExportDeclaration */:
41241                         return true;
41242                     // Export assignments do not create name bindings outside the module
41243                     case 259 /* ExportAssignment */:
41244                         return false;
41245                     default:
41246                         return false;
41247                 }
41248             }
41249         }
41250         function collectLinkedAliases(node, setVisibility) {
41251             var exportSymbol;
41252             if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
41253                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
41254             }
41255             else if (node.parent.kind === 263 /* ExportSpecifier */) {
41256                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
41257             }
41258             var result;
41259             var visited;
41260             if (exportSymbol) {
41261                 visited = ts.createMap();
41262                 visited.set("" + getSymbolId(exportSymbol), true);
41263                 buildVisibleNodeList(exportSymbol.declarations);
41264             }
41265             return result;
41266             function buildVisibleNodeList(declarations) {
41267                 ts.forEach(declarations, function (declaration) {
41268                     var resultNode = getAnyImportSyntax(declaration) || declaration;
41269                     if (setVisibility) {
41270                         getNodeLinks(declaration).isVisible = true;
41271                     }
41272                     else {
41273                         result = result || [];
41274                         ts.pushIfUnique(result, resultNode);
41275                     }
41276                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
41277                         // Add the referenced top container visible
41278                         var internalModuleReference = declaration.moduleReference;
41279                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
41280                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
41281                         var id = importSymbol && "" + getSymbolId(importSymbol);
41282                         if (importSymbol && !visited.has(id)) {
41283                             visited.set(id, true);
41284                             buildVisibleNodeList(importSymbol.declarations);
41285                         }
41286                     }
41287                 });
41288             }
41289         }
41290         /**
41291          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
41292          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
41293          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
41294          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
41295          * In order to see if the same query has already been done before, the target object and the propertyName both
41296          * must match the one passed in.
41297          *
41298          * @param target The symbol, type, or signature whose type is being queried
41299          * @param propertyName The property name that should be used to query the target for its type
41300          */
41301         function pushTypeResolution(target, propertyName) {
41302             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
41303             if (resolutionCycleStartIndex >= 0) {
41304                 // A cycle was found
41305                 var length_3 = resolutionTargets.length;
41306                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
41307                     resolutionResults[i] = false;
41308                 }
41309                 return false;
41310             }
41311             resolutionTargets.push(target);
41312             resolutionResults.push(/*items*/ true);
41313             resolutionPropertyNames.push(propertyName);
41314             return true;
41315         }
41316         function findResolutionCycleStartIndex(target, propertyName) {
41317             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
41318                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
41319                     return -1;
41320                 }
41321                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
41322                     return i;
41323                 }
41324             }
41325             return -1;
41326         }
41327         function hasType(target, propertyName) {
41328             switch (propertyName) {
41329                 case 0 /* Type */:
41330                     return !!getSymbolLinks(target).type;
41331                 case 5 /* EnumTagType */:
41332                     return !!(getNodeLinks(target).resolvedEnumType);
41333                 case 2 /* DeclaredType */:
41334                     return !!getSymbolLinks(target).declaredType;
41335                 case 1 /* ResolvedBaseConstructorType */:
41336                     return !!target.resolvedBaseConstructorType;
41337                 case 3 /* ResolvedReturnType */:
41338                     return !!target.resolvedReturnType;
41339                 case 4 /* ImmediateBaseConstraint */:
41340                     return !!target.immediateBaseConstraint;
41341                 case 6 /* ResolvedTypeArguments */:
41342                     return !!target.resolvedTypeArguments;
41343             }
41344             return ts.Debug.assertNever(propertyName);
41345         }
41346         /**
41347          * Pop an entry from the type resolution stack and return its associated result value. The result value will
41348          * be true if no circularities were detected, or false if a circularity was found.
41349          */
41350         function popTypeResolution() {
41351             resolutionTargets.pop();
41352             resolutionPropertyNames.pop();
41353             return resolutionResults.pop();
41354         }
41355         function getDeclarationContainer(node) {
41356             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
41357                 switch (node.kind) {
41358                     case 242 /* VariableDeclaration */:
41359                     case 243 /* VariableDeclarationList */:
41360                     case 258 /* ImportSpecifier */:
41361                     case 257 /* NamedImports */:
41362                     case 256 /* NamespaceImport */:
41363                     case 255 /* ImportClause */:
41364                         return false;
41365                     default:
41366                         return true;
41367                 }
41368             }).parent;
41369         }
41370         function getTypeOfPrototypeProperty(prototype) {
41371             // TypeScript 1.0 spec (April 2014): 8.4
41372             // Every class automatically contains a static property member named 'prototype',
41373             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
41374             // It is an error to explicitly declare a static property member with the name 'prototype'.
41375             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
41376             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
41377         }
41378         // Return the type of the given property in the given type, or undefined if no such property exists
41379         function getTypeOfPropertyOfType(type, name) {
41380             var prop = getPropertyOfType(type, name);
41381             return prop ? getTypeOfSymbol(prop) : undefined;
41382         }
41383         function getTypeOfPropertyOrIndexSignature(type, name) {
41384             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
41385         }
41386         function isTypeAny(type) {
41387             return type && (type.flags & 1 /* Any */) !== 0;
41388         }
41389         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
41390         // assigned by contextual typing.
41391         function getTypeForBindingElementParent(node) {
41392             var symbol = getSymbolOfNode(node);
41393             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
41394         }
41395         function getRestType(source, properties, symbol) {
41396             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
41397             if (source.flags & 131072 /* Never */) {
41398                 return emptyObjectType;
41399             }
41400             if (source.flags & 1048576 /* Union */) {
41401                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
41402             }
41403             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
41404             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
41405                 if (omitKeyType.flags & 131072 /* Never */) {
41406                     return source;
41407                 }
41408                 var omitTypeAlias = getGlobalOmitSymbol();
41409                 if (!omitTypeAlias) {
41410                     return errorType;
41411                 }
41412                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
41413             }
41414             var members = ts.createSymbolTable();
41415             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
41416                 var prop = _a[_i];
41417                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
41418                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
41419                     && isSpreadableProperty(prop)) {
41420                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
41421                 }
41422             }
41423             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
41424             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
41425             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
41426             result.objectFlags |= 131072 /* ObjectRestType */;
41427             return result;
41428         }
41429         // Determine the control flow type associated with a destructuring declaration or assignment. The following
41430         // forms of destructuring are possible:
41431         //   let { x } = obj;  // BindingElement
41432         //   let [ x ] = obj;  // BindingElement
41433         //   { x } = obj;      // ShorthandPropertyAssignment
41434         //   { x: v } = obj;   // PropertyAssignment
41435         //   [ x ] = obj;      // Expression
41436         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
41437         // flow analyzer doesn't have to handle all the different syntactic forms.
41438         function getFlowTypeOfDestructuring(node, declaredType) {
41439             var reference = getSyntheticElementAccess(node);
41440             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
41441         }
41442         function getSyntheticElementAccess(node) {
41443             var parentAccess = getParentElementAccess(node);
41444             if (parentAccess && parentAccess.flowNode) {
41445                 var propName = getDestructuringPropertyName(node);
41446                 if (propName) {
41447                     var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
41448                     result.parent = node;
41449                     result.expression = parentAccess;
41450                     var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
41451                     literal.parent = result;
41452                     literal.text = propName;
41453                     result.argumentExpression = literal;
41454                     result.flowNode = parentAccess.flowNode;
41455                     return result;
41456                 }
41457             }
41458         }
41459         function getParentElementAccess(node) {
41460             var ancestor = node.parent.parent;
41461             switch (ancestor.kind) {
41462                 case 191 /* BindingElement */:
41463                 case 281 /* PropertyAssignment */:
41464                     return getSyntheticElementAccess(ancestor);
41465                 case 192 /* ArrayLiteralExpression */:
41466                     return getSyntheticElementAccess(node.parent);
41467                 case 242 /* VariableDeclaration */:
41468                     return ancestor.initializer;
41469                 case 209 /* BinaryExpression */:
41470                     return ancestor.right;
41471             }
41472         }
41473         function getDestructuringPropertyName(node) {
41474             var parent = node.parent;
41475             if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
41476                 return getLiteralPropertyNameText(node.propertyName || node.name);
41477             }
41478             if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
41479                 return getLiteralPropertyNameText(node.name);
41480             }
41481             return "" + parent.elements.indexOf(node);
41482         }
41483         function getLiteralPropertyNameText(name) {
41484             var type = getLiteralTypeFromPropertyName(name);
41485             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
41486         }
41487         /** Return the inferred type for a binding element */
41488         function getTypeForBindingElement(declaration) {
41489             var pattern = declaration.parent;
41490             var parentType = getTypeForBindingElementParent(pattern.parent);
41491             // If no type or an any type was inferred for parent, infer that for the binding element
41492             if (!parentType || isTypeAny(parentType)) {
41493                 return parentType;
41494             }
41495             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
41496             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
41497                 parentType = getNonNullableType(parentType);
41498             }
41499             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
41500             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
41501                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
41502             }
41503             var type;
41504             if (pattern.kind === 189 /* ObjectBindingPattern */) {
41505                 if (declaration.dotDotDotToken) {
41506                     parentType = getReducedType(parentType);
41507                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
41508                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
41509                         return errorType;
41510                     }
41511                     var literalMembers = [];
41512                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
41513                         var element = _a[_i];
41514                         if (!element.dotDotDotToken) {
41515                             literalMembers.push(element.propertyName || element.name);
41516                         }
41517                     }
41518                     type = getRestType(parentType, literalMembers, declaration.symbol);
41519                 }
41520                 else {
41521                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
41522                     var name = declaration.propertyName || declaration.name;
41523                     var indexType = getLiteralTypeFromPropertyName(name);
41524                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
41525                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41526                 }
41527             }
41528             else {
41529                 // This elementType will be used if the specific property corresponding to this index is not
41530                 // present (aka the tuple element property). This call also checks that the parentType is in
41531                 // fact an iterable or array (depending on target language).
41532                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
41533                 var index_1 = pattern.elements.indexOf(declaration);
41534                 if (declaration.dotDotDotToken) {
41535                     // If the parent is a tuple type, the rest element has a tuple type of the
41536                     // remaining tuple element types. Otherwise, the rest element has an array type with same
41537                     // element type as the parent type.
41538                     type = everyType(parentType, isTupleType) ?
41539                         mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
41540                         createArrayType(elementType);
41541                 }
41542                 else if (isArrayLikeType(parentType)) {
41543                     var indexType = getLiteralType(index_1);
41544                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
41545                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
41546                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41547                 }
41548                 else {
41549                     type = elementType;
41550                 }
41551             }
41552             if (!declaration.initializer) {
41553                 return type;
41554             }
41555             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
41556                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
41557                 // undefined from the final type.
41558                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
41559                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
41560                     type;
41561             }
41562             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
41563         }
41564         function getTypeForDeclarationFromJSDocComment(declaration) {
41565             var jsdocType = ts.getJSDocType(declaration);
41566             if (jsdocType) {
41567                 return getTypeFromTypeNode(jsdocType);
41568             }
41569             return undefined;
41570         }
41571         function isNullOrUndefined(node) {
41572             var expr = ts.skipParentheses(node);
41573             return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
41574         }
41575         function isEmptyArrayLiteral(node) {
41576             var expr = ts.skipParentheses(node);
41577             return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
41578         }
41579         function addOptionality(type, optional) {
41580             if (optional === void 0) { optional = true; }
41581             return strictNullChecks && optional ? getOptionalType(type) : type;
41582         }
41583         // Return the inferred type for a variable, parameter, or property declaration
41584         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
41585             // A variable declared in a for..in statement is of type string, or of type keyof T when the
41586             // right hand expression is of a type parameter type.
41587             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
41588                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
41589                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
41590             }
41591             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
41592                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
41593                 // missing properties/signatures required to get its iteratedType (like
41594                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
41595                 // or it may have led to an error inside getElementTypeOfIterable.
41596                 var forOfStatement = declaration.parent.parent;
41597                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
41598             }
41599             if (ts.isBindingPattern(declaration.parent)) {
41600                 return getTypeForBindingElement(declaration);
41601             }
41602             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
41603                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
41604             // Use type from type annotation if one is present
41605             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
41606             if (declaredType) {
41607                 return addOptionality(declaredType, isOptional);
41608             }
41609             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
41610                 declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
41611                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
41612                 // If --noImplicitAny is on or the declaration is in a Javascript file,
41613                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
41614                 // initializer or a 'null' or 'undefined' initializer.
41615                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
41616                     return autoType;
41617                 }
41618                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
41619                 // literal initializer.
41620                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
41621                     return autoArrayType;
41622                 }
41623             }
41624             if (declaration.kind === 156 /* Parameter */) {
41625                 var func = declaration.parent;
41626                 // For a parameter of a set accessor, use the type of the get accessor if one is present
41627                 if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
41628                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
41629                     if (getter) {
41630                         var getterSignature = getSignatureFromDeclaration(getter);
41631                         var thisParameter = getAccessorThisParameter(func);
41632                         if (thisParameter && declaration === thisParameter) {
41633                             // Use the type from the *getter*
41634                             ts.Debug.assert(!thisParameter.type);
41635                             return getTypeOfSymbol(getterSignature.thisParameter);
41636                         }
41637                         return getReturnTypeOfSignature(getterSignature);
41638                     }
41639                 }
41640                 if (ts.isInJSFile(declaration)) {
41641                     var typeTag = ts.getJSDocType(func);
41642                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
41643                         return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
41644                     }
41645                 }
41646                 // Use contextual parameter type if one is available
41647                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
41648                 if (type) {
41649                     return addOptionality(type, isOptional);
41650                 }
41651             }
41652             else if (ts.isInJSFile(declaration)) {
41653                 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
41654                 if (containerObjectType) {
41655                     return containerObjectType;
41656                 }
41657             }
41658             // Use the type of the initializer expression if one is present and the declaration is
41659             // not a parameter of a contextually typed function
41660             if (declaration.initializer) {
41661                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
41662                 return addOptionality(type, isOptional);
41663             }
41664             if (ts.isJsxAttribute(declaration)) {
41665                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
41666                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
41667                 return trueType;
41668             }
41669             // If the declaration specifies a binding pattern and is not a parameter of a contextually
41670             // typed function, use the type implied by the binding pattern
41671             if (ts.isBindingPattern(declaration.name)) {
41672                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
41673             }
41674             // No type specified and nothing can be inferred
41675             return undefined;
41676         }
41677         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
41678             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
41679             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
41680             if (container) {
41681                 var tag = ts.getJSDocTypeTag(container);
41682                 if (tag && tag.typeExpression) {
41683                     return getTypeFromTypeNode(tag.typeExpression);
41684                 }
41685                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
41686                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
41687             }
41688             var definedInConstructor = false;
41689             var definedInMethod = false;
41690             var jsdocType;
41691             var types;
41692             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
41693                 var declaration = _a[_i];
41694                 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
41695                     ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
41696                         undefined;
41697                 if (!expression) {
41698                     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
41699                 }
41700                 var kind = ts.isAccessExpression(expression)
41701                     ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
41702                     : ts.getAssignmentDeclarationKind(expression);
41703                 if (kind === 4 /* ThisProperty */) {
41704                     if (isDeclarationInConstructor(expression)) {
41705                         definedInConstructor = true;
41706                     }
41707                     else {
41708                         definedInMethod = true;
41709                     }
41710                 }
41711                 if (!ts.isCallExpression(expression)) {
41712                     jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
41713                 }
41714                 if (!jsdocType) {
41715                     (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
41716                 }
41717             }
41718             var type = jsdocType;
41719             if (!type) {
41720                 if (!ts.length(types)) {
41721                     return errorType; // No types from any declarations :(
41722                 }
41723                 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
41724                 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
41725                 if (definedInMethod) {
41726                     var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
41727                     if (propType) {
41728                         (constructorTypes || (constructorTypes = [])).push(propType);
41729                         definedInConstructor = true;
41730                     }
41731                 }
41732                 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
41733                 type = getUnionType(sourceTypes, 2 /* Subtype */);
41734             }
41735             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
41736             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
41737                 reportImplicitAny(symbol.valueDeclaration, anyType);
41738                 return anyType;
41739             }
41740             return widened;
41741         }
41742         function getJSContainerObjectType(decl, symbol, init) {
41743             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
41744                 return undefined;
41745             }
41746             var exports = ts.createSymbolTable();
41747             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
41748                 var s_2 = getSymbolOfNode(decl);
41749                 if (s_2 && ts.hasEntries(s_2.exports)) {
41750                     mergeSymbolTable(exports, s_2.exports);
41751                 }
41752                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
41753             }
41754             var s = getSymbolOfNode(decl);
41755             if (s && ts.hasEntries(s.exports)) {
41756                 mergeSymbolTable(exports, s.exports);
41757             }
41758             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
41759             type.objectFlags |= 16384 /* JSLiteral */;
41760             return type;
41761         }
41762         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
41763             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
41764             if (typeNode) {
41765                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
41766                 if (!declaredType) {
41767                     return type;
41768                 }
41769                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
41770                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
41771                 }
41772             }
41773             if (symbol.parent) {
41774                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
41775                 if (typeNode_2) {
41776                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
41777                 }
41778             }
41779             return declaredType;
41780         }
41781         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
41782         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
41783             if (ts.isCallExpression(expression)) {
41784                 if (resolvedSymbol) {
41785                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
41786                 }
41787                 var objectLitType = checkExpressionCached(expression.arguments[2]);
41788                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
41789                 if (valueType) {
41790                     return valueType;
41791                 }
41792                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
41793                 if (getFunc) {
41794                     var getSig = getSingleCallSignature(getFunc);
41795                     if (getSig) {
41796                         return getReturnTypeOfSignature(getSig);
41797                     }
41798                 }
41799                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
41800                 if (setFunc) {
41801                     var setSig = getSingleCallSignature(setFunc);
41802                     if (setSig) {
41803                         return getTypeOfFirstParameterOfSignature(setSig);
41804                     }
41805                 }
41806                 return anyType;
41807             }
41808             if (containsSameNamedThisProperty(expression.left, expression.right)) {
41809                 return anyType;
41810             }
41811             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
41812             if (type.flags & 524288 /* Object */ &&
41813                 kind === 2 /* ModuleExports */ &&
41814                 symbol.escapedName === "export=" /* ExportEquals */) {
41815                 var exportedType = resolveStructuredTypeMembers(type);
41816                 var members_4 = ts.createSymbolTable();
41817                 ts.copyEntries(exportedType.members, members_4);
41818                 if (resolvedSymbol && !resolvedSymbol.exports) {
41819                     resolvedSymbol.exports = ts.createSymbolTable();
41820                 }
41821                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
41822                     var _a;
41823                     var exportedMember = members_4.get(name);
41824                     if (exportedMember && exportedMember !== s) {
41825                         if (s.flags & 111551 /* Value */) {
41826                             // If the member has an additional value-like declaration, union the types from the two declarations,
41827                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
41828                             // a pattern like:
41829                             //
41830                             // module.exports = { a: true };
41831                             // module.exports.a = 3;
41832                             //
41833                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
41834                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
41835                             // it's unclear what that's supposed to mean, so it's probably a mistake.
41836                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
41837                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
41838                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
41839                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41840                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41841                             }
41842                             var union = createSymbol(s.flags | exportedMember.flags, name);
41843                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
41844                             union.valueDeclaration = exportedMember.valueDeclaration;
41845                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
41846                             members_4.set(name, union);
41847                         }
41848                         else {
41849                             members_4.set(name, mergeSymbol(s, exportedMember));
41850                         }
41851                     }
41852                     else {
41853                         members_4.set(name, s);
41854                     }
41855                 });
41856                 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
41857                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
41858                 return result;
41859             }
41860             if (isEmptyArrayLiteralType(type)) {
41861                 reportImplicitAny(expression, anyArrayType);
41862                 return anyArrayType;
41863             }
41864             return type;
41865         }
41866         function containsSameNamedThisProperty(thisProperty, expression) {
41867             return ts.isPropertyAccessExpression(thisProperty)
41868                 && thisProperty.expression.kind === 104 /* ThisKeyword */
41869                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
41870         }
41871         function isDeclarationInConstructor(expression) {
41872             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
41873             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
41874             // Function expressions that are assigned to the prototype count as methods.
41875             return thisContainer.kind === 162 /* Constructor */ ||
41876                 thisContainer.kind === 244 /* FunctionDeclaration */ ||
41877                 (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
41878         }
41879         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
41880             ts.Debug.assert(types.length === declarations.length);
41881             return types.filter(function (_, i) {
41882                 var declaration = declarations[i];
41883                 var expression = ts.isBinaryExpression(declaration) ? declaration :
41884                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
41885                 return expression && isDeclarationInConstructor(expression);
41886             });
41887         }
41888         /** check for definition in base class if any declaration is in a class */
41889         function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
41890             var parentDeclaration = ts.forEach(property.declarations, function (d) {
41891                 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
41892                 return ts.isClassLike(parent) && parent;
41893             });
41894             if (parentDeclaration) {
41895                 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
41896                 var baseClassType = classType && getBaseTypes(classType)[0];
41897                 if (baseClassType) {
41898                     return getTypeOfPropertyOfType(baseClassType, property.escapedName);
41899                 }
41900             }
41901         }
41902         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
41903         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
41904         // pattern. Otherwise, it is the type any.
41905         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
41906             if (element.initializer) {
41907                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
41908                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
41909                 // pattern.
41910                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
41911                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
41912             }
41913             if (ts.isBindingPattern(element.name)) {
41914                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
41915             }
41916             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
41917                 reportImplicitAny(element, anyType);
41918             }
41919             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
41920             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
41921             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
41922             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
41923             return includePatternInType ? nonInferrableAnyType : anyType;
41924         }
41925         // Return the type implied by an object binding pattern
41926         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
41927             var members = ts.createSymbolTable();
41928             var stringIndexInfo;
41929             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
41930             ts.forEach(pattern.elements, function (e) {
41931                 var name = e.propertyName || e.name;
41932                 if (e.dotDotDotToken) {
41933                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
41934                     return;
41935                 }
41936                 var exprType = getLiteralTypeFromPropertyName(name);
41937                 if (!isTypeUsableAsPropertyName(exprType)) {
41938                     // do not include computed properties in the implied type
41939                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
41940                     return;
41941                 }
41942                 var text = getPropertyNameFromType(exprType);
41943                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
41944                 var symbol = createSymbol(flags, text);
41945                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
41946                 symbol.bindingElement = e;
41947                 members.set(symbol.escapedName, symbol);
41948             });
41949             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
41950             result.objectFlags |= objectFlags;
41951             if (includePatternInType) {
41952                 result.pattern = pattern;
41953                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41954             }
41955             return result;
41956         }
41957         // Return the type implied by an array binding pattern
41958         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
41959             var elements = pattern.elements;
41960             var lastElement = ts.lastOrUndefined(elements);
41961             var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
41962             if (elements.length === 0 || elements.length === 1 && hasRestElement) {
41963                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
41964             }
41965             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
41966             var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
41967             var result = createTupleType(elementTypes, minLength, hasRestElement);
41968             if (includePatternInType) {
41969                 result = cloneTypeReference(result);
41970                 result.pattern = pattern;
41971                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41972             }
41973             return result;
41974         }
41975         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
41976         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
41977         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
41978         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
41979         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
41980         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
41981         // the parameter.
41982         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
41983             if (includePatternInType === void 0) { includePatternInType = false; }
41984             if (reportErrors === void 0) { reportErrors = false; }
41985             return pattern.kind === 189 /* ObjectBindingPattern */
41986                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
41987                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
41988         }
41989         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
41990         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
41991         // is a bit more involved. For example:
41992         //
41993         //   var [x, s = ""] = [1, "one"];
41994         //
41995         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
41996         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
41997         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
41998         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
41999             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
42000         }
42001         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
42002             if (type) {
42003                 if (reportErrors) {
42004                     reportErrorsFromWidening(declaration, type);
42005                 }
42006                 // always widen a 'unique symbol' type if the type was created for a different declaration.
42007                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
42008                     type = esSymbolType;
42009                 }
42010                 return getWidenedType(type);
42011             }
42012             // Rest parameters default to type any[], other parameters default to type any
42013             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
42014             // Report implicit any errors unless this is a private property within an ambient declaration
42015             if (reportErrors) {
42016                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
42017                     reportImplicitAny(declaration, type);
42018                 }
42019             }
42020             return type;
42021         }
42022         function declarationBelongsToPrivateAmbientMember(declaration) {
42023             var root = ts.getRootDeclaration(declaration);
42024             var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
42025             return isPrivateWithinAmbient(memberDeclaration);
42026         }
42027         function tryGetTypeFromEffectiveTypeNode(declaration) {
42028             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
42029             if (typeNode) {
42030                 return getTypeFromTypeNode(typeNode);
42031             }
42032         }
42033         function getTypeOfVariableOrParameterOrProperty(symbol) {
42034             var links = getSymbolLinks(symbol);
42035             if (!links.type) {
42036                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
42037                 // For a contextually typed parameter it is possible that a type has already
42038                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
42039                 // to preserve this type.
42040                 if (!links.type) {
42041                     links.type = type;
42042                 }
42043             }
42044             return links.type;
42045         }
42046         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
42047             // Handle prototype property
42048             if (symbol.flags & 4194304 /* Prototype */) {
42049                 return getTypeOfPrototypeProperty(symbol);
42050             }
42051             // CommonsJS require and module both have type any.
42052             if (symbol === requireSymbol) {
42053                 return anyType;
42054             }
42055             if (symbol.flags & 134217728 /* ModuleExports */) {
42056                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
42057                 var members = ts.createSymbolTable();
42058                 members.set("exports", fileSymbol);
42059                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
42060             }
42061             // Handle catch clause variables
42062             var declaration = symbol.valueDeclaration;
42063             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
42064                 return anyType;
42065             }
42066             // Handle export default expressions
42067             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
42068                 if (!declaration.statements.length) {
42069                     return emptyObjectType;
42070                 }
42071                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
42072             }
42073             // Handle variable, parameter or property
42074             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42075                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
42076                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
42077                     return getTypeOfFuncClassEnumModule(symbol);
42078                 }
42079                 return reportCircularityError(symbol);
42080             }
42081             var type;
42082             if (declaration.kind === 259 /* ExportAssignment */) {
42083                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
42084             }
42085             else if (ts.isBinaryExpression(declaration) ||
42086                 (ts.isInJSFile(declaration) &&
42087                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
42088                 type = getWidenedTypeForAssignmentDeclaration(symbol);
42089             }
42090             else if (ts.isJSDocPropertyLikeTag(declaration)
42091                 || ts.isPropertyAccessExpression(declaration)
42092                 || ts.isElementAccessExpression(declaration)
42093                 || ts.isIdentifier(declaration)
42094                 || ts.isStringLiteralLike(declaration)
42095                 || ts.isNumericLiteral(declaration)
42096                 || ts.isClassDeclaration(declaration)
42097                 || ts.isFunctionDeclaration(declaration)
42098                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
42099                 || ts.isMethodSignature(declaration)
42100                 || ts.isSourceFile(declaration)) {
42101                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
42102                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42103                     return getTypeOfFuncClassEnumModule(symbol);
42104                 }
42105                 type = ts.isBinaryExpression(declaration.parent) ?
42106                     getWidenedTypeForAssignmentDeclaration(symbol) :
42107                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
42108             }
42109             else if (ts.isPropertyAssignment(declaration)) {
42110                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
42111             }
42112             else if (ts.isJsxAttribute(declaration)) {
42113                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
42114             }
42115             else if (ts.isShorthandPropertyAssignment(declaration)) {
42116                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
42117             }
42118             else if (ts.isObjectLiteralMethod(declaration)) {
42119                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
42120             }
42121             else if (ts.isParameter(declaration)
42122                 || ts.isPropertyDeclaration(declaration)
42123                 || ts.isPropertySignature(declaration)
42124                 || ts.isVariableDeclaration(declaration)
42125                 || ts.isBindingElement(declaration)) {
42126                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
42127             }
42128             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
42129             // Re-dispatch based on valueDeclaration.kind instead.
42130             else if (ts.isEnumDeclaration(declaration)) {
42131                 type = getTypeOfFuncClassEnumModule(symbol);
42132             }
42133             else if (ts.isEnumMember(declaration)) {
42134                 type = getTypeOfEnumMember(symbol);
42135             }
42136             else if (ts.isAccessor(declaration)) {
42137                 type = resolveTypeOfAccessors(symbol);
42138             }
42139             else {
42140                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
42141             }
42142             if (!popTypeResolution()) {
42143                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
42144                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
42145                     return getTypeOfFuncClassEnumModule(symbol);
42146                 }
42147                 return reportCircularityError(symbol);
42148             }
42149             return type;
42150         }
42151         function getAnnotatedAccessorTypeNode(accessor) {
42152             if (accessor) {
42153                 if (accessor.kind === 163 /* GetAccessor */) {
42154                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
42155                     return getterTypeAnnotation;
42156                 }
42157                 else {
42158                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
42159                     return setterTypeAnnotation;
42160                 }
42161             }
42162             return undefined;
42163         }
42164         function getAnnotatedAccessorType(accessor) {
42165             var node = getAnnotatedAccessorTypeNode(accessor);
42166             return node && getTypeFromTypeNode(node);
42167         }
42168         function getAnnotatedAccessorThisParameter(accessor) {
42169             var parameter = getAccessorThisParameter(accessor);
42170             return parameter && parameter.symbol;
42171         }
42172         function getThisTypeOfDeclaration(declaration) {
42173             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
42174         }
42175         function getTypeOfAccessors(symbol) {
42176             var links = getSymbolLinks(symbol);
42177             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
42178         }
42179         function getTypeOfAccessorsWorker(symbol) {
42180             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42181                 return errorType;
42182             }
42183             var type = resolveTypeOfAccessors(symbol);
42184             if (!popTypeResolution()) {
42185                 type = anyType;
42186                 if (noImplicitAny) {
42187                     var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42188                     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));
42189                 }
42190             }
42191             return type;
42192         }
42193         function resolveTypeOfAccessors(symbol) {
42194             var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42195             var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
42196             if (getter && ts.isInJSFile(getter)) {
42197                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
42198                 if (jsDocType) {
42199                     return jsDocType;
42200                 }
42201             }
42202             // First try to see if the user specified a return type on the get-accessor.
42203             var getterReturnType = getAnnotatedAccessorType(getter);
42204             if (getterReturnType) {
42205                 return getterReturnType;
42206             }
42207             else {
42208                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
42209                 var setterParameterType = getAnnotatedAccessorType(setter);
42210                 if (setterParameterType) {
42211                     return setterParameterType;
42212                 }
42213                 else {
42214                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
42215                     if (getter && getter.body) {
42216                         return getReturnTypeFromBody(getter);
42217                     }
42218                     // Otherwise, fall back to 'any'.
42219                     else {
42220                         if (setter) {
42221                             if (!isPrivateWithinAmbient(setter)) {
42222                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
42223                             }
42224                         }
42225                         else {
42226                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
42227                             if (!isPrivateWithinAmbient(getter)) {
42228                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
42229                             }
42230                         }
42231                         return anyType;
42232                     }
42233                 }
42234             }
42235         }
42236         function getBaseTypeVariableOfClass(symbol) {
42237             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
42238             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
42239                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
42240                     undefined;
42241         }
42242         function getTypeOfFuncClassEnumModule(symbol) {
42243             var links = getSymbolLinks(symbol);
42244             var originalLinks = links;
42245             if (!links.type) {
42246                 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
42247                 if (jsDeclaration) {
42248                     var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
42249                     if (merged) {
42250                         // note:we overwrite links because we just cloned the symbol
42251                         symbol = links = merged;
42252                     }
42253                 }
42254                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
42255             }
42256             return links.type;
42257         }
42258         function getTypeOfFuncClassEnumModuleWorker(symbol) {
42259             var declaration = symbol.valueDeclaration;
42260             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
42261                 return anyType;
42262             }
42263             else if (declaration && (declaration.kind === 209 /* BinaryExpression */ ||
42264                 ts.isAccessExpression(declaration) &&
42265                     declaration.parent.kind === 209 /* BinaryExpression */)) {
42266                 return getWidenedTypeForAssignmentDeclaration(symbol);
42267             }
42268             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
42269                 var resolvedModule = resolveExternalModuleSymbol(symbol);
42270                 if (resolvedModule !== symbol) {
42271                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
42272                         return errorType;
42273                     }
42274                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
42275                     var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
42276                     if (!popTypeResolution()) {
42277                         return reportCircularityError(symbol);
42278                     }
42279                     return type_1;
42280                 }
42281             }
42282             var type = createObjectType(16 /* Anonymous */, symbol);
42283             if (symbol.flags & 32 /* Class */) {
42284                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
42285                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
42286             }
42287             else {
42288                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
42289             }
42290         }
42291         function getTypeOfEnumMember(symbol) {
42292             var links = getSymbolLinks(symbol);
42293             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
42294         }
42295         function getTypeOfAlias(symbol) {
42296             var links = getSymbolLinks(symbol);
42297             if (!links.type) {
42298                 var targetSymbol = resolveAlias(symbol);
42299                 // It only makes sense to get the type of a value symbol. If the result of resolving
42300                 // the alias is not a value, then it has no type. To get the type associated with a
42301                 // type symbol, call getDeclaredTypeOfSymbol.
42302                 // This check is important because without it, a call to getTypeOfSymbol could end
42303                 // up recursively calling getTypeOfAlias, causing a stack overflow.
42304                 links.type = targetSymbol.flags & 111551 /* Value */
42305                     ? getTypeOfSymbol(targetSymbol)
42306                     : errorType;
42307             }
42308             return links.type;
42309         }
42310         function getTypeOfInstantiatedSymbol(symbol) {
42311             var links = getSymbolLinks(symbol);
42312             if (!links.type) {
42313                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
42314                     return links.type = errorType;
42315                 }
42316                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
42317                 if (!popTypeResolution()) {
42318                     type = reportCircularityError(symbol);
42319                 }
42320                 links.type = type;
42321             }
42322             return links.type;
42323         }
42324         function reportCircularityError(symbol) {
42325             var declaration = symbol.valueDeclaration;
42326             // Check if variable has type annotation that circularly references the variable itself
42327             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
42328                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
42329                 return errorType;
42330             }
42331             // Check if variable has initializer that circularly references the variable itself
42332             if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
42333                 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));
42334             }
42335             // Circularities could also result from parameters in function expressions that end up
42336             // having themselves as contextual types following type argument inference. In those cases
42337             // we have already reported an implicit any error so we don't report anything here.
42338             return anyType;
42339         }
42340         function getTypeOfSymbolWithDeferredType(symbol) {
42341             var links = getSymbolLinks(symbol);
42342             if (!links.type) {
42343                 ts.Debug.assertIsDefined(links.deferralParent);
42344                 ts.Debug.assertIsDefined(links.deferralConstituents);
42345                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
42346             }
42347             return links.type;
42348         }
42349         function getTypeOfSymbol(symbol) {
42350             var checkFlags = ts.getCheckFlags(symbol);
42351             if (checkFlags & 65536 /* DeferredType */) {
42352                 return getTypeOfSymbolWithDeferredType(symbol);
42353             }
42354             if (checkFlags & 1 /* Instantiated */) {
42355                 return getTypeOfInstantiatedSymbol(symbol);
42356             }
42357             if (checkFlags & 262144 /* Mapped */) {
42358                 return getTypeOfMappedSymbol(symbol);
42359             }
42360             if (checkFlags & 8192 /* ReverseMapped */) {
42361                 return getTypeOfReverseMappedSymbol(symbol);
42362             }
42363             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
42364                 return getTypeOfVariableOrParameterOrProperty(symbol);
42365             }
42366             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42367                 return getTypeOfFuncClassEnumModule(symbol);
42368             }
42369             if (symbol.flags & 8 /* EnumMember */) {
42370                 return getTypeOfEnumMember(symbol);
42371             }
42372             if (symbol.flags & 98304 /* Accessor */) {
42373                 return getTypeOfAccessors(symbol);
42374             }
42375             if (symbol.flags & 2097152 /* Alias */) {
42376                 return getTypeOfAlias(symbol);
42377             }
42378             return errorType;
42379         }
42380         function isReferenceToType(type, target) {
42381             return type !== undefined
42382                 && target !== undefined
42383                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
42384                 && type.target === target;
42385         }
42386         function getTargetType(type) {
42387             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
42388         }
42389         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
42390         function hasBaseType(type, checkBase) {
42391             return check(type);
42392             function check(type) {
42393                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
42394                     var target = getTargetType(type);
42395                     return target === checkBase || ts.some(getBaseTypes(target), check);
42396                 }
42397                 else if (type.flags & 2097152 /* Intersection */) {
42398                     return ts.some(type.types, check);
42399                 }
42400                 return false;
42401             }
42402         }
42403         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
42404         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
42405         // in-place and returns the same array.
42406         function appendTypeParameters(typeParameters, declarations) {
42407             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
42408                 var declaration = declarations_2[_i];
42409                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
42410             }
42411             return typeParameters;
42412         }
42413         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
42414         function getOuterTypeParameters(node, includeThisTypes) {
42415             while (true) {
42416                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
42417                 if (node && ts.isBinaryExpression(node)) {
42418                     // prototype assignments get the outer type parameters of their constructor function
42419                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42420                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
42421                         var symbol = getSymbolOfNode(node.left);
42422                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
42423                             node = symbol.parent.valueDeclaration;
42424                         }
42425                     }
42426                 }
42427                 if (!node) {
42428                     return undefined;
42429                 }
42430                 switch (node.kind) {
42431                     case 225 /* VariableStatement */:
42432                     case 245 /* ClassDeclaration */:
42433                     case 214 /* ClassExpression */:
42434                     case 246 /* InterfaceDeclaration */:
42435                     case 165 /* CallSignature */:
42436                     case 166 /* ConstructSignature */:
42437                     case 160 /* MethodSignature */:
42438                     case 170 /* FunctionType */:
42439                     case 171 /* ConstructorType */:
42440                     case 300 /* JSDocFunctionType */:
42441                     case 244 /* FunctionDeclaration */:
42442                     case 161 /* MethodDeclaration */:
42443                     case 201 /* FunctionExpression */:
42444                     case 202 /* ArrowFunction */:
42445                     case 247 /* TypeAliasDeclaration */:
42446                     case 321 /* JSDocTemplateTag */:
42447                     case 322 /* JSDocTypedefTag */:
42448                     case 316 /* JSDocEnumTag */:
42449                     case 315 /* JSDocCallbackTag */:
42450                     case 186 /* MappedType */:
42451                     case 180 /* ConditionalType */:
42452                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
42453                         if (node.kind === 186 /* MappedType */) {
42454                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
42455                         }
42456                         else if (node.kind === 180 /* ConditionalType */) {
42457                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
42458                         }
42459                         else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) {
42460                             break;
42461                         }
42462                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
42463                         var thisType = includeThisTypes &&
42464                             (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
42465                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
42466                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
42467                 }
42468             }
42469         }
42470         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
42471         function getOuterTypeParametersOfClassOrInterface(symbol) {
42472             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
42473             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
42474             return getOuterTypeParameters(declaration);
42475         }
42476         // The local type parameters are the combined set of type parameters from all declarations of the class,
42477         // interface, or type alias.
42478         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
42479             var result;
42480             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42481                 var node = _a[_i];
42482                 if (node.kind === 246 /* InterfaceDeclaration */ ||
42483                     node.kind === 245 /* ClassDeclaration */ ||
42484                     node.kind === 214 /* ClassExpression */ ||
42485                     isJSConstructor(node) ||
42486                     ts.isTypeAlias(node)) {
42487                     var declaration = node;
42488                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
42489                 }
42490             }
42491             return result;
42492         }
42493         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
42494         // its locally declared type parameters.
42495         function getTypeParametersOfClassOrInterface(symbol) {
42496             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
42497         }
42498         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
42499         // rest parameter of type any[].
42500         function isMixinConstructorType(type) {
42501             var signatures = getSignaturesOfType(type, 1 /* Construct */);
42502             if (signatures.length === 1) {
42503                 var s = signatures[0];
42504                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
42505             }
42506             return false;
42507         }
42508         function isConstructorType(type) {
42509             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
42510                 return true;
42511             }
42512             if (type.flags & 8650752 /* TypeVariable */) {
42513                 var constraint = getBaseConstraintOfType(type);
42514                 return !!constraint && isMixinConstructorType(constraint);
42515             }
42516             return false;
42517         }
42518         function getBaseTypeNodeOfClass(type) {
42519             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
42520         }
42521         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42522             var typeArgCount = ts.length(typeArgumentNodes);
42523             var isJavascript = ts.isInJSFile(location);
42524             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
42525         }
42526         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42527             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
42528             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
42529             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
42530         }
42531         /**
42532          * The base constructor of a class can resolve to
42533          * * undefinedType if the class has no extends clause,
42534          * * unknownType if an error occurred during resolution of the extends expression,
42535          * * nullType if the extends expression is the null value,
42536          * * anyType if the extends expression has type any, or
42537          * * an object type with at least one construct signature.
42538          */
42539         function getBaseConstructorTypeOfClass(type) {
42540             if (!type.resolvedBaseConstructorType) {
42541                 var decl = type.symbol.valueDeclaration;
42542                 var extended = ts.getEffectiveBaseTypeNode(decl);
42543                 var baseTypeNode = getBaseTypeNodeOfClass(type);
42544                 if (!baseTypeNode) {
42545                     return type.resolvedBaseConstructorType = undefinedType;
42546                 }
42547                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
42548                     return errorType;
42549                 }
42550                 var baseConstructorType = checkExpression(baseTypeNode.expression);
42551                 if (extended && baseTypeNode !== extended) {
42552                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
42553                     checkExpression(extended.expression);
42554                 }
42555                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
42556                     // Resolving the members of a class requires us to resolve the base class of that class.
42557                     // We force resolution here such that we catch circularities now.
42558                     resolveStructuredTypeMembers(baseConstructorType);
42559                 }
42560                 if (!popTypeResolution()) {
42561                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
42562                     return type.resolvedBaseConstructorType = errorType;
42563                 }
42564                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
42565                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
42566                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
42567                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
42568                         var ctorReturn = unknownType;
42569                         if (constraint) {
42570                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
42571                             if (ctorSig[0]) {
42572                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
42573                             }
42574                         }
42575                         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)));
42576                     }
42577                     return type.resolvedBaseConstructorType = errorType;
42578                 }
42579                 type.resolvedBaseConstructorType = baseConstructorType;
42580             }
42581             return type.resolvedBaseConstructorType;
42582         }
42583         function getImplementsTypes(type) {
42584             var resolvedImplementsTypes = ts.emptyArray;
42585             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42586                 var declaration = _a[_i];
42587                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
42588                 if (!implementsTypeNodes)
42589                     continue;
42590                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
42591                     var node = implementsTypeNodes_1[_b];
42592                     var implementsType = getTypeFromTypeNode(node);
42593                     if (implementsType !== errorType) {
42594                         if (resolvedImplementsTypes === ts.emptyArray) {
42595                             resolvedImplementsTypes = [implementsType];
42596                         }
42597                         else {
42598                             resolvedImplementsTypes.push(implementsType);
42599                         }
42600                     }
42601                 }
42602             }
42603             return resolvedImplementsTypes;
42604         }
42605         function getBaseTypes(type) {
42606             if (!type.resolvedBaseTypes) {
42607                 if (type.objectFlags & 8 /* Tuple */) {
42608                     type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
42609                 }
42610                 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42611                     if (type.symbol.flags & 32 /* Class */) {
42612                         resolveBaseTypesOfClass(type);
42613                     }
42614                     if (type.symbol.flags & 64 /* Interface */) {
42615                         resolveBaseTypesOfInterface(type);
42616                     }
42617                 }
42618                 else {
42619                     ts.Debug.fail("type must be class or interface");
42620                 }
42621             }
42622             return type.resolvedBaseTypes;
42623         }
42624         function resolveBaseTypesOfClass(type) {
42625             type.resolvedBaseTypes = ts.resolvingEmptyArray;
42626             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
42627             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
42628                 return type.resolvedBaseTypes = ts.emptyArray;
42629             }
42630             var baseTypeNode = getBaseTypeNodeOfClass(type);
42631             var baseType;
42632             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
42633             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
42634                 areAllOuterTypeParametersApplied(originalBaseType)) {
42635                 // 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
42636                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
42637                 // type arguments in the same manner as a type reference to get the same error reporting experience.
42638                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
42639             }
42640             else if (baseConstructorType.flags & 1 /* Any */) {
42641                 baseType = baseConstructorType;
42642             }
42643             else {
42644                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
42645                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
42646                 // we check that all instantiated signatures return the same type.
42647                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
42648                 if (!constructors.length) {
42649                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
42650                     return type.resolvedBaseTypes = ts.emptyArray;
42651                 }
42652                 baseType = getReturnTypeOfSignature(constructors[0]);
42653             }
42654             if (baseType === errorType) {
42655                 return type.resolvedBaseTypes = ts.emptyArray;
42656             }
42657             var reducedBaseType = getReducedType(baseType);
42658             if (!isValidBaseType(reducedBaseType)) {
42659                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
42660                 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));
42661                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
42662                 return type.resolvedBaseTypes = ts.emptyArray;
42663             }
42664             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
42665                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42666                 return type.resolvedBaseTypes = ts.emptyArray;
42667             }
42668             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
42669                 // Circular reference, likely through instantiation of default parameters
42670                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
42671                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
42672                 // partial instantiation of the members without the base types fully resolved
42673                 type.members = undefined;
42674             }
42675             return type.resolvedBaseTypes = [reducedBaseType];
42676         }
42677         function areAllOuterTypeParametersApplied(type) {
42678             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
42679             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
42680             var outerTypeParameters = type.outerTypeParameters;
42681             if (outerTypeParameters) {
42682                 var last_1 = outerTypeParameters.length - 1;
42683                 var typeArguments = getTypeArguments(type);
42684                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
42685             }
42686             return true;
42687         }
42688         // A valid base type is `any`, an object type or intersection of object types.
42689         function isValidBaseType(type) {
42690             if (type.flags & 262144 /* TypeParameter */) {
42691                 var constraint = getBaseConstraintOfType(type);
42692                 if (constraint) {
42693                     return isValidBaseType(constraint);
42694                 }
42695             }
42696             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
42697             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
42698             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
42699                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
42700         }
42701         function resolveBaseTypesOfInterface(type) {
42702             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
42703             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42704                 var declaration = _a[_i];
42705                 if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
42706                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
42707                         var node = _c[_b];
42708                         var baseType = getReducedType(getTypeFromTypeNode(node));
42709                         if (baseType !== errorType) {
42710                             if (isValidBaseType(baseType)) {
42711                                 if (type !== baseType && !hasBaseType(baseType, type)) {
42712                                     if (type.resolvedBaseTypes === ts.emptyArray) {
42713                                         type.resolvedBaseTypes = [baseType];
42714                                     }
42715                                     else {
42716                                         type.resolvedBaseTypes.push(baseType);
42717                                     }
42718                                 }
42719                                 else {
42720                                     error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42721                                 }
42722                             }
42723                             else {
42724                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
42725                             }
42726                         }
42727                     }
42728                 }
42729             }
42730         }
42731         /**
42732          * Returns true if the interface given by the symbol is free of "this" references.
42733          *
42734          * Specifically, the result is true if the interface itself contains no references
42735          * to "this" in its body, if all base types are interfaces,
42736          * and if none of the base interfaces have a "this" type.
42737          */
42738         function isThislessInterface(symbol) {
42739             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42740                 var declaration = _a[_i];
42741                 if (declaration.kind === 246 /* InterfaceDeclaration */) {
42742                     if (declaration.flags & 128 /* ContainsThis */) {
42743                         return false;
42744                     }
42745                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
42746                     if (baseTypeNodes) {
42747                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
42748                             var node = baseTypeNodes_1[_b];
42749                             if (ts.isEntityNameExpression(node.expression)) {
42750                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
42751                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
42752                                     return false;
42753                                 }
42754                             }
42755                         }
42756                     }
42757                 }
42758             }
42759             return true;
42760         }
42761         function getDeclaredTypeOfClassOrInterface(symbol) {
42762             var links = getSymbolLinks(symbol);
42763             var originalLinks = links;
42764             if (!links.declaredType) {
42765                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
42766                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
42767                 if (merged) {
42768                     // note:we overwrite links because we just cloned the symbol
42769                     symbol = links = merged;
42770                 }
42771                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
42772                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
42773                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42774                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
42775                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
42776                 // property types inferred from initializers and method return types inferred from return statements are very hard
42777                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
42778                 // "this" references.
42779                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
42780                     type.objectFlags |= 4 /* Reference */;
42781                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
42782                     type.outerTypeParameters = outerTypeParameters;
42783                     type.localTypeParameters = localTypeParameters;
42784                     type.instantiations = ts.createMap();
42785                     type.instantiations.set(getTypeListId(type.typeParameters), type);
42786                     type.target = type;
42787                     type.resolvedTypeArguments = type.typeParameters;
42788                     type.thisType = createTypeParameter(symbol);
42789                     type.thisType.isThisType = true;
42790                     type.thisType.constraint = type;
42791                 }
42792             }
42793             return links.declaredType;
42794         }
42795         function getDeclaredTypeOfTypeAlias(symbol) {
42796             var links = getSymbolLinks(symbol);
42797             if (!links.declaredType) {
42798                 // Note that we use the links object as the target here because the symbol object is used as the unique
42799                 // identity for resolution of the 'type' property in SymbolLinks.
42800                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
42801                     return errorType;
42802                 }
42803                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
42804                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
42805                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
42806                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
42807                 if (popTypeResolution()) {
42808                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42809                     if (typeParameters) {
42810                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
42811                         // an instantiation of the type alias with the type parameters supplied as type arguments.
42812                         links.typeParameters = typeParameters;
42813                         links.instantiations = ts.createMap();
42814                         links.instantiations.set(getTypeListId(typeParameters), type);
42815                     }
42816                 }
42817                 else {
42818                     type = errorType;
42819                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
42820                 }
42821                 links.declaredType = type;
42822             }
42823             return links.declaredType;
42824         }
42825         function isStringConcatExpression(expr) {
42826             if (ts.isStringLiteralLike(expr)) {
42827                 return true;
42828             }
42829             else if (expr.kind === 209 /* BinaryExpression */) {
42830                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
42831             }
42832             return false;
42833         }
42834         function isLiteralEnumMember(member) {
42835             var expr = member.initializer;
42836             if (!expr) {
42837                 return !(member.flags & 8388608 /* Ambient */);
42838             }
42839             switch (expr.kind) {
42840                 case 10 /* StringLiteral */:
42841                 case 8 /* NumericLiteral */:
42842                 case 14 /* NoSubstitutionTemplateLiteral */:
42843                     return true;
42844                 case 207 /* PrefixUnaryExpression */:
42845                     return expr.operator === 40 /* MinusToken */ &&
42846                         expr.operand.kind === 8 /* NumericLiteral */;
42847                 case 75 /* Identifier */:
42848                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
42849                 case 209 /* BinaryExpression */:
42850                     return isStringConcatExpression(expr);
42851                 default:
42852                     return false;
42853             }
42854         }
42855         function getEnumKind(symbol) {
42856             var links = getSymbolLinks(symbol);
42857             if (links.enumKind !== undefined) {
42858                 return links.enumKind;
42859             }
42860             var hasNonLiteralMember = false;
42861             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42862                 var declaration = _a[_i];
42863                 if (declaration.kind === 248 /* EnumDeclaration */) {
42864                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42865                         var member = _c[_b];
42866                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
42867                             return links.enumKind = 1 /* Literal */;
42868                         }
42869                         if (!isLiteralEnumMember(member)) {
42870                             hasNonLiteralMember = true;
42871                         }
42872                     }
42873                 }
42874             }
42875             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
42876         }
42877         function getBaseTypeOfEnumLiteralType(type) {
42878             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
42879         }
42880         function getDeclaredTypeOfEnum(symbol) {
42881             var links = getSymbolLinks(symbol);
42882             if (links.declaredType) {
42883                 return links.declaredType;
42884             }
42885             if (getEnumKind(symbol) === 1 /* Literal */) {
42886                 enumCount++;
42887                 var memberTypeList = [];
42888                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42889                     var declaration = _a[_i];
42890                     if (declaration.kind === 248 /* EnumDeclaration */) {
42891                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42892                             var member = _c[_b];
42893                             var value = getEnumMemberValue(member);
42894                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
42895                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
42896                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
42897                         }
42898                     }
42899                 }
42900                 if (memberTypeList.length) {
42901                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
42902                     if (enumType_1.flags & 1048576 /* Union */) {
42903                         enumType_1.flags |= 1024 /* EnumLiteral */;
42904                         enumType_1.symbol = symbol;
42905                     }
42906                     return links.declaredType = enumType_1;
42907                 }
42908             }
42909             var enumType = createType(32 /* Enum */);
42910             enumType.symbol = symbol;
42911             return links.declaredType = enumType;
42912         }
42913         function getDeclaredTypeOfEnumMember(symbol) {
42914             var links = getSymbolLinks(symbol);
42915             if (!links.declaredType) {
42916                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
42917                 if (!links.declaredType) {
42918                     links.declaredType = enumType;
42919                 }
42920             }
42921             return links.declaredType;
42922         }
42923         function getDeclaredTypeOfTypeParameter(symbol) {
42924             var links = getSymbolLinks(symbol);
42925             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
42926         }
42927         function getDeclaredTypeOfAlias(symbol) {
42928             var links = getSymbolLinks(symbol);
42929             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
42930         }
42931         function getDeclaredTypeOfSymbol(symbol) {
42932             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
42933         }
42934         function tryGetDeclaredTypeOfSymbol(symbol) {
42935             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42936                 return getDeclaredTypeOfClassOrInterface(symbol);
42937             }
42938             if (symbol.flags & 524288 /* TypeAlias */) {
42939                 return getDeclaredTypeOfTypeAlias(symbol);
42940             }
42941             if (symbol.flags & 262144 /* TypeParameter */) {
42942                 return getDeclaredTypeOfTypeParameter(symbol);
42943             }
42944             if (symbol.flags & 384 /* Enum */) {
42945                 return getDeclaredTypeOfEnum(symbol);
42946             }
42947             if (symbol.flags & 8 /* EnumMember */) {
42948                 return getDeclaredTypeOfEnumMember(symbol);
42949             }
42950             if (symbol.flags & 2097152 /* Alias */) {
42951                 return getDeclaredTypeOfAlias(symbol);
42952             }
42953             return undefined;
42954         }
42955         /**
42956          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
42957          * literal type, an array with an element type that is free of this references, or a type reference that is
42958          * free of this references.
42959          */
42960         function isThislessType(node) {
42961             switch (node.kind) {
42962                 case 125 /* AnyKeyword */:
42963                 case 148 /* UnknownKeyword */:
42964                 case 143 /* StringKeyword */:
42965                 case 140 /* NumberKeyword */:
42966                 case 151 /* BigIntKeyword */:
42967                 case 128 /* BooleanKeyword */:
42968                 case 144 /* SymbolKeyword */:
42969                 case 141 /* ObjectKeyword */:
42970                 case 110 /* VoidKeyword */:
42971                 case 146 /* UndefinedKeyword */:
42972                 case 100 /* NullKeyword */:
42973                 case 137 /* NeverKeyword */:
42974                 case 187 /* LiteralType */:
42975                     return true;
42976                 case 174 /* ArrayType */:
42977                     return isThislessType(node.elementType);
42978                 case 169 /* TypeReference */:
42979                     return !node.typeArguments || node.typeArguments.every(isThislessType);
42980             }
42981             return false;
42982         }
42983         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
42984         function isThislessTypeParameter(node) {
42985             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
42986             return !constraint || isThislessType(constraint);
42987         }
42988         /**
42989          * A variable-like declaration is free of this references if it has a type annotation
42990          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
42991          */
42992         function isThislessVariableLikeDeclaration(node) {
42993             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
42994             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
42995         }
42996         /**
42997          * A function-like declaration is considered free of `this` references if it has a return type
42998          * annotation that is free of this references and if each parameter is thisless and if
42999          * each type parameter (if present) is thisless.
43000          */
43001         function isThislessFunctionLikeDeclaration(node) {
43002             var returnType = ts.getEffectiveReturnTypeNode(node);
43003             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
43004             return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
43005                 node.parameters.every(isThislessVariableLikeDeclaration) &&
43006                 typeParameters.every(isThislessTypeParameter);
43007         }
43008         /**
43009          * Returns true if the class or interface member given by the symbol is free of "this" references. The
43010          * function may return false for symbols that are actually free of "this" references because it is not
43011          * feasible to perform a complete analysis in all cases. In particular, property members with types
43012          * inferred from their initializers and function members with inferred return types are conservatively
43013          * assumed not to be free of "this" references.
43014          */
43015         function isThisless(symbol) {
43016             if (symbol.declarations && symbol.declarations.length === 1) {
43017                 var declaration = symbol.declarations[0];
43018                 if (declaration) {
43019                     switch (declaration.kind) {
43020                         case 159 /* PropertyDeclaration */:
43021                         case 158 /* PropertySignature */:
43022                             return isThislessVariableLikeDeclaration(declaration);
43023                         case 161 /* MethodDeclaration */:
43024                         case 160 /* MethodSignature */:
43025                         case 162 /* Constructor */:
43026                         case 163 /* GetAccessor */:
43027                         case 164 /* SetAccessor */:
43028                             return isThislessFunctionLikeDeclaration(declaration);
43029                     }
43030                 }
43031             }
43032             return false;
43033         }
43034         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
43035         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
43036         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
43037             var result = ts.createSymbolTable();
43038             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
43039                 var symbol = symbols_2[_i];
43040                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
43041             }
43042             return result;
43043         }
43044         function addInheritedMembers(symbols, baseSymbols) {
43045             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
43046                 var s = baseSymbols_1[_i];
43047                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
43048                     symbols.set(s.escapedName, s);
43049                 }
43050             }
43051         }
43052         function isStaticPrivateIdentifierProperty(s) {
43053             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
43054         }
43055         function resolveDeclaredMembers(type) {
43056             if (!type.declaredProperties) {
43057                 var symbol = type.symbol;
43058                 var members = getMembersOfSymbol(symbol);
43059                 type.declaredProperties = getNamedMembers(members);
43060                 // Start with signatures at empty array in case of recursive types
43061                 type.declaredCallSignatures = ts.emptyArray;
43062                 type.declaredConstructSignatures = ts.emptyArray;
43063                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43064                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43065                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43066                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43067             }
43068             return type;
43069         }
43070         /**
43071          * Indicates whether a type can be used as a property name.
43072          */
43073         function isTypeUsableAsPropertyName(type) {
43074             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
43075         }
43076         /**
43077          * Indicates whether a declaration name is definitely late-bindable.
43078          * A declaration name is only late-bindable if:
43079          * - It is a `ComputedPropertyName`.
43080          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
43081          * `ElementAccessExpression` consisting only of these same three types of nodes.
43082          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
43083          */
43084         function isLateBindableName(node) {
43085             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
43086                 return false;
43087             }
43088             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
43089             return ts.isEntityNameExpression(expr)
43090                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
43091         }
43092         function isLateBoundName(name) {
43093             return name.charCodeAt(0) === 95 /* _ */ &&
43094                 name.charCodeAt(1) === 95 /* _ */ &&
43095                 name.charCodeAt(2) === 64 /* at */;
43096         }
43097         /**
43098          * Indicates whether a declaration has a late-bindable dynamic name.
43099          */
43100         function hasLateBindableName(node) {
43101             var name = ts.getNameOfDeclaration(node);
43102             return !!name && isLateBindableName(name);
43103         }
43104         /**
43105          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
43106          */
43107         function hasNonBindableDynamicName(node) {
43108             return ts.hasDynamicName(node) && !hasLateBindableName(node);
43109         }
43110         /**
43111          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
43112          */
43113         function isNonBindableDynamicName(node) {
43114             return ts.isDynamicName(node) && !isLateBindableName(node);
43115         }
43116         /**
43117          * Gets the symbolic name for a member from its type.
43118          */
43119         function getPropertyNameFromType(type) {
43120             if (type.flags & 8192 /* UniqueESSymbol */) {
43121                 return type.escapedName;
43122             }
43123             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
43124                 return ts.escapeLeadingUnderscores("" + type.value);
43125             }
43126             return ts.Debug.fail();
43127         }
43128         /**
43129          * Adds a declaration to a late-bound dynamic member. This performs the same function for
43130          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
43131          * members.
43132          */
43133         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
43134             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
43135             symbol.flags |= symbolFlags;
43136             getSymbolLinks(member.symbol).lateSymbol = symbol;
43137             if (!symbol.declarations) {
43138                 symbol.declarations = [member];
43139             }
43140             else {
43141                 symbol.declarations.push(member);
43142             }
43143             if (symbolFlags & 111551 /* Value */) {
43144                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
43145                     symbol.valueDeclaration = member;
43146                 }
43147             }
43148         }
43149         /**
43150          * Performs late-binding of a dynamic member. This performs the same function for
43151          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
43152          * members.
43153          *
43154          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
43155          * binding phase to attempt to resolve the name for the symbol from the type of the computed
43156          * property's expression. If the type of the expression is a string-literal, numeric-literal,
43157          * or unique symbol type, we can use that type as the name of the symbol.
43158          *
43159          * For example, given:
43160          *
43161          *   const x = Symbol();
43162          *
43163          *   interface I {
43164          *     [x]: number;
43165          *   }
43166          *
43167          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
43168          * In the late-binding phase we can type-check the expression `x` and see that it has a
43169          * unique symbol type which we can then use as the name of the member. This allows users
43170          * to define custom symbols that can be used in the members of an object type.
43171          *
43172          * @param parent The containing symbol for the member.
43173          * @param earlySymbols The early-bound symbols of the parent.
43174          * @param lateSymbols The late-bound symbols of the parent.
43175          * @param decl The member to bind.
43176          */
43177         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
43178             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
43179             var links = getNodeLinks(decl);
43180             if (!links.resolvedSymbol) {
43181                 // In the event we attempt to resolve the late-bound name of this member recursively,
43182                 // fall back to the early-bound name of this member.
43183                 links.resolvedSymbol = decl.symbol;
43184                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
43185                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
43186                 if (isTypeUsableAsPropertyName(type)) {
43187                     var memberName = getPropertyNameFromType(type);
43188                     var symbolFlags = decl.symbol.flags;
43189                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
43190                     var lateSymbol = lateSymbols.get(memberName);
43191                     if (!lateSymbol)
43192                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
43193                     // Report an error if a late-bound member has the same name as an early-bound member,
43194                     // or if we have another early-bound symbol declaration with the same name and
43195                     // conflicting flags.
43196                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
43197                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
43198                         // If we have an existing early-bound member, combine its declarations so that we can
43199                         // report an error at each declaration.
43200                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
43201                         var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
43202                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
43203                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
43204                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
43205                     }
43206                     lateSymbol.nameType = type;
43207                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
43208                     if (lateSymbol.parent) {
43209                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
43210                     }
43211                     else {
43212                         lateSymbol.parent = parent;
43213                     }
43214                     return links.resolvedSymbol = lateSymbol;
43215                 }
43216             }
43217             return links.resolvedSymbol;
43218         }
43219         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
43220             var links = getSymbolLinks(symbol);
43221             if (!links[resolutionKind]) {
43222                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
43223                 var earlySymbols = !isStatic ? symbol.members :
43224                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
43225                         symbol.exports;
43226                 // In the event we recursively resolve the members/exports of the symbol, we
43227                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
43228                 // members/exports of the symbol.
43229                 links[resolutionKind] = earlySymbols || emptySymbols;
43230                 // fill in any as-yet-unresolved late-bound members.
43231                 var lateSymbols = ts.createSymbolTable();
43232                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43233                     var decl = _a[_i];
43234                     var members = ts.getMembersOfDeclaration(decl);
43235                     if (members) {
43236                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
43237                             var member = members_5[_b];
43238                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
43239                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
43240                             }
43241                         }
43242                     }
43243                 }
43244                 var assignments = symbol.assignmentDeclarationMembers;
43245                 if (assignments) {
43246                     var decls = ts.arrayFrom(assignments.values());
43247                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
43248                         var member = decls_1[_c];
43249                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
43250                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
43251                             || assignmentKind === 4 /* ThisProperty */
43252                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
43253                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
43254                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
43255                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
43256                         }
43257                     }
43258                 }
43259                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
43260             }
43261             return links[resolutionKind];
43262         }
43263         /**
43264          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
43265          *
43266          * For a description of late-binding, see `lateBindMember`.
43267          */
43268         function getMembersOfSymbol(symbol) {
43269             return symbol.flags & 6256 /* LateBindingContainer */
43270                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
43271                 : symbol.members || emptySymbols;
43272         }
43273         /**
43274          * If a symbol is the dynamic name of the member of an object type, get the late-bound
43275          * symbol of the member.
43276          *
43277          * For a description of late-binding, see `lateBindMember`.
43278          */
43279         function getLateBoundSymbol(symbol) {
43280             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
43281                 var links = getSymbolLinks(symbol);
43282                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
43283                     // force late binding of members/exports. This will set the late-bound symbol
43284                     var parent = getMergedSymbol(symbol.parent);
43285                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
43286                         getExportsOfSymbol(parent);
43287                     }
43288                     else {
43289                         getMembersOfSymbol(parent);
43290                     }
43291                 }
43292                 return links.lateSymbol || (links.lateSymbol = symbol);
43293             }
43294             return symbol;
43295         }
43296         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
43297             if (ts.getObjectFlags(type) & 4 /* Reference */) {
43298                 var target = type.target;
43299                 var typeArguments = getTypeArguments(type);
43300                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
43301                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
43302                     return needApparentType ? getApparentType(ref) : ref;
43303                 }
43304             }
43305             else if (type.flags & 2097152 /* Intersection */) {
43306                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
43307             }
43308             return needApparentType ? getApparentType(type) : type;
43309         }
43310         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
43311             var mapper;
43312             var members;
43313             var callSignatures;
43314             var constructSignatures;
43315             var stringIndexInfo;
43316             var numberIndexInfo;
43317             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
43318                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
43319                 callSignatures = source.declaredCallSignatures;
43320                 constructSignatures = source.declaredConstructSignatures;
43321                 stringIndexInfo = source.declaredStringIndexInfo;
43322                 numberIndexInfo = source.declaredNumberIndexInfo;
43323             }
43324             else {
43325                 mapper = createTypeMapper(typeParameters, typeArguments);
43326                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
43327                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
43328                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
43329                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
43330                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
43331             }
43332             var baseTypes = getBaseTypes(source);
43333             if (baseTypes.length) {
43334                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
43335                     members = ts.createSymbolTable(source.declaredProperties);
43336                 }
43337                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43338                 var thisArgument = ts.lastOrUndefined(typeArguments);
43339                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
43340                     var baseType = baseTypes_1[_i];
43341                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
43342                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
43343                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
43344                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
43345                     if (!stringIndexInfo) {
43346                         stringIndexInfo = instantiatedBaseType === anyType ?
43347                             createIndexInfo(anyType, /*isReadonly*/ false) :
43348                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
43349                     }
43350                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
43351                 }
43352             }
43353             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43354         }
43355         function resolveClassOrInterfaceMembers(type) {
43356             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
43357         }
43358         function resolveTypeReferenceMembers(type) {
43359             var source = resolveDeclaredMembers(type.target);
43360             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
43361             var typeArguments = getTypeArguments(type);
43362             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
43363             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
43364         }
43365         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
43366             var sig = new Signature(checker, flags);
43367             sig.declaration = declaration;
43368             sig.typeParameters = typeParameters;
43369             sig.parameters = parameters;
43370             sig.thisParameter = thisParameter;
43371             sig.resolvedReturnType = resolvedReturnType;
43372             sig.resolvedTypePredicate = resolvedTypePredicate;
43373             sig.minArgumentCount = minArgumentCount;
43374             sig.target = undefined;
43375             sig.mapper = undefined;
43376             sig.unionSignatures = undefined;
43377             return sig;
43378         }
43379         function cloneSignature(sig) {
43380             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
43381             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
43382             result.target = sig.target;
43383             result.mapper = sig.mapper;
43384             result.unionSignatures = sig.unionSignatures;
43385             return result;
43386         }
43387         function createUnionSignature(signature, unionSignatures) {
43388             var result = cloneSignature(signature);
43389             result.unionSignatures = unionSignatures;
43390             result.target = undefined;
43391             result.mapper = undefined;
43392             return result;
43393         }
43394         function getOptionalCallSignature(signature, callChainFlags) {
43395             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
43396                 return signature;
43397             }
43398             if (!signature.optionalCallSignatureCache) {
43399                 signature.optionalCallSignatureCache = {};
43400             }
43401             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
43402             return signature.optionalCallSignatureCache[key]
43403                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
43404         }
43405         function createOptionalCallSignature(signature, callChainFlags) {
43406             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.");
43407             var result = cloneSignature(signature);
43408             result.flags |= callChainFlags;
43409             return result;
43410         }
43411         function getExpandedParameters(sig) {
43412             if (signatureHasRestParameter(sig)) {
43413                 var restIndex_1 = sig.parameters.length - 1;
43414                 var restParameter = sig.parameters[restIndex_1];
43415                 var restType = getTypeOfSymbol(restParameter);
43416                 if (isTupleType(restType)) {
43417                     var elementTypes = getTypeArguments(restType);
43418                     var minLength_1 = restType.target.minLength;
43419                     var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
43420                     var restParams = ts.map(elementTypes, function (t, i) {
43421                         var name = getParameterNameAtPosition(sig, restIndex_1 + i);
43422                         var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
43423                             i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
43424                         var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
43425                         symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
43426                         return symbol;
43427                     });
43428                     return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
43429                 }
43430             }
43431             return sig.parameters;
43432         }
43433         function getDefaultConstructSignatures(classType) {
43434             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43435             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
43436             if (baseSignatures.length === 0) {
43437                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
43438             }
43439             var baseTypeNode = getBaseTypeNodeOfClass(classType);
43440             var isJavaScript = ts.isInJSFile(baseTypeNode);
43441             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
43442             var typeArgCount = ts.length(typeArguments);
43443             var result = [];
43444             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
43445                 var baseSig = baseSignatures_1[_i];
43446                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
43447                 var typeParamCount = ts.length(baseSig.typeParameters);
43448                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
43449                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
43450                     sig.typeParameters = classType.localTypeParameters;
43451                     sig.resolvedReturnType = classType;
43452                     result.push(sig);
43453                 }
43454             }
43455             return result;
43456         }
43457         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
43458             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
43459                 var s = signatureList_1[_i];
43460                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
43461                     return s;
43462                 }
43463             }
43464         }
43465         function findMatchingSignatures(signatureLists, signature, listIndex) {
43466             if (signature.typeParameters) {
43467                 // We require an exact match for generic signatures, so we only return signatures from the first
43468                 // signature list and only if they have exact matches in the other signature lists.
43469                 if (listIndex > 0) {
43470                     return undefined;
43471                 }
43472                 for (var i = 1; i < signatureLists.length; i++) {
43473                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
43474                         return undefined;
43475                     }
43476                 }
43477                 return [signature];
43478             }
43479             var result;
43480             for (var i = 0; i < signatureLists.length; i++) {
43481                 // Allow matching non-generic signatures to have excess parameters and different return types.
43482                 // Prefer matching this types if possible.
43483                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
43484                 if (!match) {
43485                     return undefined;
43486                 }
43487                 result = ts.appendIfUnique(result, match);
43488             }
43489             return result;
43490         }
43491         // The signatures of a union type are those signatures that are present in each of the constituent types.
43492         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
43493         // parameters and may differ in return types. When signatures differ in return types, the resulting return
43494         // type is the union of the constituent return types.
43495         function getUnionSignatures(signatureLists) {
43496             var result;
43497             var indexWithLengthOverOne;
43498             for (var i = 0; i < signatureLists.length; i++) {
43499                 if (signatureLists[i].length === 0)
43500                     return ts.emptyArray;
43501                 if (signatureLists[i].length > 1) {
43502                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
43503                 }
43504                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
43505                     var signature = _a[_i];
43506                     // Only process signatures with parameter lists that aren't already in the result list
43507                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
43508                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
43509                         if (unionSignatures) {
43510                             var s = signature;
43511                             // Union the result types when more than one signature matches
43512                             if (unionSignatures.length > 1) {
43513                                 var thisParameter = signature.thisParameter;
43514                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
43515                                 if (firstThisParameterOfUnionSignatures) {
43516                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
43517                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
43518                                 }
43519                                 s = createUnionSignature(signature, unionSignatures);
43520                                 s.thisParameter = thisParameter;
43521                             }
43522                             (result || (result = [])).push(s);
43523                         }
43524                     }
43525                 }
43526             }
43527             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
43528                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
43529                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
43530                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
43531                 // signatures from the type, whose ordering would be non-obvious)
43532                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
43533                 var results = masterList.slice();
43534                 var _loop_9 = function (signatures) {
43535                     if (signatures !== masterList) {
43536                         var signature_1 = signatures[0];
43537                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
43538                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
43539                         if (!results) {
43540                             return "break";
43541                         }
43542                     }
43543                 };
43544                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
43545                     var signatures = signatureLists_1[_b];
43546                     var state_3 = _loop_9(signatures);
43547                     if (state_3 === "break")
43548                         break;
43549                 }
43550                 result = results;
43551             }
43552             return result || ts.emptyArray;
43553         }
43554         function combineUnionThisParam(left, right) {
43555             if (!left || !right) {
43556                 return left || right;
43557             }
43558             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
43559             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
43560             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
43561             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
43562             return createSymbolWithType(left, thisType);
43563         }
43564         function combineUnionParameters(left, right) {
43565             var leftCount = getParameterCount(left);
43566             var rightCount = getParameterCount(right);
43567             var longest = leftCount >= rightCount ? left : right;
43568             var shorter = longest === left ? right : left;
43569             var longestCount = longest === left ? leftCount : rightCount;
43570             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
43571             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
43572             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
43573             for (var i = 0; i < longestCount; i++) {
43574                 var longestParamType = tryGetTypeAtPosition(longest, i);
43575                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
43576                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
43577                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
43578                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
43579                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
43580                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
43581                 var paramName = leftName === rightName ? leftName :
43582                     !leftName ? rightName :
43583                         !rightName ? leftName :
43584                             undefined;
43585                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
43586                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
43587                 params[i] = paramSymbol;
43588             }
43589             if (needsExtraRestElement) {
43590                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
43591                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
43592                 params[longestCount] = restParamSymbol;
43593             }
43594             return params;
43595         }
43596         function combineSignaturesOfUnionMembers(left, right) {
43597             var declaration = left.declaration;
43598             var params = combineUnionParameters(left, right);
43599             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
43600             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
43601             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
43602             /*resolvedReturnType*/ undefined, 
43603             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
43604             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
43605             return result;
43606         }
43607         function getUnionIndexInfo(types, kind) {
43608             var indexTypes = [];
43609             var isAnyReadonly = false;
43610             for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
43611                 var type = types_3[_i];
43612                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
43613                 if (!indexInfo) {
43614                     return undefined;
43615                 }
43616                 indexTypes.push(indexInfo.type);
43617                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
43618             }
43619             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
43620         }
43621         function resolveUnionTypeMembers(type) {
43622             // The members and properties collections are empty for union types. To get all properties of a union
43623             // type use getPropertiesOfType (only the language service uses this).
43624             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
43625             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
43626             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
43627             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
43628             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43629         }
43630         function intersectTypes(type1, type2) {
43631             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
43632         }
43633         function intersectIndexInfos(info1, info2) {
43634             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
43635         }
43636         function unionSpreadIndexInfos(info1, info2) {
43637             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
43638         }
43639         function findMixins(types) {
43640             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
43641             var mixinFlags = ts.map(types, isMixinConstructorType);
43642             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
43643                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
43644                 mixinFlags[firstMixinIndex] = false;
43645             }
43646             return mixinFlags;
43647         }
43648         function includeMixinType(type, types, mixinFlags, index) {
43649             var mixedTypes = [];
43650             for (var i = 0; i < types.length; i++) {
43651                 if (i === index) {
43652                     mixedTypes.push(type);
43653                 }
43654                 else if (mixinFlags[i]) {
43655                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
43656                 }
43657             }
43658             return getIntersectionType(mixedTypes);
43659         }
43660         function resolveIntersectionTypeMembers(type) {
43661             // The members and properties collections are empty for intersection types. To get all properties of an
43662             // intersection type use getPropertiesOfType (only the language service uses this).
43663             var callSignatures;
43664             var constructSignatures;
43665             var stringIndexInfo;
43666             var numberIndexInfo;
43667             var types = type.types;
43668             var mixinFlags = findMixins(types);
43669             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
43670             var _loop_10 = function (i) {
43671                 var t = type.types[i];
43672                 // When an intersection type contains mixin constructor types, the construct signatures from
43673                 // those types are discarded and their return types are mixed into the return types of all
43674                 // other construct signatures in the intersection type. For example, the intersection type
43675                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
43676                 // 'new(s: string) => A & B'.
43677                 if (!mixinFlags[i]) {
43678                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
43679                     if (signatures.length && mixinCount > 0) {
43680                         signatures = ts.map(signatures, function (s) {
43681                             var clone = cloneSignature(s);
43682                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
43683                             return clone;
43684                         });
43685                     }
43686                     constructSignatures = appendSignatures(constructSignatures, signatures);
43687                 }
43688                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
43689                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
43690                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
43691             };
43692             for (var i = 0; i < types.length; i++) {
43693                 _loop_10(i);
43694             }
43695             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
43696         }
43697         function appendSignatures(signatures, newSignatures) {
43698             var _loop_11 = function (sig) {
43699                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
43700                     signatures = ts.append(signatures, sig);
43701                 }
43702             };
43703             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
43704                 var sig = newSignatures_1[_i];
43705                 _loop_11(sig);
43706             }
43707             return signatures;
43708         }
43709         /**
43710          * Converts an AnonymousType to a ResolvedType.
43711          */
43712         function resolveAnonymousTypeMembers(type) {
43713             var symbol = getMergedSymbol(type.symbol);
43714             if (type.target) {
43715                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43716                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
43717                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
43718                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
43719                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
43720                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
43721                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43722             }
43723             else if (symbol.flags & 2048 /* TypeLiteral */) {
43724                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43725                 var members = getMembersOfSymbol(symbol);
43726                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43727                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43728                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43729                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43730                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43731             }
43732             else {
43733                 // Combinations of function, class, enum and module
43734                 var members = emptySymbols;
43735                 var stringIndexInfo = void 0;
43736                 if (symbol.exports) {
43737                     members = getExportsOfSymbol(symbol);
43738                     if (symbol === globalThisSymbol) {
43739                         var varsOnly_1 = ts.createMap();
43740                         members.forEach(function (p) {
43741                             if (!(p.flags & 418 /* BlockScoped */)) {
43742                                 varsOnly_1.set(p.escapedName, p);
43743                             }
43744                         });
43745                         members = varsOnly_1;
43746                     }
43747                 }
43748                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
43749                 if (symbol.flags & 32 /* Class */) {
43750                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
43751                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43752                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
43753                         members = ts.createSymbolTable(getNamedMembers(members));
43754                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
43755                     }
43756                     else if (baseConstructorType === anyType) {
43757                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
43758                     }
43759                 }
43760                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
43761                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
43762                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43763                 // We resolve the members before computing the signatures because a signature may use
43764                 // typeof with a qualified name expression that circularly references the type we are
43765                 // in the process of resolving (see issue #6072). The temporarily empty signature list
43766                 // will never be observed because a qualified name can't reference signatures.
43767                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
43768                     type.callSignatures = getSignaturesOfSymbol(symbol);
43769                 }
43770                 // And likewise for construct signatures for classes
43771                 if (symbol.flags & 32 /* Class */) {
43772                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
43773                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
43774                     if (symbol.flags & 16 /* Function */) {
43775                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
43776                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
43777                             undefined; }));
43778                     }
43779                     if (!constructSignatures.length) {
43780                         constructSignatures = getDefaultConstructSignatures(classType_1);
43781                     }
43782                     type.constructSignatures = constructSignatures;
43783                 }
43784             }
43785         }
43786         function resolveReverseMappedTypeMembers(type) {
43787             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
43788             var modifiers = getMappedTypeModifiers(type.mappedType);
43789             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
43790             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
43791             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
43792             var members = ts.createSymbolTable();
43793             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
43794                 var prop = _a[_i];
43795                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
43796                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
43797                 inferredProp.declarations = prop.declarations;
43798                 inferredProp.nameType = getSymbolLinks(prop).nameType;
43799                 inferredProp.propertyType = getTypeOfSymbol(prop);
43800                 inferredProp.mappedType = type.mappedType;
43801                 inferredProp.constraintType = type.constraintType;
43802                 members.set(prop.escapedName, inferredProp);
43803             }
43804             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
43805         }
43806         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
43807         // bound includes those keys that are known to always be present, for example because
43808         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
43809         function getLowerBoundOfKeyType(type) {
43810             if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
43811                 return type;
43812             }
43813             if (type.flags & 4194304 /* Index */) {
43814                 return getIndexType(getApparentType(type.type));
43815             }
43816             if (type.flags & 16777216 /* Conditional */) {
43817                 if (type.root.isDistributive) {
43818                     var checkType = type.checkType;
43819                     var constraint = getLowerBoundOfKeyType(checkType);
43820                     if (constraint !== checkType) {
43821                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43822                     }
43823                 }
43824                 return type;
43825             }
43826             if (type.flags & 1048576 /* Union */) {
43827                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43828             }
43829             if (type.flags & 2097152 /* Intersection */) {
43830                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43831             }
43832             return neverType;
43833         }
43834         /** Resolve the members of a mapped type { [P in K]: T } */
43835         function resolveMappedTypeMembers(type) {
43836             var members = ts.createSymbolTable();
43837             var stringIndexInfo;
43838             var numberIndexInfo;
43839             // Resolve upfront such that recursive references see an empty object type.
43840             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43841             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
43842             // and T as the template type.
43843             var typeParameter = getTypeParameterFromMappedType(type);
43844             var constraintType = getConstraintTypeFromMappedType(type);
43845             var templateType = getTemplateTypeFromMappedType(type.target || type);
43846             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
43847             var templateModifiers = getMappedTypeModifiers(type);
43848             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
43849             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43850                 // We have a { [P in keyof T]: X }
43851                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
43852                     var prop = _a[_i];
43853                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
43854                 }
43855                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
43856                     addMemberForKeyType(stringType);
43857                 }
43858                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
43859                     addMemberForKeyType(numberType);
43860                 }
43861             }
43862             else {
43863                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
43864             }
43865             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43866             function addMemberForKeyType(t) {
43867                 // Create a mapper from T to the current iteration type constituent. Then, if the
43868                 // mapped type is itself an instantiated type, combine the iteration mapper with the
43869                 // instantiation mapper.
43870                 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
43871                 // If the current iteration type constituent is a string literal type, create a property.
43872                 // Otherwise, for type string create a string index signature.
43873                 if (isTypeUsableAsPropertyName(t)) {
43874                     var propName = getPropertyNameFromType(t);
43875                     var modifiersProp = getPropertyOfType(modifiersType, propName);
43876                     var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
43877                         !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
43878                     var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
43879                         !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
43880                     var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
43881                     var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
43882                     prop.mappedType = type;
43883                     prop.mapper = templateMapper;
43884                     if (modifiersProp) {
43885                         prop.syntheticOrigin = modifiersProp;
43886                         prop.declarations = modifiersProp.declarations;
43887                     }
43888                     prop.nameType = t;
43889                     members.set(propName, prop);
43890                 }
43891                 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
43892                     var propType = instantiateType(templateType, templateMapper);
43893                     if (t.flags & (1 /* Any */ | 4 /* String */)) {
43894                         stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43895                     }
43896                     else {
43897                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43898                     }
43899                 }
43900             }
43901         }
43902         function getTypeOfMappedSymbol(symbol) {
43903             if (!symbol.type) {
43904                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
43905                     return errorType;
43906                 }
43907                 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
43908                 var propType = instantiateType(templateType, symbol.mapper);
43909                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
43910                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
43911                 // mode, if the underlying property is optional we remove 'undefined' from the type.
43912                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
43913                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
43914                         propType;
43915                 if (!popTypeResolution()) {
43916                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
43917                     type = errorType;
43918                 }
43919                 symbol.type = type;
43920                 symbol.mapper = undefined;
43921             }
43922             return symbol.type;
43923         }
43924         function getTypeParameterFromMappedType(type) {
43925             return type.typeParameter ||
43926                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
43927         }
43928         function getConstraintTypeFromMappedType(type) {
43929             return type.constraintType ||
43930                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
43931         }
43932         function getTemplateTypeFromMappedType(type) {
43933             return type.templateType ||
43934                 (type.templateType = type.declaration.type ?
43935                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
43936                     errorType);
43937         }
43938         function getConstraintDeclarationForMappedType(type) {
43939             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
43940         }
43941         function isMappedTypeWithKeyofConstraintDeclaration(type) {
43942             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
43943             return constraintDeclaration.kind === 184 /* TypeOperator */ &&
43944                 constraintDeclaration.operator === 134 /* KeyOfKeyword */;
43945         }
43946         function getModifiersTypeFromMappedType(type) {
43947             if (!type.modifiersType) {
43948                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43949                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
43950                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
43951                     // 'keyof T' to a literal union type and we can't recover T from that type.
43952                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
43953                 }
43954                 else {
43955                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
43956                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
43957                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
43958                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
43959                     var constraint = getConstraintTypeFromMappedType(declaredType);
43960                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
43961                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
43962                 }
43963             }
43964             return type.modifiersType;
43965         }
43966         function getMappedTypeModifiers(type) {
43967             var declaration = type.declaration;
43968             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
43969                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
43970         }
43971         function getMappedTypeOptionality(type) {
43972             var modifiers = getMappedTypeModifiers(type);
43973             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
43974         }
43975         function getCombinedMappedTypeOptionality(type) {
43976             var optionality = getMappedTypeOptionality(type);
43977             var modifiersType = getModifiersTypeFromMappedType(type);
43978             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
43979         }
43980         function isPartialMappedType(type) {
43981             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
43982         }
43983         function isGenericMappedType(type) {
43984             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
43985         }
43986         function resolveStructuredTypeMembers(type) {
43987             if (!type.members) {
43988                 if (type.flags & 524288 /* Object */) {
43989                     if (type.objectFlags & 4 /* Reference */) {
43990                         resolveTypeReferenceMembers(type);
43991                     }
43992                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
43993                         resolveClassOrInterfaceMembers(type);
43994                     }
43995                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
43996                         resolveReverseMappedTypeMembers(type);
43997                     }
43998                     else if (type.objectFlags & 16 /* Anonymous */) {
43999                         resolveAnonymousTypeMembers(type);
44000                     }
44001                     else if (type.objectFlags & 32 /* Mapped */) {
44002                         resolveMappedTypeMembers(type);
44003                     }
44004                 }
44005                 else if (type.flags & 1048576 /* Union */) {
44006                     resolveUnionTypeMembers(type);
44007                 }
44008                 else if (type.flags & 2097152 /* Intersection */) {
44009                     resolveIntersectionTypeMembers(type);
44010                 }
44011             }
44012             return type;
44013         }
44014         /** Return properties of an object type or an empty array for other types */
44015         function getPropertiesOfObjectType(type) {
44016             if (type.flags & 524288 /* Object */) {
44017                 return resolveStructuredTypeMembers(type).properties;
44018             }
44019             return ts.emptyArray;
44020         }
44021         /** If the given type is an object type and that type has a property by the given name,
44022          * return the symbol for that property. Otherwise return undefined.
44023          */
44024         function getPropertyOfObjectType(type, name) {
44025             if (type.flags & 524288 /* Object */) {
44026                 var resolved = resolveStructuredTypeMembers(type);
44027                 var symbol = resolved.members.get(name);
44028                 if (symbol && symbolIsValue(symbol)) {
44029                     return symbol;
44030                 }
44031             }
44032         }
44033         function getPropertiesOfUnionOrIntersectionType(type) {
44034             if (!type.resolvedProperties) {
44035                 var members = ts.createSymbolTable();
44036                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
44037                     var current = _a[_i];
44038                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
44039                         var prop = _c[_b];
44040                         if (!members.has(prop.escapedName)) {
44041                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
44042                             if (combinedProp) {
44043                                 members.set(prop.escapedName, combinedProp);
44044                             }
44045                         }
44046                     }
44047                     // The properties of a union type are those that are present in all constituent types, so
44048                     // we only need to check the properties of the first type without index signature
44049                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
44050                         break;
44051                     }
44052                 }
44053                 type.resolvedProperties = getNamedMembers(members);
44054             }
44055             return type.resolvedProperties;
44056         }
44057         function getPropertiesOfType(type) {
44058             type = getReducedApparentType(type);
44059             return type.flags & 3145728 /* UnionOrIntersection */ ?
44060                 getPropertiesOfUnionOrIntersectionType(type) :
44061                 getPropertiesOfObjectType(type);
44062         }
44063         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
44064             var list = obj.properties;
44065             return list.some(function (property) {
44066                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
44067                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
44068                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
44069                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
44070             });
44071         }
44072         function getAllPossiblePropertiesOfTypes(types) {
44073             var unionType = getUnionType(types);
44074             if (!(unionType.flags & 1048576 /* Union */)) {
44075                 return getAugmentedPropertiesOfType(unionType);
44076             }
44077             var props = ts.createSymbolTable();
44078             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
44079                 var memberType = types_4[_i];
44080                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
44081                     var escapedName = _b[_a].escapedName;
44082                     if (!props.has(escapedName)) {
44083                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
44084                         // May be undefined if the property is private
44085                         if (prop)
44086                             props.set(escapedName, prop);
44087                     }
44088                 }
44089             }
44090             return ts.arrayFrom(props.values());
44091         }
44092         function getConstraintOfType(type) {
44093             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
44094                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
44095                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
44096                         getBaseConstraintOfType(type);
44097         }
44098         function getConstraintOfTypeParameter(typeParameter) {
44099             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
44100         }
44101         function getConstraintOfIndexedAccess(type) {
44102             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
44103         }
44104         function getSimplifiedTypeOrConstraint(type) {
44105             var simplified = getSimplifiedType(type, /*writing*/ false);
44106             return simplified !== type ? simplified : getConstraintOfType(type);
44107         }
44108         function getConstraintFromIndexedAccess(type) {
44109             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
44110             if (indexConstraint && indexConstraint !== type.indexType) {
44111                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
44112                 if (indexedAccess) {
44113                     return indexedAccess;
44114                 }
44115             }
44116             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
44117             if (objectConstraint && objectConstraint !== type.objectType) {
44118                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
44119             }
44120             return undefined;
44121         }
44122         function getDefaultConstraintOfConditionalType(type) {
44123             if (!type.resolvedDefaultConstraint) {
44124                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
44125                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
44126                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
44127                 // in effect treating `any` like `never` rather than `unknown` in this location.
44128                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
44129                 var falseConstraint = getFalseTypeFromConditionalType(type);
44130                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
44131             }
44132             return type.resolvedDefaultConstraint;
44133         }
44134         function getConstraintOfDistributiveConditionalType(type) {
44135             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
44136             // type parameter. If so, create an instantiation of the conditional type where T is replaced
44137             // with its constraint. We do this because if the constraint is a union type it will be distributed
44138             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
44139             // removes 'undefined' from T.
44140             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
44141             // as the constraint for all type params (check type included) have been replace with `unknown`, which
44142             // is going to produce even more false positive/negative results than the distribute constraint already does.
44143             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
44144             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
44145             // likely doesn't need to exist.
44146             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
44147                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
44148                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
44149                 if (constraint && constraint !== type.checkType) {
44150                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
44151                     if (!(instantiated.flags & 131072 /* Never */)) {
44152                         return instantiated;
44153                     }
44154                 }
44155             }
44156             return undefined;
44157         }
44158         function getConstraintFromConditionalType(type) {
44159             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
44160         }
44161         function getConstraintOfConditionalType(type) {
44162             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
44163         }
44164         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
44165             var constraints;
44166             var hasDisjointDomainType = false;
44167             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
44168                 var t = types_5[_i];
44169                 if (t.flags & 63176704 /* Instantiable */) {
44170                     // We keep following constraints as long as we have an instantiable type that is known
44171                     // not to be circular or infinite (hence we stop on index access types).
44172                     var constraint = getConstraintOfType(t);
44173                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
44174                         constraint = getConstraintOfType(constraint);
44175                     }
44176                     if (constraint) {
44177                         constraints = ts.append(constraints, constraint);
44178                         if (targetIsUnion) {
44179                             constraints = ts.append(constraints, t);
44180                         }
44181                     }
44182                 }
44183                 else if (t.flags & 67238908 /* DisjointDomains */) {
44184                     hasDisjointDomainType = true;
44185                 }
44186             }
44187             // If the target is a union type or if we are intersecting with types belonging to one of the
44188             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
44189             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
44190                 if (hasDisjointDomainType) {
44191                     // We add any types belong to one of the disjoint domains because they might cause the final
44192                     // intersection operation to reduce the union constraints.
44193                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
44194                         var t = types_6[_a];
44195                         if (t.flags & 67238908 /* DisjointDomains */) {
44196                             constraints = ts.append(constraints, t);
44197                         }
44198                     }
44199                 }
44200                 return getIntersectionType(constraints);
44201             }
44202             return undefined;
44203         }
44204         function getBaseConstraintOfType(type) {
44205             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
44206                 var constraint = getResolvedBaseConstraint(type);
44207                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
44208             }
44209             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
44210         }
44211         /**
44212          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
44213          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
44214          */
44215         function getBaseConstraintOrType(type) {
44216             return getBaseConstraintOfType(type) || type;
44217         }
44218         function hasNonCircularBaseConstraint(type) {
44219             return getResolvedBaseConstraint(type) !== circularConstraintType;
44220         }
44221         /**
44222          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
44223          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
44224          * circularly references the type variable.
44225          */
44226         function getResolvedBaseConstraint(type) {
44227             var nonTerminating = false;
44228             return type.resolvedBaseConstraint ||
44229                 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
44230             function getImmediateBaseConstraint(t) {
44231                 if (!t.immediateBaseConstraint) {
44232                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
44233                         return circularConstraintType;
44234                     }
44235                     if (constraintDepth >= 50) {
44236                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
44237                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
44238                         // new type identities as we descend into it. We stop the recursion here and mark this type
44239                         // and the outer types as having circular constraints.
44240                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
44241                         nonTerminating = true;
44242                         return t.immediateBaseConstraint = noConstraintType;
44243                     }
44244                     constraintDepth++;
44245                     var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
44246                     constraintDepth--;
44247                     if (!popTypeResolution()) {
44248                         if (t.flags & 262144 /* TypeParameter */) {
44249                             var errorNode = getConstraintDeclaration(t);
44250                             if (errorNode) {
44251                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
44252                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
44253                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
44254                                 }
44255                             }
44256                         }
44257                         result = circularConstraintType;
44258                     }
44259                     if (nonTerminating) {
44260                         result = circularConstraintType;
44261                     }
44262                     t.immediateBaseConstraint = result || noConstraintType;
44263                 }
44264                 return t.immediateBaseConstraint;
44265             }
44266             function getBaseConstraint(t) {
44267                 var c = getImmediateBaseConstraint(t);
44268                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
44269             }
44270             function computeBaseConstraint(t) {
44271                 if (t.flags & 262144 /* TypeParameter */) {
44272                     var constraint = getConstraintFromTypeParameter(t);
44273                     return t.isThisType || !constraint ?
44274                         constraint :
44275                         getBaseConstraint(constraint);
44276                 }
44277                 if (t.flags & 3145728 /* UnionOrIntersection */) {
44278                     var types = t.types;
44279                     var baseTypes = [];
44280                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
44281                         var type_2 = types_7[_i];
44282                         var baseType = getBaseConstraint(type_2);
44283                         if (baseType) {
44284                             baseTypes.push(baseType);
44285                         }
44286                     }
44287                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
44288                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
44289                             undefined;
44290                 }
44291                 if (t.flags & 4194304 /* Index */) {
44292                     return keyofConstraintType;
44293                 }
44294                 if (t.flags & 8388608 /* IndexedAccess */) {
44295                     var baseObjectType = getBaseConstraint(t.objectType);
44296                     var baseIndexType = getBaseConstraint(t.indexType);
44297                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
44298                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
44299                 }
44300                 if (t.flags & 16777216 /* Conditional */) {
44301                     var constraint = getConstraintFromConditionalType(t);
44302                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
44303                     var result = constraint && getBaseConstraint(constraint);
44304                     constraintDepth--;
44305                     return result;
44306                 }
44307                 if (t.flags & 33554432 /* Substitution */) {
44308                     return getBaseConstraint(t.substitute);
44309                 }
44310                 return t;
44311             }
44312         }
44313         function getApparentTypeOfIntersectionType(type) {
44314             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
44315         }
44316         function getResolvedTypeParameterDefault(typeParameter) {
44317             if (!typeParameter.default) {
44318                 if (typeParameter.target) {
44319                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
44320                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
44321                 }
44322                 else {
44323                     // To block recursion, set the initial value to the resolvingDefaultType.
44324                     typeParameter.default = resolvingDefaultType;
44325                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
44326                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
44327                     if (typeParameter.default === resolvingDefaultType) {
44328                         // If we have not been called recursively, set the correct default type.
44329                         typeParameter.default = defaultType;
44330                     }
44331                 }
44332             }
44333             else if (typeParameter.default === resolvingDefaultType) {
44334                 // If we are called recursively for this type parameter, mark the default as circular.
44335                 typeParameter.default = circularConstraintType;
44336             }
44337             return typeParameter.default;
44338         }
44339         /**
44340          * Gets the default type for a type parameter.
44341          *
44342          * If the type parameter is the result of an instantiation, this gets the instantiated
44343          * default type of its target. If the type parameter has no default type or the default is
44344          * circular, `undefined` is returned.
44345          */
44346         function getDefaultFromTypeParameter(typeParameter) {
44347             var defaultType = getResolvedTypeParameterDefault(typeParameter);
44348             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
44349         }
44350         function hasNonCircularTypeParameterDefault(typeParameter) {
44351             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
44352         }
44353         /**
44354          * Indicates whether the declaration of a typeParameter has a default type.
44355          */
44356         function hasTypeParameterDefault(typeParameter) {
44357             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
44358         }
44359         function getApparentTypeOfMappedType(type) {
44360             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
44361         }
44362         function getResolvedApparentTypeOfMappedType(type) {
44363             var typeVariable = getHomomorphicTypeVariable(type);
44364             if (typeVariable) {
44365                 var constraint = getConstraintOfTypeParameter(typeVariable);
44366                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
44367                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
44368                 }
44369             }
44370             return type;
44371         }
44372         /**
44373          * For a type parameter, return the base constraint of the type parameter. For the string, number,
44374          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
44375          * type itself.
44376          */
44377         function getApparentType(type) {
44378             var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
44379             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
44380                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
44381                     t.flags & 132 /* StringLike */ ? globalStringType :
44382                         t.flags & 296 /* NumberLike */ ? globalNumberType :
44383                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
44384                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
44385                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
44386                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
44387                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
44388                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
44389                                                     t;
44390         }
44391         function getReducedApparentType(type) {
44392             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
44393             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
44394             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
44395             // that type may need futher reduction to remove empty intersections.
44396             return getReducedType(getApparentType(getReducedType(type)));
44397         }
44398         function createUnionOrIntersectionProperty(containingType, name) {
44399             var singleProp;
44400             var propSet;
44401             var indexTypes;
44402             var isUnion = containingType.flags & 1048576 /* Union */;
44403             // Flags we want to propagate to the result if they exist in all source symbols
44404             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
44405             var syntheticFlag = 4 /* SyntheticMethod */;
44406             var checkFlags = 0;
44407             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
44408                 var current = _a[_i];
44409                 var type = getApparentType(current);
44410                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
44411                     var prop = getPropertyOfType(type, name);
44412                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
44413                     if (prop) {
44414                         if (isUnion) {
44415                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
44416                         }
44417                         else {
44418                             optionalFlag &= prop.flags;
44419                         }
44420                         if (!singleProp) {
44421                             singleProp = prop;
44422                         }
44423                         else if (prop !== singleProp) {
44424                             if (!propSet) {
44425                                 propSet = ts.createMap();
44426                                 propSet.set("" + getSymbolId(singleProp), singleProp);
44427                             }
44428                             var id = "" + getSymbolId(prop);
44429                             if (!propSet.has(id)) {
44430                                 propSet.set(id, prop);
44431                             }
44432                         }
44433                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
44434                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
44435                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
44436                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
44437                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
44438                         if (!isPrototypeProperty(prop)) {
44439                             syntheticFlag = 2 /* SyntheticProperty */;
44440                         }
44441                     }
44442                     else if (isUnion) {
44443                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
44444                         if (indexInfo) {
44445                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
44446                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
44447                         }
44448                         else if (isObjectLiteralType(type)) {
44449                             checkFlags |= 32 /* WritePartial */;
44450                             indexTypes = ts.append(indexTypes, undefinedType);
44451                         }
44452                         else {
44453                             checkFlags |= 16 /* ReadPartial */;
44454                         }
44455                     }
44456                 }
44457             }
44458             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
44459                 // No property was found, or, in a union, a property has a private or protected declaration in one
44460                 // constituent, but is missing or has a different declaration in another constituent.
44461                 return undefined;
44462             }
44463             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
44464                 return singleProp;
44465             }
44466             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
44467             var declarations;
44468             var firstType;
44469             var nameType;
44470             var propTypes = [];
44471             var firstValueDeclaration;
44472             var hasNonUniformValueDeclaration = false;
44473             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
44474                 var prop = props_1[_b];
44475                 if (!firstValueDeclaration) {
44476                     firstValueDeclaration = prop.valueDeclaration;
44477                 }
44478                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
44479                     hasNonUniformValueDeclaration = true;
44480                 }
44481                 declarations = ts.addRange(declarations, prop.declarations);
44482                 var type = getTypeOfSymbol(prop);
44483                 if (!firstType) {
44484                     firstType = type;
44485                     nameType = getSymbolLinks(prop).nameType;
44486                 }
44487                 else if (type !== firstType) {
44488                     checkFlags |= 64 /* HasNonUniformType */;
44489                 }
44490                 if (isLiteralType(type)) {
44491                     checkFlags |= 128 /* HasLiteralType */;
44492                 }
44493                 if (type.flags & 131072 /* Never */) {
44494                     checkFlags |= 131072 /* HasNeverType */;
44495                 }
44496                 propTypes.push(type);
44497             }
44498             ts.addRange(propTypes, indexTypes);
44499             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
44500             result.containingType = containingType;
44501             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
44502                 result.valueDeclaration = firstValueDeclaration;
44503                 // Inherit information about parent type.
44504                 if (firstValueDeclaration.symbol.parent) {
44505                     result.parent = firstValueDeclaration.symbol.parent;
44506                 }
44507             }
44508             result.declarations = declarations;
44509             result.nameType = nameType;
44510             if (propTypes.length > 2) {
44511                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
44512                 result.checkFlags |= 65536 /* DeferredType */;
44513                 result.deferralParent = containingType;
44514                 result.deferralConstituents = propTypes;
44515             }
44516             else {
44517                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
44518             }
44519             return result;
44520         }
44521         // Return the symbol for a given property in a union or intersection type, or undefined if the property
44522         // does not exist in any constituent type. Note that the returned property may only be present in some
44523         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
44524         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
44525         // and do not appear to be present in the union type.
44526         function getUnionOrIntersectionProperty(type, name) {
44527             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
44528             var property = properties.get(name);
44529             if (!property) {
44530                 property = createUnionOrIntersectionProperty(type, name);
44531                 if (property) {
44532                     properties.set(name, property);
44533                 }
44534             }
44535             return property;
44536         }
44537         function getPropertyOfUnionOrIntersectionType(type, name) {
44538             var property = getUnionOrIntersectionProperty(type, name);
44539             // We need to filter out partial properties in union types
44540             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
44541         }
44542         /**
44543          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
44544          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
44545          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
44546          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
44547          */
44548         function getReducedType(type) {
44549             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
44550                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
44551             }
44552             else if (type.flags & 2097152 /* Intersection */) {
44553                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
44554                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
44555                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
44556                 }
44557                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
44558             }
44559             return type;
44560         }
44561         function getReducedUnionType(unionType) {
44562             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
44563             if (reducedTypes === unionType.types) {
44564                 return unionType;
44565             }
44566             var reduced = getUnionType(reducedTypes);
44567             if (reduced.flags & 1048576 /* Union */) {
44568                 reduced.resolvedReducedType = reduced;
44569             }
44570             return reduced;
44571         }
44572         function isNeverReducedProperty(prop) {
44573             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
44574         }
44575         function isDiscriminantWithNeverType(prop) {
44576             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
44577             // a literal type and none is never, that reduces to never.
44578             return !(prop.flags & 16777216 /* Optional */) &&
44579                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
44580                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
44581         }
44582         function isConflictingPrivateProperty(prop) {
44583             // Return true for a synthetic property with multiple declarations, at least one of which is private.
44584             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
44585         }
44586         function elaborateNeverIntersection(errorInfo, type) {
44587             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
44588                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
44589                 if (neverProp) {
44590                     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));
44591                 }
44592                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
44593                 if (privateProp) {
44594                     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));
44595                 }
44596             }
44597             return errorInfo;
44598         }
44599         /**
44600          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
44601          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
44602          * Object and Function as appropriate.
44603          *
44604          * @param type a type to look up property from
44605          * @param name a name of property to look up in a given type
44606          */
44607         function getPropertyOfType(type, name) {
44608             type = getReducedApparentType(type);
44609             if (type.flags & 524288 /* Object */) {
44610                 var resolved = resolveStructuredTypeMembers(type);
44611                 var symbol = resolved.members.get(name);
44612                 if (symbol && symbolIsValue(symbol)) {
44613                     return symbol;
44614                 }
44615                 var functionType = resolved === anyFunctionType ? globalFunctionType :
44616                     resolved.callSignatures.length ? globalCallableFunctionType :
44617                         resolved.constructSignatures.length ? globalNewableFunctionType :
44618                             undefined;
44619                 if (functionType) {
44620                     var symbol_1 = getPropertyOfObjectType(functionType, name);
44621                     if (symbol_1) {
44622                         return symbol_1;
44623                     }
44624                 }
44625                 return getPropertyOfObjectType(globalObjectType, name);
44626             }
44627             if (type.flags & 3145728 /* UnionOrIntersection */) {
44628                 return getPropertyOfUnionOrIntersectionType(type, name);
44629             }
44630             return undefined;
44631         }
44632         function getSignaturesOfStructuredType(type, kind) {
44633             if (type.flags & 3670016 /* StructuredType */) {
44634                 var resolved = resolveStructuredTypeMembers(type);
44635                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
44636             }
44637             return ts.emptyArray;
44638         }
44639         /**
44640          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
44641          * maps primitive types and type parameters are to their apparent types.
44642          */
44643         function getSignaturesOfType(type, kind) {
44644             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
44645         }
44646         function getIndexInfoOfStructuredType(type, kind) {
44647             if (type.flags & 3670016 /* StructuredType */) {
44648                 var resolved = resolveStructuredTypeMembers(type);
44649                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
44650             }
44651         }
44652         function getIndexTypeOfStructuredType(type, kind) {
44653             var info = getIndexInfoOfStructuredType(type, kind);
44654             return info && info.type;
44655         }
44656         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
44657         // maps primitive types and type parameters are to their apparent types.
44658         function getIndexInfoOfType(type, kind) {
44659             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
44660         }
44661         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
44662         // maps primitive types and type parameters are to their apparent types.
44663         function getIndexTypeOfType(type, kind) {
44664             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
44665         }
44666         function getImplicitIndexTypeOfType(type, kind) {
44667             if (isObjectTypeWithInferableIndex(type)) {
44668                 var propTypes = [];
44669                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
44670                     var prop = _a[_i];
44671                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
44672                         propTypes.push(getTypeOfSymbol(prop));
44673                     }
44674                 }
44675                 if (kind === 0 /* String */) {
44676                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
44677                 }
44678                 if (propTypes.length) {
44679                     return getUnionType(propTypes);
44680                 }
44681             }
44682             return undefined;
44683         }
44684         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
44685         // type checking functions).
44686         function getTypeParametersFromDeclaration(declaration) {
44687             var result;
44688             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
44689                 var node = _a[_i];
44690                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
44691             }
44692             return result;
44693         }
44694         function symbolsToArray(symbols) {
44695             var result = [];
44696             symbols.forEach(function (symbol, id) {
44697                 if (!isReservedMemberName(id)) {
44698                     result.push(symbol);
44699                 }
44700             });
44701             return result;
44702         }
44703         function isJSDocOptionalParameter(node) {
44704             return ts.isInJSFile(node) && (
44705             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
44706             node.type && node.type.kind === 299 /* JSDocOptionalType */
44707                 || ts.getJSDocParameterTags(node).some(function (_a) {
44708                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
44709                     return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44710                 }));
44711         }
44712         function tryFindAmbientModule(moduleName, withAugmentations) {
44713             if (ts.isExternalModuleNameRelative(moduleName)) {
44714                 return undefined;
44715             }
44716             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
44717             // merged symbol is module declaration symbol combined with all augmentations
44718             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
44719         }
44720         function isOptionalParameter(node) {
44721             if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
44722                 return true;
44723             }
44724             if (node.initializer) {
44725                 var signature = getSignatureFromDeclaration(node.parent);
44726                 var parameterIndex = node.parent.parameters.indexOf(node);
44727                 ts.Debug.assert(parameterIndex >= 0);
44728                 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
44729             }
44730             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
44731             if (iife) {
44732                 return !node.type &&
44733                     !node.dotDotDotToken &&
44734                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
44735             }
44736             return false;
44737         }
44738         function isOptionalJSDocParameterTag(node) {
44739             if (!ts.isJSDocParameterTag(node)) {
44740                 return false;
44741             }
44742             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
44743             return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44744         }
44745         function createTypePredicate(kind, parameterName, parameterIndex, type) {
44746             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
44747         }
44748         /**
44749          * Gets the minimum number of type arguments needed to satisfy all non-optional type
44750          * parameters.
44751          */
44752         function getMinTypeArgumentCount(typeParameters) {
44753             var minTypeArgumentCount = 0;
44754             if (typeParameters) {
44755                 for (var i = 0; i < typeParameters.length; i++) {
44756                     if (!hasTypeParameterDefault(typeParameters[i])) {
44757                         minTypeArgumentCount = i + 1;
44758                     }
44759                 }
44760             }
44761             return minTypeArgumentCount;
44762         }
44763         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
44764             var numTypeParameters = ts.length(typeParameters);
44765             if (!numTypeParameters) {
44766                 return [];
44767             }
44768             var numTypeArguments = ts.length(typeArguments);
44769             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
44770                 var result = typeArguments ? typeArguments.slice() : [];
44771                 // Map invalid forward references in default types to the error type
44772                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44773                     result[i] = errorType;
44774                 }
44775                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
44776                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44777                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
44778                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
44779                         defaultType = anyType;
44780                     }
44781                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
44782                 }
44783                 result.length = typeParameters.length;
44784                 return result;
44785             }
44786             return typeArguments && typeArguments.slice();
44787         }
44788         function getSignatureFromDeclaration(declaration) {
44789             var links = getNodeLinks(declaration);
44790             if (!links.resolvedSignature) {
44791                 var parameters = [];
44792                 var flags = 0 /* None */;
44793                 var minArgumentCount = 0;
44794                 var thisParameter = void 0;
44795                 var hasThisParameter = false;
44796                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
44797                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
44798                 var isUntypedSignatureInJSFile = !iife &&
44799                     ts.isInJSFile(declaration) &&
44800                     ts.isValueSignatureDeclaration(declaration) &&
44801                     !ts.hasJSDocParameterTags(declaration) &&
44802                     !ts.getJSDocType(declaration);
44803                 if (isUntypedSignatureInJSFile) {
44804                     flags |= 16 /* IsUntypedSignatureInJSFile */;
44805                 }
44806                 // If this is a JSDoc construct signature, then skip the first parameter in the
44807                 // parameter list.  The first parameter represents the return type of the construct
44808                 // signature.
44809                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
44810                     var param = declaration.parameters[i];
44811                     var paramSymbol = param.symbol;
44812                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
44813                     // Include parameter symbol instead of property symbol in the signature
44814                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
44815                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
44816                         paramSymbol = resolvedSymbol;
44817                     }
44818                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
44819                         hasThisParameter = true;
44820                         thisParameter = param.symbol;
44821                     }
44822                     else {
44823                         parameters.push(paramSymbol);
44824                     }
44825                     if (type && type.kind === 187 /* LiteralType */) {
44826                         flags |= 2 /* HasLiteralTypes */;
44827                     }
44828                     // Record a new minimum argument count if this is not an optional parameter
44829                     var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
44830                         param.initializer || param.questionToken || param.dotDotDotToken ||
44831                         iife && parameters.length > iife.arguments.length && !type ||
44832                         isJSDocOptionalParameter(param);
44833                     if (!isOptionalParameter_1) {
44834                         minArgumentCount = parameters.length;
44835                     }
44836                 }
44837                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
44838                 if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
44839                     !hasNonBindableDynamicName(declaration) &&
44840                     (!hasThisParameter || !thisParameter)) {
44841                     var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
44842                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
44843                     if (other) {
44844                         thisParameter = getAnnotatedAccessorThisParameter(other);
44845                     }
44846                 }
44847                 var classType = declaration.kind === 162 /* Constructor */ ?
44848                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
44849                     : undefined;
44850                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
44851                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
44852                     flags |= 1 /* HasRestParameter */;
44853                 }
44854                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
44855                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
44856             }
44857             return links.resolvedSignature;
44858         }
44859         /**
44860          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
44861          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
44862          * OR
44863          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
44864          */
44865         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
44866             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
44867                 return false;
44868             }
44869             var lastParam = ts.lastOrUndefined(declaration.parameters);
44870             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
44871             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
44872                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
44873             });
44874             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
44875             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
44876             if (lastParamVariadicType) {
44877                 // Replace the last parameter with a rest parameter.
44878                 parameters.pop();
44879             }
44880             parameters.push(syntheticArgsSymbol);
44881             return true;
44882         }
44883         function getSignatureOfTypeTag(node) {
44884             // should be attached to a function declaration or expression
44885             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
44886                 return undefined;
44887             var typeTag = ts.getJSDocTypeTag(node);
44888             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
44889             return signature && getErasedSignature(signature);
44890         }
44891         function getReturnTypeOfTypeTag(node) {
44892             var signature = getSignatureOfTypeTag(node);
44893             return signature && getReturnTypeOfSignature(signature);
44894         }
44895         function containsArgumentsReference(declaration) {
44896             var links = getNodeLinks(declaration);
44897             if (links.containsArgumentsReference === undefined) {
44898                 if (links.flags & 8192 /* CaptureArguments */) {
44899                     links.containsArgumentsReference = true;
44900                 }
44901                 else {
44902                     links.containsArgumentsReference = traverse(declaration.body);
44903                 }
44904             }
44905             return links.containsArgumentsReference;
44906             function traverse(node) {
44907                 if (!node)
44908                     return false;
44909                 switch (node.kind) {
44910                     case 75 /* Identifier */:
44911                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
44912                     case 159 /* PropertyDeclaration */:
44913                     case 161 /* MethodDeclaration */:
44914                     case 163 /* GetAccessor */:
44915                     case 164 /* SetAccessor */:
44916                         return node.name.kind === 154 /* ComputedPropertyName */
44917                             && traverse(node.name);
44918                     default:
44919                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
44920                 }
44921             }
44922         }
44923         function getSignaturesOfSymbol(symbol) {
44924             if (!symbol)
44925                 return ts.emptyArray;
44926             var result = [];
44927             for (var i = 0; i < symbol.declarations.length; i++) {
44928                 var decl = symbol.declarations[i];
44929                 if (!ts.isFunctionLike(decl))
44930                     continue;
44931                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
44932                 // an implementation node if it has a body and the previous node is of the same kind and immediately
44933                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
44934                 if (i > 0 && decl.body) {
44935                     var previous = symbol.declarations[i - 1];
44936                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
44937                         continue;
44938                     }
44939                 }
44940                 result.push(getSignatureFromDeclaration(decl));
44941             }
44942             return result;
44943         }
44944         function resolveExternalModuleTypeByLiteral(name) {
44945             var moduleSym = resolveExternalModuleName(name, name);
44946             if (moduleSym) {
44947                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44948                 if (resolvedModuleSymbol) {
44949                     return getTypeOfSymbol(resolvedModuleSymbol);
44950                 }
44951             }
44952             return anyType;
44953         }
44954         function getThisTypeOfSignature(signature) {
44955             if (signature.thisParameter) {
44956                 return getTypeOfSymbol(signature.thisParameter);
44957             }
44958         }
44959         function getTypePredicateOfSignature(signature) {
44960             if (!signature.resolvedTypePredicate) {
44961                 if (signature.target) {
44962                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
44963                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
44964                 }
44965                 else if (signature.unionSignatures) {
44966                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
44967                 }
44968                 else {
44969                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
44970                     var jsdocPredicate = void 0;
44971                     if (!type && ts.isInJSFile(signature.declaration)) {
44972                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
44973                         if (jsdocSignature && signature !== jsdocSignature) {
44974                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
44975                         }
44976                     }
44977                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
44978                         createTypePredicateFromTypePredicateNode(type, signature) :
44979                         jsdocPredicate || noTypePredicate;
44980                 }
44981                 ts.Debug.assert(!!signature.resolvedTypePredicate);
44982             }
44983             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
44984         }
44985         function createTypePredicateFromTypePredicateNode(node, signature) {
44986             var parameterName = node.parameterName;
44987             var type = node.type && getTypeFromTypeNode(node.type);
44988             return parameterName.kind === 183 /* ThisType */ ?
44989                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
44990                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
44991         }
44992         function getReturnTypeOfSignature(signature) {
44993             if (!signature.resolvedReturnType) {
44994                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
44995                     return errorType;
44996                 }
44997                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
44998                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
44999                         getReturnTypeFromAnnotation(signature.declaration) ||
45000                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
45001                 if (signature.flags & 4 /* IsInnerCallChain */) {
45002                     type = addOptionalTypeMarker(type);
45003                 }
45004                 else if (signature.flags & 8 /* IsOuterCallChain */) {
45005                     type = getOptionalType(type);
45006                 }
45007                 if (!popTypeResolution()) {
45008                     if (signature.declaration) {
45009                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
45010                         if (typeNode) {
45011                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
45012                         }
45013                         else if (noImplicitAny) {
45014                             var declaration = signature.declaration;
45015                             var name = ts.getNameOfDeclaration(declaration);
45016                             if (name) {
45017                                 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));
45018                             }
45019                             else {
45020                                 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);
45021                             }
45022                         }
45023                     }
45024                     type = anyType;
45025                 }
45026                 signature.resolvedReturnType = type;
45027             }
45028             return signature.resolvedReturnType;
45029         }
45030         function getReturnTypeFromAnnotation(declaration) {
45031             if (declaration.kind === 162 /* Constructor */) {
45032                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
45033             }
45034             if (ts.isJSDocConstructSignature(declaration)) {
45035                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
45036             }
45037             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
45038             if (typeNode) {
45039                 return getTypeFromTypeNode(typeNode);
45040             }
45041             if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
45042                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
45043                 if (jsDocType) {
45044                     return jsDocType;
45045                 }
45046                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
45047                 var setterType = getAnnotatedAccessorType(setter);
45048                 if (setterType) {
45049                     return setterType;
45050                 }
45051             }
45052             return getReturnTypeOfTypeTag(declaration);
45053         }
45054         function isResolvingReturnTypeOfSignature(signature) {
45055             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
45056         }
45057         function getRestTypeOfSignature(signature) {
45058             return tryGetRestTypeOfSignature(signature) || anyType;
45059         }
45060         function tryGetRestTypeOfSignature(signature) {
45061             if (signatureHasRestParameter(signature)) {
45062                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
45063                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
45064                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
45065             }
45066             return undefined;
45067         }
45068         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
45069             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
45070             if (inferredTypeParameters) {
45071                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
45072                 if (returnSignature) {
45073                     var newReturnSignature = cloneSignature(returnSignature);
45074                     newReturnSignature.typeParameters = inferredTypeParameters;
45075                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
45076                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
45077                     return newInstantiatedSignature;
45078                 }
45079             }
45080             return instantiatedSignature;
45081         }
45082         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
45083             var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
45084             var id = getTypeListId(typeArguments);
45085             var instantiation = instantiations.get(id);
45086             if (!instantiation) {
45087                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
45088             }
45089             return instantiation;
45090         }
45091         function createSignatureInstantiation(signature, typeArguments) {
45092             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
45093         }
45094         function createSignatureTypeMapper(signature, typeArguments) {
45095             return createTypeMapper(signature.typeParameters, typeArguments);
45096         }
45097         function getErasedSignature(signature) {
45098             return signature.typeParameters ?
45099                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
45100                 signature;
45101         }
45102         function createErasedSignature(signature) {
45103             // Create an instantiation of the signature where all type arguments are the any type.
45104             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
45105         }
45106         function getCanonicalSignature(signature) {
45107             return signature.typeParameters ?
45108                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
45109                 signature;
45110         }
45111         function createCanonicalSignature(signature) {
45112             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
45113             // its original. When a generic class or interface is instantiated, each generic method in the class or
45114             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
45115             // where different generations of the same type parameter are in scope). This leads to a lot of new type
45116             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
45117             // that uses the original type identities for all unconstrained type parameters.
45118             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
45119         }
45120         function getBaseSignature(signature) {
45121             var typeParameters = signature.typeParameters;
45122             if (typeParameters) {
45123                 var typeEraser_1 = createTypeEraser(typeParameters);
45124                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
45125                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
45126             }
45127             return signature;
45128         }
45129         function getOrCreateTypeFromSignature(signature) {
45130             // There are two ways to declare a construct signature, one is by declaring a class constructor
45131             // using the constructor keyword, and the other is declaring a bare construct signature in an
45132             // object type literal or interface (using the new keyword). Each way of declaring a constructor
45133             // will result in a different declaration kind.
45134             if (!signature.isolatedSignatureType) {
45135                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
45136                 var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
45137                 var type = createObjectType(16 /* Anonymous */);
45138                 type.members = emptySymbols;
45139                 type.properties = ts.emptyArray;
45140                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
45141                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
45142                 signature.isolatedSignatureType = type;
45143             }
45144             return signature.isolatedSignatureType;
45145         }
45146         function getIndexSymbol(symbol) {
45147             return symbol.members.get("__index" /* Index */);
45148         }
45149         function getIndexDeclarationOfSymbol(symbol, kind) {
45150             var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
45151             var indexSymbol = getIndexSymbol(symbol);
45152             if (indexSymbol) {
45153                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
45154                     var decl = _a[_i];
45155                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
45156                     if (node.parameters.length === 1) {
45157                         var parameter = node.parameters[0];
45158                         if (parameter.type && parameter.type.kind === syntaxKind) {
45159                             return node;
45160                         }
45161                     }
45162                 }
45163             }
45164             return undefined;
45165         }
45166         function createIndexInfo(type, isReadonly, declaration) {
45167             return { type: type, isReadonly: isReadonly, declaration: declaration };
45168         }
45169         function getIndexInfoOfSymbol(symbol, kind) {
45170             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
45171             if (declaration) {
45172                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
45173             }
45174             return undefined;
45175         }
45176         function getConstraintDeclaration(type) {
45177             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
45178         }
45179         function getInferredTypeParameterConstraint(typeParameter) {
45180             var inferences;
45181             if (typeParameter.symbol) {
45182                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
45183                     var declaration = _a[_i];
45184                     if (declaration.parent.kind === 181 /* InferType */) {
45185                         // When an 'infer T' declaration is immediately contained in a type reference node
45186                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
45187                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
45188                         // present, we form an intersection of the inferred constraint types.
45189                         var grandParent = declaration.parent.parent;
45190                         if (grandParent.kind === 169 /* TypeReference */) {
45191                             var typeReference = grandParent;
45192                             var typeParameters = getTypeParametersForTypeReference(typeReference);
45193                             if (typeParameters) {
45194                                 var index = typeReference.typeArguments.indexOf(declaration.parent);
45195                                 if (index < typeParameters.length) {
45196                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
45197                                     if (declaredConstraint) {
45198                                         // Type parameter constraints can reference other type parameters so
45199                                         // constraints need to be instantiated. If instantiation produces the
45200                                         // type parameter itself, we discard that inference. For example, in
45201                                         //   type Foo<T extends string, U extends T> = [T, U];
45202                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
45203                                         // the instantiated constraint for U is X, so we discard that inference.
45204                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
45205                                         var constraint = instantiateType(declaredConstraint, mapper);
45206                                         if (constraint !== typeParameter) {
45207                                             inferences = ts.append(inferences, constraint);
45208                                         }
45209                                     }
45210                                 }
45211                             }
45212                         }
45213                         // When an 'infer T' declaration is immediately contained in a rest parameter
45214                         // declaration, we infer an 'unknown[]' constraint.
45215                         else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
45216                             inferences = ts.append(inferences, createArrayType(unknownType));
45217                         }
45218                     }
45219                 }
45220             }
45221             return inferences && getIntersectionType(inferences);
45222         }
45223         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
45224         function getConstraintFromTypeParameter(typeParameter) {
45225             if (!typeParameter.constraint) {
45226                 if (typeParameter.target) {
45227                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
45228                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
45229                 }
45230                 else {
45231                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
45232                     if (!constraintDeclaration) {
45233                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
45234                     }
45235                     else {
45236                         var type = getTypeFromTypeNode(constraintDeclaration);
45237                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
45238                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
45239                             // use unknown otherwise
45240                             type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType;
45241                         }
45242                         typeParameter.constraint = type;
45243                     }
45244                 }
45245             }
45246             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
45247         }
45248         function getParentSymbolOfTypeParameter(typeParameter) {
45249             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
45250             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
45251             return host && getSymbolOfNode(host);
45252         }
45253         function getTypeListId(types) {
45254             var result = "";
45255             if (types) {
45256                 var length_4 = types.length;
45257                 var i = 0;
45258                 while (i < length_4) {
45259                     var startId = types[i].id;
45260                     var count = 1;
45261                     while (i + count < length_4 && types[i + count].id === startId + count) {
45262                         count++;
45263                     }
45264                     if (result.length) {
45265                         result += ",";
45266                     }
45267                     result += startId;
45268                     if (count > 1) {
45269                         result += ":" + count;
45270                     }
45271                     i += count;
45272                 }
45273             }
45274             return result;
45275         }
45276         // This function is used to propagate certain flags when creating new object type references and union types.
45277         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
45278         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
45279         // that care about the presence of such types at arbitrary depth in a containing type.
45280         function getPropagatingFlagsOfTypes(types, excludeKinds) {
45281             var result = 0;
45282             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
45283                 var type = types_8[_i];
45284                 if (!(type.flags & excludeKinds)) {
45285                     result |= ts.getObjectFlags(type);
45286                 }
45287             }
45288             return result & 3670016 /* PropagatingFlags */;
45289         }
45290         function createTypeReference(target, typeArguments) {
45291             var id = getTypeListId(typeArguments);
45292             var type = target.instantiations.get(id);
45293             if (!type) {
45294                 type = createObjectType(4 /* Reference */, target.symbol);
45295                 target.instantiations.set(id, type);
45296                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
45297                 type.target = target;
45298                 type.resolvedTypeArguments = typeArguments;
45299             }
45300             return type;
45301         }
45302         function cloneTypeReference(source) {
45303             var type = createType(source.flags);
45304             type.symbol = source.symbol;
45305             type.objectFlags = source.objectFlags;
45306             type.target = source.target;
45307             type.resolvedTypeArguments = source.resolvedTypeArguments;
45308             return type;
45309         }
45310         function createDeferredTypeReference(target, node, mapper) {
45311             var aliasSymbol = getAliasSymbolForTypeNode(node);
45312             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
45313             var type = createObjectType(4 /* Reference */, target.symbol);
45314             type.target = target;
45315             type.node = node;
45316             type.mapper = mapper;
45317             type.aliasSymbol = aliasSymbol;
45318             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
45319             return type;
45320         }
45321         function getTypeArguments(type) {
45322             var _a, _b;
45323             if (!type.resolvedTypeArguments) {
45324                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
45325                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
45326                 }
45327                 var node = type.node;
45328                 var typeArguments = !node ? ts.emptyArray :
45329                     node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
45330                         node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
45331                             ts.map(node.elementTypes, getTypeFromTypeNode);
45332                 if (popTypeResolution()) {
45333                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
45334                 }
45335                 else {
45336                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
45337                     error(type.node || currentNode, type.target.symbol
45338                         ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
45339                         : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
45340                 }
45341             }
45342             return type.resolvedTypeArguments;
45343         }
45344         function getTypeReferenceArity(type) {
45345             return ts.length(type.target.typeParameters);
45346         }
45347         /**
45348          * Get type from type-reference that reference to class or interface
45349          */
45350         function getTypeFromClassOrInterfaceReference(node, symbol) {
45351             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
45352             var typeParameters = type.localTypeParameters;
45353             if (typeParameters) {
45354                 var numTypeArguments = ts.length(node.typeArguments);
45355                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45356                 var isJs = ts.isInJSFile(node);
45357                 var isJsImplicitAny = !noImplicitAny && isJs;
45358                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
45359                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
45360                     var diag = minTypeArgumentCount === typeParameters.length ?
45361                         missingAugmentsTag ?
45362                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
45363                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45364                         missingAugmentsTag ?
45365                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
45366                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
45367                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
45368                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
45369                     if (!isJs) {
45370                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
45371                         return errorType;
45372                     }
45373                 }
45374                 if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
45375                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
45376                 }
45377                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
45378                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
45379                 // of the class or interface.
45380                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
45381                 return createTypeReference(type, typeArguments);
45382             }
45383             return checkNoTypeArguments(node, symbol) ? type : errorType;
45384         }
45385         function getTypeAliasInstantiation(symbol, typeArguments) {
45386             var type = getDeclaredTypeOfSymbol(symbol);
45387             var links = getSymbolLinks(symbol);
45388             var typeParameters = links.typeParameters;
45389             var id = getTypeListId(typeArguments);
45390             var instantiation = links.instantiations.get(id);
45391             if (!instantiation) {
45392                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
45393             }
45394             return instantiation;
45395         }
45396         /**
45397          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
45398          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
45399          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
45400          */
45401         function getTypeFromTypeAliasReference(node, symbol) {
45402             var type = getDeclaredTypeOfSymbol(symbol);
45403             var typeParameters = getSymbolLinks(symbol).typeParameters;
45404             if (typeParameters) {
45405                 var numTypeArguments = ts.length(node.typeArguments);
45406                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45407                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
45408                     error(node, minTypeArgumentCount === typeParameters.length ?
45409                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45410                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
45411                     return errorType;
45412                 }
45413                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
45414             }
45415             return checkNoTypeArguments(node, symbol) ? type : errorType;
45416         }
45417         function getTypeReferenceName(node) {
45418             switch (node.kind) {
45419                 case 169 /* TypeReference */:
45420                     return node.typeName;
45421                 case 216 /* ExpressionWithTypeArguments */:
45422                     // We only support expressions that are simple qualified names. For other
45423                     // expressions this produces undefined.
45424                     var expr = node.expression;
45425                     if (ts.isEntityNameExpression(expr)) {
45426                         return expr;
45427                     }
45428                 // fall through;
45429             }
45430             return undefined;
45431         }
45432         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
45433             if (!typeReferenceName) {
45434                 return unknownSymbol;
45435             }
45436             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
45437         }
45438         function getTypeReferenceType(node, symbol) {
45439             if (symbol === unknownSymbol) {
45440                 return errorType;
45441             }
45442             symbol = getExpandoSymbol(symbol) || symbol;
45443             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
45444                 return getTypeFromClassOrInterfaceReference(node, symbol);
45445             }
45446             if (symbol.flags & 524288 /* TypeAlias */) {
45447                 return getTypeFromTypeAliasReference(node, symbol);
45448             }
45449             // Get type from reference to named type that cannot be generic (enum or type parameter)
45450             var res = tryGetDeclaredTypeOfSymbol(symbol);
45451             if (res) {
45452                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
45453             }
45454             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
45455                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
45456                 if (jsdocType) {
45457                     return jsdocType;
45458                 }
45459                 else {
45460                     // Resolve the type reference as a Type for the purpose of reporting errors.
45461                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
45462                     return getTypeOfSymbol(symbol);
45463                 }
45464             }
45465             return errorType;
45466         }
45467         /**
45468          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
45469          * Note: If the value is imported from commonjs, it should really be an alias,
45470          * but this function's special-case code fakes alias resolution as well.
45471          */
45472         function getTypeFromJSDocValueReference(node, symbol) {
45473             var links = getNodeLinks(node);
45474             if (!links.resolvedJSDocType) {
45475                 var valueType = getTypeOfSymbol(symbol);
45476                 var typeType = valueType;
45477                 if (symbol.valueDeclaration) {
45478                     var decl = ts.getRootDeclaration(symbol.valueDeclaration);
45479                     var isRequireAlias = false;
45480                     if (ts.isVariableDeclaration(decl) && decl.initializer) {
45481                         var expr = decl.initializer;
45482                         // skip past entity names, eg `require("x").a.b.c`
45483                         while (ts.isPropertyAccessExpression(expr)) {
45484                             expr = expr.expression;
45485                         }
45486                         isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
45487                     }
45488                     var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
45489                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
45490                     if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
45491                         typeType = getTypeReferenceType(node, valueType.symbol);
45492                     }
45493                 }
45494                 links.resolvedJSDocType = typeType;
45495             }
45496             return links.resolvedJSDocType;
45497         }
45498         function getSubstitutionType(baseType, substitute) {
45499             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
45500                 return baseType;
45501             }
45502             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
45503             var cached = substitutionTypes.get(id);
45504             if (cached) {
45505                 return cached;
45506             }
45507             var result = createType(33554432 /* Substitution */);
45508             result.baseType = baseType;
45509             result.substitute = substitute;
45510             substitutionTypes.set(id, result);
45511             return result;
45512         }
45513         function isUnaryTupleTypeNode(node) {
45514             return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
45515         }
45516         function getImpliedConstraint(type, checkNode, extendsNode) {
45517             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
45518                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
45519                     undefined;
45520         }
45521         function getConditionalFlowTypeOfType(type, node) {
45522             var constraints;
45523             while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
45524                 var parent = node.parent;
45525                 if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
45526                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
45527                     if (constraint) {
45528                         constraints = ts.append(constraints, constraint);
45529                     }
45530                 }
45531                 node = parent;
45532             }
45533             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
45534         }
45535         function isJSDocTypeReference(node) {
45536             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
45537         }
45538         function checkNoTypeArguments(node, symbol) {
45539             if (node.typeArguments) {
45540                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
45541                 return false;
45542             }
45543             return true;
45544         }
45545         function getIntendedTypeFromJSDocTypeReference(node) {
45546             if (ts.isIdentifier(node.typeName)) {
45547                 var typeArgs = node.typeArguments;
45548                 switch (node.typeName.escapedText) {
45549                     case "String":
45550                         checkNoTypeArguments(node);
45551                         return stringType;
45552                     case "Number":
45553                         checkNoTypeArguments(node);
45554                         return numberType;
45555                     case "Boolean":
45556                         checkNoTypeArguments(node);
45557                         return booleanType;
45558                     case "Void":
45559                         checkNoTypeArguments(node);
45560                         return voidType;
45561                     case "Undefined":
45562                         checkNoTypeArguments(node);
45563                         return undefinedType;
45564                     case "Null":
45565                         checkNoTypeArguments(node);
45566                         return nullType;
45567                     case "Function":
45568                     case "function":
45569                         checkNoTypeArguments(node);
45570                         return globalFunctionType;
45571                     case "array":
45572                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
45573                     case "promise":
45574                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
45575                     case "Object":
45576                         if (typeArgs && typeArgs.length === 2) {
45577                             if (ts.isJSDocIndexSignature(node)) {
45578                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
45579                                 var target = getTypeFromTypeNode(typeArgs[1]);
45580                                 var index = createIndexInfo(target, /*isReadonly*/ false);
45581                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
45582                             }
45583                             return anyType;
45584                         }
45585                         checkNoTypeArguments(node);
45586                         return !noImplicitAny ? anyType : undefined;
45587                 }
45588             }
45589         }
45590         function getTypeFromJSDocNullableTypeNode(node) {
45591             var type = getTypeFromTypeNode(node.type);
45592             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
45593         }
45594         function getTypeFromTypeReference(node) {
45595             var links = getNodeLinks(node);
45596             if (!links.resolvedType) {
45597                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
45598                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
45599                     links.resolvedSymbol = unknownSymbol;
45600                     return links.resolvedType = checkExpressionCached(node.parent.expression);
45601                 }
45602                 var symbol = void 0;
45603                 var type = void 0;
45604                 var meaning = 788968 /* Type */;
45605                 if (isJSDocTypeReference(node)) {
45606                     type = getIntendedTypeFromJSDocTypeReference(node);
45607                     if (!type) {
45608                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
45609                         if (symbol === unknownSymbol) {
45610                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
45611                         }
45612                         else {
45613                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
45614                         }
45615                         type = getTypeReferenceType(node, symbol);
45616                     }
45617                 }
45618                 if (!type) {
45619                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
45620                     type = getTypeReferenceType(node, symbol);
45621                 }
45622                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
45623                 // type reference in checkTypeReferenceNode.
45624                 links.resolvedSymbol = symbol;
45625                 links.resolvedType = type;
45626             }
45627             return links.resolvedType;
45628         }
45629         function typeArgumentsFromTypeReferenceNode(node) {
45630             return ts.map(node.typeArguments, getTypeFromTypeNode);
45631         }
45632         function getTypeFromTypeQueryNode(node) {
45633             var links = getNodeLinks(node);
45634             if (!links.resolvedType) {
45635                 // TypeScript 1.0 spec (April 2014): 3.6.3
45636                 // The expression is processed as an identifier expression (section 4.3)
45637                 // or property access expression(section 4.10),
45638                 // the widened type(section 3.9) of which becomes the result.
45639                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
45640             }
45641             return links.resolvedType;
45642         }
45643         function getTypeOfGlobalSymbol(symbol, arity) {
45644             function getTypeDeclaration(symbol) {
45645                 var declarations = symbol.declarations;
45646                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
45647                     var declaration = declarations_3[_i];
45648                     switch (declaration.kind) {
45649                         case 245 /* ClassDeclaration */:
45650                         case 246 /* InterfaceDeclaration */:
45651                         case 248 /* EnumDeclaration */:
45652                             return declaration;
45653                     }
45654                 }
45655             }
45656             if (!symbol) {
45657                 return arity ? emptyGenericType : emptyObjectType;
45658             }
45659             var type = getDeclaredTypeOfSymbol(symbol);
45660             if (!(type.flags & 524288 /* Object */)) {
45661                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
45662                 return arity ? emptyGenericType : emptyObjectType;
45663             }
45664             if (ts.length(type.typeParameters) !== arity) {
45665                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
45666                 return arity ? emptyGenericType : emptyObjectType;
45667             }
45668             return type;
45669         }
45670         function getGlobalValueSymbol(name, reportErrors) {
45671             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
45672         }
45673         function getGlobalTypeSymbol(name, reportErrors) {
45674             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
45675         }
45676         function getGlobalSymbol(name, meaning, diagnostic) {
45677             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
45678             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
45679         }
45680         function getGlobalType(name, arity, reportErrors) {
45681             var symbol = getGlobalTypeSymbol(name, reportErrors);
45682             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
45683         }
45684         function getGlobalTypedPropertyDescriptorType() {
45685             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
45686         }
45687         function getGlobalTemplateStringsArrayType() {
45688             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45689         }
45690         function getGlobalImportMetaType() {
45691             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45692         }
45693         function getGlobalESSymbolConstructorSymbol(reportErrors) {
45694             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
45695         }
45696         function getGlobalESSymbolType(reportErrors) {
45697             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
45698         }
45699         function getGlobalPromiseType(reportErrors) {
45700             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
45701         }
45702         function getGlobalPromiseLikeType(reportErrors) {
45703             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
45704         }
45705         function getGlobalPromiseConstructorSymbol(reportErrors) {
45706             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
45707         }
45708         function getGlobalPromiseConstructorLikeType(reportErrors) {
45709             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
45710         }
45711         function getGlobalAsyncIterableType(reportErrors) {
45712             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45713         }
45714         function getGlobalAsyncIteratorType(reportErrors) {
45715             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45716         }
45717         function getGlobalAsyncIterableIteratorType(reportErrors) {
45718             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45719         }
45720         function getGlobalAsyncGeneratorType(reportErrors) {
45721             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45722         }
45723         function getGlobalIterableType(reportErrors) {
45724             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45725         }
45726         function getGlobalIteratorType(reportErrors) {
45727             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45728         }
45729         function getGlobalIterableIteratorType(reportErrors) {
45730             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45731         }
45732         function getGlobalGeneratorType(reportErrors) {
45733             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45734         }
45735         function getGlobalIteratorYieldResultType(reportErrors) {
45736             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45737         }
45738         function getGlobalIteratorReturnResultType(reportErrors) {
45739             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45740         }
45741         function getGlobalTypeOrUndefined(name, arity) {
45742             if (arity === void 0) { arity = 0; }
45743             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
45744             return symbol && getTypeOfGlobalSymbol(symbol, arity);
45745         }
45746         function getGlobalExtractSymbol() {
45747             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45748         }
45749         function getGlobalOmitSymbol() {
45750             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45751         }
45752         function getGlobalBigIntType(reportErrors) {
45753             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
45754         }
45755         /**
45756          * Instantiates a global type that is generic with some element type, and returns that instantiation.
45757          */
45758         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
45759             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
45760         }
45761         function createTypedPropertyDescriptorType(propertyType) {
45762             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
45763         }
45764         function createIterableType(iteratedType) {
45765             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
45766         }
45767         function createArrayType(elementType, readonly) {
45768             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
45769         }
45770         function getArrayOrTupleTargetType(node) {
45771             var readonly = isReadonlyTypeOperator(node.parent);
45772             if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
45773                 return readonly ? globalReadonlyArrayType : globalArrayType;
45774             }
45775             var lastElement = ts.lastOrUndefined(node.elementTypes);
45776             var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
45777             var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
45778             return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
45779         }
45780         // Return true if the given type reference node is directly aliased or if it needs to be deferred
45781         // because it is possibly contained in a circular chain of eagerly resolved types.
45782         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
45783             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
45784                 node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) :
45785                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
45786         }
45787         // Return true when the given node is transitively contained in type constructs that eagerly
45788         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
45789         // of type aliases are eagerly resolved.
45790         function isResolvedByTypeAlias(node) {
45791             var parent = node.parent;
45792             switch (parent.kind) {
45793                 case 182 /* ParenthesizedType */:
45794                 case 169 /* TypeReference */:
45795                 case 178 /* UnionType */:
45796                 case 179 /* IntersectionType */:
45797                 case 185 /* IndexedAccessType */:
45798                 case 180 /* ConditionalType */:
45799                 case 184 /* TypeOperator */:
45800                 case 174 /* ArrayType */:
45801                 case 175 /* TupleType */:
45802                     return isResolvedByTypeAlias(parent);
45803                 case 247 /* TypeAliasDeclaration */:
45804                     return true;
45805             }
45806             return false;
45807         }
45808         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
45809         // of a type alias.
45810         function mayResolveTypeAlias(node) {
45811             switch (node.kind) {
45812                 case 169 /* TypeReference */:
45813                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
45814                 case 172 /* TypeQuery */:
45815                     return true;
45816                 case 184 /* TypeOperator */:
45817                     return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
45818                 case 182 /* ParenthesizedType */:
45819                 case 176 /* OptionalType */:
45820                 case 299 /* JSDocOptionalType */:
45821                 case 297 /* JSDocNullableType */:
45822                 case 298 /* JSDocNonNullableType */:
45823                 case 294 /* JSDocTypeExpression */:
45824                     return mayResolveTypeAlias(node.type);
45825                 case 177 /* RestType */:
45826                     return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
45827                 case 178 /* UnionType */:
45828                 case 179 /* IntersectionType */:
45829                     return ts.some(node.types, mayResolveTypeAlias);
45830                 case 185 /* IndexedAccessType */:
45831                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
45832                 case 180 /* ConditionalType */:
45833                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
45834                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
45835             }
45836             return false;
45837         }
45838         function getTypeFromArrayOrTupleTypeNode(node) {
45839             var links = getNodeLinks(node);
45840             if (!links.resolvedType) {
45841                 var target = getArrayOrTupleTargetType(node);
45842                 if (target === emptyGenericType) {
45843                     links.resolvedType = emptyObjectType;
45844                 }
45845                 else if (isDeferredTypeReferenceNode(node)) {
45846                     links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
45847                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
45848                 }
45849                 else {
45850                     var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
45851                     links.resolvedType = createTypeReference(target, elementTypes);
45852                 }
45853             }
45854             return links.resolvedType;
45855         }
45856         function isReadonlyTypeOperator(node) {
45857             return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
45858         }
45859         // We represent tuple types as type references to synthesized generic interface types created by
45860         // this function. The types are of the form:
45861         //
45862         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
45863         //
45864         // Note that the generic type created by this function has no symbol associated with it. The same
45865         // is true for each of the synthesized type parameters.
45866         function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45867             var typeParameters;
45868             var properties = [];
45869             var maxLength = hasRestElement ? arity - 1 : arity;
45870             if (arity) {
45871                 typeParameters = new Array(arity);
45872                 for (var i = 0; i < arity; i++) {
45873                     var typeParameter = typeParameters[i] = createTypeParameter();
45874                     if (i < maxLength) {
45875                         var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
45876                         property.type = typeParameter;
45877                         properties.push(property);
45878                     }
45879                 }
45880             }
45881             var literalTypes = [];
45882             for (var i = minLength; i <= maxLength; i++)
45883                 literalTypes.push(getLiteralType(i));
45884             var lengthSymbol = createSymbol(4 /* Property */, "length");
45885             lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
45886             properties.push(lengthSymbol);
45887             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
45888             type.typeParameters = typeParameters;
45889             type.outerTypeParameters = undefined;
45890             type.localTypeParameters = typeParameters;
45891             type.instantiations = ts.createMap();
45892             type.instantiations.set(getTypeListId(type.typeParameters), type);
45893             type.target = type;
45894             type.resolvedTypeArguments = type.typeParameters;
45895             type.thisType = createTypeParameter();
45896             type.thisType.isThisType = true;
45897             type.thisType.constraint = type;
45898             type.declaredProperties = properties;
45899             type.declaredCallSignatures = ts.emptyArray;
45900             type.declaredConstructSignatures = ts.emptyArray;
45901             type.declaredStringIndexInfo = undefined;
45902             type.declaredNumberIndexInfo = undefined;
45903             type.minLength = minLength;
45904             type.hasRestElement = hasRestElement;
45905             type.readonly = readonly;
45906             type.associatedNames = associatedNames;
45907             return type;
45908         }
45909         function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45910             var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
45911             var type = tupleTypes.get(key);
45912             if (!type) {
45913                 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
45914             }
45915             return type;
45916         }
45917         function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
45918             if (minLength === void 0) { minLength = elementTypes.length; }
45919             if (hasRestElement === void 0) { hasRestElement = false; }
45920             if (readonly === void 0) { readonly = false; }
45921             var arity = elementTypes.length;
45922             if (arity === 1 && hasRestElement) {
45923                 return createArrayType(elementTypes[0], readonly);
45924             }
45925             var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
45926             return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
45927         }
45928         function sliceTupleType(type, index) {
45929             var tuple = type.target;
45930             if (tuple.hasRestElement) {
45931                 // don't slice off rest element
45932                 index = Math.min(index, getTypeReferenceArity(type) - 1);
45933             }
45934             return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
45935         }
45936         function getTypeFromOptionalTypeNode(node) {
45937             var type = getTypeFromTypeNode(node.type);
45938             return strictNullChecks ? getOptionalType(type) : type;
45939         }
45940         function getTypeId(type) {
45941             return type.id;
45942         }
45943         function containsType(types, type) {
45944             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
45945         }
45946         function insertType(types, type) {
45947             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
45948             if (index < 0) {
45949                 types.splice(~index, 0, type);
45950                 return true;
45951             }
45952             return false;
45953         }
45954         function addTypeToUnion(typeSet, includes, type) {
45955             var flags = type.flags;
45956             if (flags & 1048576 /* Union */) {
45957                 return addTypesToUnion(typeSet, includes, type.types);
45958             }
45959             // We ignore 'never' types in unions
45960             if (!(flags & 131072 /* Never */)) {
45961                 includes |= flags & 71041023 /* IncludesMask */;
45962                 if (flags & 66846720 /* StructuredOrInstantiable */)
45963                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
45964                 if (type === wildcardType)
45965                     includes |= 8388608 /* IncludesWildcard */;
45966                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
45967                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
45968                         includes |= 4194304 /* IncludesNonWideningType */;
45969                 }
45970                 else {
45971                     var len = typeSet.length;
45972                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
45973                     if (index < 0) {
45974                         typeSet.splice(~index, 0, type);
45975                     }
45976                 }
45977             }
45978             return includes;
45979         }
45980         // Add the given types to the given type set. Order is preserved, duplicates are removed,
45981         // and nested types of the given kind are flattened into the set.
45982         function addTypesToUnion(typeSet, includes, types) {
45983             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
45984                 var type = types_9[_i];
45985                 includes = addTypeToUnion(typeSet, includes, type);
45986             }
45987             return includes;
45988         }
45989         function isSetOfLiteralsFromSameEnum(types) {
45990             var first = types[0];
45991             if (first.flags & 1024 /* EnumLiteral */) {
45992                 var firstEnum = getParentOfSymbol(first.symbol);
45993                 for (var i = 1; i < types.length; i++) {
45994                     var other = types[i];
45995                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
45996                         return false;
45997                     }
45998                 }
45999                 return true;
46000             }
46001             return false;
46002         }
46003         function removeSubtypes(types, primitivesOnly) {
46004             var len = types.length;
46005             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
46006                 return true;
46007             }
46008             var i = len;
46009             var count = 0;
46010             while (i > 0) {
46011                 i--;
46012                 var source = types[i];
46013                 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
46014                     var target = types_10[_i];
46015                     if (source !== target) {
46016                         if (count === 100000) {
46017                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
46018                             // same ratio of checks per element. If the estimated number of remaining type checks is
46019                             // greater than an upper limit we deem the union type too complex to represent. The
46020                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
46021                             // caps union types at 5000 unique literal types and 1000 unique object types.
46022                             var estimatedCount = (count / (len - i)) * len;
46023                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
46024                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46025                                 return false;
46026                             }
46027                         }
46028                         count++;
46029                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
46030                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
46031                             isTypeDerivedFrom(source, target))) {
46032                             ts.orderedRemoveItemAt(types, i);
46033                             break;
46034                         }
46035                     }
46036                 }
46037             }
46038             return true;
46039         }
46040         function removeRedundantLiteralTypes(types, includes) {
46041             var i = types.length;
46042             while (i > 0) {
46043                 i--;
46044                 var t = types[i];
46045                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
46046                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
46047                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
46048                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
46049                     isFreshLiteralType(t) && containsType(types, t.regularType);
46050                 if (remove) {
46051                     ts.orderedRemoveItemAt(types, i);
46052                 }
46053             }
46054         }
46055         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
46056         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
46057         // of other types. Subtype reduction is expensive for large union types and is possible only when union
46058         // types are known not to circularly reference themselves (as is the case with union types created by
46059         // expression constructs such as array literals and the || and ?: operators). Named types can
46060         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
46061         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
46062         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
46063             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
46064             if (types.length === 0) {
46065                 return neverType;
46066             }
46067             if (types.length === 1) {
46068                 return types[0];
46069             }
46070             var typeSet = [];
46071             var includes = addTypesToUnion(typeSet, 0, types);
46072             if (unionReduction !== 0 /* None */) {
46073                 if (includes & 3 /* AnyOrUnknown */) {
46074                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
46075                 }
46076                 switch (unionReduction) {
46077                     case 1 /* Literal */:
46078                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
46079                             removeRedundantLiteralTypes(typeSet, includes);
46080                         }
46081                         break;
46082                     case 2 /* Subtype */:
46083                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
46084                             return errorType;
46085                         }
46086                         break;
46087                 }
46088                 if (typeSet.length === 0) {
46089                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
46090                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
46091                             neverType;
46092                 }
46093             }
46094             var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
46095                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
46096             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
46097         }
46098         function getUnionTypePredicate(signatures) {
46099             var first;
46100             var types = [];
46101             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
46102                 var sig = signatures_6[_i];
46103                 var pred = getTypePredicateOfSignature(sig);
46104                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
46105                     continue;
46106                 }
46107                 if (first) {
46108                     if (!typePredicateKindsMatch(first, pred)) {
46109                         // No common type predicate.
46110                         return undefined;
46111                     }
46112                 }
46113                 else {
46114                     first = pred;
46115                 }
46116                 types.push(pred.type);
46117             }
46118             if (!first) {
46119                 // No union signatures had a type predicate.
46120                 return undefined;
46121             }
46122             var unionType = getUnionType(types);
46123             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
46124         }
46125         function typePredicateKindsMatch(a, b) {
46126             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
46127         }
46128         // This function assumes the constituent type list is sorted and deduplicated.
46129         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
46130             if (types.length === 0) {
46131                 return neverType;
46132             }
46133             if (types.length === 1) {
46134                 return types[0];
46135             }
46136             var id = getTypeListId(types);
46137             var type = unionTypes.get(id);
46138             if (!type) {
46139                 type = createType(1048576 /* Union */);
46140                 unionTypes.set(id, type);
46141                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46142                 type.types = types;
46143                 /*
46144                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
46145                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
46146                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
46147                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
46148                 */
46149                 type.aliasSymbol = aliasSymbol;
46150                 type.aliasTypeArguments = aliasTypeArguments;
46151             }
46152             return type;
46153         }
46154         function getTypeFromUnionTypeNode(node) {
46155             var links = getNodeLinks(node);
46156             if (!links.resolvedType) {
46157                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46158                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46159             }
46160             return links.resolvedType;
46161         }
46162         function addTypeToIntersection(typeSet, includes, type) {
46163             var flags = type.flags;
46164             if (flags & 2097152 /* Intersection */) {
46165                 return addTypesToIntersection(typeSet, includes, type.types);
46166             }
46167             if (isEmptyAnonymousObjectType(type)) {
46168                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
46169                     includes |= 16777216 /* IncludesEmptyObject */;
46170                     typeSet.set(type.id.toString(), type);
46171                 }
46172             }
46173             else {
46174                 if (flags & 3 /* AnyOrUnknown */) {
46175                     if (type === wildcardType)
46176                         includes |= 8388608 /* IncludesWildcard */;
46177                 }
46178                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
46179                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
46180                         // We have seen two distinct unit types which means we should reduce to an
46181                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
46182                         includes |= 67108864 /* NonPrimitive */;
46183                     }
46184                     typeSet.set(type.id.toString(), type);
46185                 }
46186                 includes |= flags & 71041023 /* IncludesMask */;
46187             }
46188             return includes;
46189         }
46190         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
46191         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
46192         function addTypesToIntersection(typeSet, includes, types) {
46193             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
46194                 var type = types_11[_i];
46195                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
46196             }
46197             return includes;
46198         }
46199         function removeRedundantPrimitiveTypes(types, includes) {
46200             var i = types.length;
46201             while (i > 0) {
46202                 i--;
46203                 var t = types[i];
46204                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46205                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46206                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46207                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
46208                 if (remove) {
46209                     ts.orderedRemoveItemAt(types, i);
46210                 }
46211             }
46212         }
46213         // Check that the given type has a match in every union. A given type is matched by
46214         // an identical type, and a literal type is additionally matched by its corresponding
46215         // primitive type.
46216         function eachUnionContains(unionTypes, type) {
46217             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
46218                 var u = unionTypes_1[_i];
46219                 if (!containsType(u.types, type)) {
46220                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
46221                         type.flags & 256 /* NumberLiteral */ ? numberType :
46222                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
46223                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
46224                                     undefined;
46225                     if (!primitive || !containsType(u.types, primitive)) {
46226                         return false;
46227                     }
46228                 }
46229             }
46230             return true;
46231         }
46232         function extractIrreducible(types, flag) {
46233             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
46234                 for (var i = 0; i < types.length; i++) {
46235                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
46236                 }
46237                 return true;
46238             }
46239             return false;
46240         }
46241         // If the given list of types contains more than one union of primitive types, replace the
46242         // first with a union containing an intersection of those primitive types, then remove the
46243         // other unions and return true. Otherwise, do nothing and return false.
46244         function intersectUnionsOfPrimitiveTypes(types) {
46245             var unionTypes;
46246             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
46247             if (index < 0) {
46248                 return false;
46249             }
46250             var i = index + 1;
46251             // Remove all but the first union of primitive types and collect them in
46252             // the unionTypes array.
46253             while (i < types.length) {
46254                 var t = types[i];
46255                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
46256                     (unionTypes || (unionTypes = [types[index]])).push(t);
46257                     ts.orderedRemoveItemAt(types, i);
46258                 }
46259                 else {
46260                     i++;
46261                 }
46262             }
46263             // Return false if there was only one union of primitive types
46264             if (!unionTypes) {
46265                 return false;
46266             }
46267             // We have more than one union of primitive types, now intersect them. For each
46268             // type in each union we check if the type is matched in every union and if so
46269             // we include it in the result.
46270             var checked = [];
46271             var result = [];
46272             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
46273                 var u = unionTypes_2[_i];
46274                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
46275                     var t = _b[_a];
46276                     if (insertType(checked, t)) {
46277                         if (eachUnionContains(unionTypes, t)) {
46278                             insertType(result, t);
46279                         }
46280                     }
46281                 }
46282             }
46283             // Finally replace the first union with the result
46284             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
46285             return true;
46286         }
46287         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46288             var result = createType(2097152 /* Intersection */);
46289             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46290             result.types = types;
46291             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
46292             result.aliasTypeArguments = aliasTypeArguments;
46293             return result;
46294         }
46295         // We normalize combinations of intersection and union types based on the distributive property of the '&'
46296         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
46297         // types with union type constituents into equivalent union types with intersection type constituents and
46298         // effectively ensure that union types are always at the top level in type representations.
46299         //
46300         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
46301         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
46302         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
46303         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
46304         // for intersections of types with signatures can be deterministic.
46305         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46306             var typeMembershipMap = ts.createMap();
46307             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
46308             var typeSet = ts.arrayFrom(typeMembershipMap.values());
46309             // An intersection type is considered empty if it contains
46310             // the type never, or
46311             // more than one unit type or,
46312             // an object type and a nullable type (null or undefined), or
46313             // a string-like type and a type known to be non-string-like, or
46314             // a number-like type and a type known to be non-number-like, or
46315             // a symbol-like type and a type known to be non-symbol-like, or
46316             // a void-like type and a type known to be non-void-like, or
46317             // a non-primitive type and a type known to be primitive.
46318             if (includes & 131072 /* Never */ ||
46319                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
46320                 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
46321                 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
46322                 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
46323                 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
46324                 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
46325                 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
46326                 return neverType;
46327             }
46328             if (includes & 1 /* Any */) {
46329                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
46330             }
46331             if (!strictNullChecks && includes & 98304 /* Nullable */) {
46332                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
46333             }
46334             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46335                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46336                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46337                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
46338                 removeRedundantPrimitiveTypes(typeSet, includes);
46339             }
46340             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
46341                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
46342             }
46343             if (typeSet.length === 0) {
46344                 return unknownType;
46345             }
46346             if (typeSet.length === 1) {
46347                 return typeSet[0];
46348             }
46349             var id = getTypeListId(typeSet);
46350             var result = intersectionTypes.get(id);
46351             if (!result) {
46352                 if (includes & 1048576 /* Union */) {
46353                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
46354                         // When the intersection creates a reduced set (which might mean that *all* union types have
46355                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
46356                         // reduced we'll never reduce again, so this occurs at most once.
46357                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46358                     }
46359                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
46360                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46361                     }
46362                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
46363                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46364                     }
46365                     else {
46366                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
46367                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
46368                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
46369                         var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
46370                         if (size >= 100000) {
46371                             error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46372                             return errorType;
46373                         }
46374                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
46375                         var unionType = typeSet[unionIndex_1];
46376                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46377                     }
46378                 }
46379                 else {
46380                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46381                 }
46382                 intersectionTypes.set(id, result);
46383             }
46384             return result;
46385         }
46386         function getTypeFromIntersectionTypeNode(node) {
46387             var links = getNodeLinks(node);
46388             if (!links.resolvedType) {
46389                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46390                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46391             }
46392             return links.resolvedType;
46393         }
46394         function createIndexType(type, stringsOnly) {
46395             var result = createType(4194304 /* Index */);
46396             result.type = type;
46397             result.stringsOnly = stringsOnly;
46398             return result;
46399         }
46400         function getIndexTypeForGenericType(type, stringsOnly) {
46401             return stringsOnly ?
46402                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
46403                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
46404         }
46405         function getLiteralTypeFromPropertyName(name) {
46406             if (ts.isPrivateIdentifier(name)) {
46407                 return neverType;
46408             }
46409             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
46410                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
46411         }
46412         function getBigIntLiteralType(node) {
46413             return getLiteralType({
46414                 negative: false,
46415                 base10Value: ts.parsePseudoBigInt(node.text)
46416             });
46417         }
46418         function getLiteralTypeFromProperty(prop, include) {
46419             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
46420                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
46421                 if (!type && !ts.isKnownSymbol(prop)) {
46422                     if (prop.escapedName === "default" /* Default */) {
46423                         type = getLiteralType("default");
46424                     }
46425                     else {
46426                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
46427                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
46428                     }
46429                 }
46430                 if (type && type.flags & include) {
46431                     return type;
46432                 }
46433             }
46434             return neverType;
46435         }
46436         function getLiteralTypeFromProperties(type, include) {
46437             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
46438         }
46439         function getNonEnumNumberIndexInfo(type) {
46440             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
46441             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
46442         }
46443         function getIndexType(type, stringsOnly, noIndexSignatures) {
46444             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
46445             type = getReducedType(type);
46446             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46447                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46448                     maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
46449                         ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
46450                             type === wildcardType ? wildcardType :
46451                                 type.flags & 2 /* Unknown */ ? neverType :
46452                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
46453                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
46454                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
46455                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
46456                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
46457         }
46458         function getExtractStringType(type) {
46459             if (keyofStringsOnly) {
46460                 return type;
46461             }
46462             var extractTypeAlias = getGlobalExtractSymbol();
46463             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
46464         }
46465         function getIndexTypeOrString(type) {
46466             var indexType = getExtractStringType(getIndexType(type));
46467             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
46468         }
46469         function getTypeFromTypeOperatorNode(node) {
46470             var links = getNodeLinks(node);
46471             if (!links.resolvedType) {
46472                 switch (node.operator) {
46473                     case 134 /* KeyOfKeyword */:
46474                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
46475                         break;
46476                     case 147 /* UniqueKeyword */:
46477                         links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
46478                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
46479                             : errorType;
46480                         break;
46481                     case 138 /* ReadonlyKeyword */:
46482                         links.resolvedType = getTypeFromTypeNode(node.type);
46483                         break;
46484                     default:
46485                         throw ts.Debug.assertNever(node.operator);
46486                 }
46487             }
46488             return links.resolvedType;
46489         }
46490         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments) {
46491             var type = createType(8388608 /* IndexedAccess */);
46492             type.objectType = objectType;
46493             type.indexType = indexType;
46494             type.aliasSymbol = aliasSymbol;
46495             type.aliasTypeArguments = aliasTypeArguments;
46496             return type;
46497         }
46498         /**
46499          * Returns if a type is or consists of a JSLiteral object type
46500          * In addition to objects which are directly literals,
46501          * * unions where every element is a jsliteral
46502          * * intersections where at least one element is a jsliteral
46503          * * and instantiable types constrained to a jsliteral
46504          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
46505          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
46506          */
46507         function isJSLiteralType(type) {
46508             if (noImplicitAny) {
46509                 return false; // Flag is meaningless under `noImplicitAny` mode
46510             }
46511             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
46512                 return true;
46513             }
46514             if (type.flags & 1048576 /* Union */) {
46515                 return ts.every(type.types, isJSLiteralType);
46516             }
46517             if (type.flags & 2097152 /* Intersection */) {
46518                 return ts.some(type.types, isJSLiteralType);
46519             }
46520             if (type.flags & 63176704 /* Instantiable */) {
46521                 return isJSLiteralType(getResolvedBaseConstraint(type));
46522             }
46523             return false;
46524         }
46525         function getPropertyNameFromIndex(indexType, accessNode) {
46526             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46527             return isTypeUsableAsPropertyName(indexType) ?
46528                 getPropertyNameFromType(indexType) :
46529                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
46530                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
46531                     accessNode && ts.isPropertyName(accessNode) ?
46532                         // late bound names are handled in the first branch, so here we only need to handle normal names
46533                         ts.getPropertyNameForPropertyNameNode(accessNode) :
46534                         undefined;
46535         }
46536         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
46537             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46538             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
46539             if (propName !== undefined) {
46540                 var prop = getPropertyOfType(objectType, propName);
46541                 if (prop) {
46542                     if (accessExpression) {
46543                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
46544                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
46545                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
46546                             return undefined;
46547                         }
46548                         if (accessFlags & 4 /* CacheSymbol */) {
46549                             getNodeLinks(accessNode).resolvedSymbol = prop;
46550                         }
46551                     }
46552                     var propType = getTypeOfSymbol(prop);
46553                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
46554                         getFlowTypeOfReference(accessExpression, propType) :
46555                         propType;
46556                 }
46557                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
46558                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
46559                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46560                         if (isTupleType(objectType)) {
46561                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
46562                         }
46563                         else {
46564                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46565                         }
46566                     }
46567                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
46568                     return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
46569                 }
46570             }
46571             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
46572                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
46573                     return objectType;
46574                 }
46575                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
46576                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
46577                 if (indexInfo) {
46578                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
46579                         if (accessExpression) {
46580                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
46581                         }
46582                         return undefined;
46583                     }
46584                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46585                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46586                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46587                         return indexInfo.type;
46588                     }
46589                     errorIfWritingToReadonlyIndex(indexInfo);
46590                     return indexInfo.type;
46591                 }
46592                 if (indexType.flags & 131072 /* Never */) {
46593                     return neverType;
46594                 }
46595                 if (isJSLiteralType(objectType)) {
46596                     return anyType;
46597                 }
46598                 if (accessExpression && !isConstEnumObjectType(objectType)) {
46599                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
46600                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46601                     }
46602                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
46603                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
46604                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
46605                         }
46606                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
46607                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
46608                         }
46609                         else {
46610                             var suggestion = void 0;
46611                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
46612                                 if (suggestion !== undefined) {
46613                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
46614                                 }
46615                             }
46616                             else {
46617                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
46618                                 if (suggestion_1 !== undefined) {
46619                                     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);
46620                                 }
46621                                 else {
46622                                     var errorInfo = void 0;
46623                                     if (indexType.flags & 1024 /* EnumLiteral */) {
46624                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
46625                                     }
46626                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
46627                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
46628                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
46629                                     }
46630                                     else if (indexType.flags & 128 /* StringLiteral */) {
46631                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46632                                     }
46633                                     else if (indexType.flags & 256 /* NumberLiteral */) {
46634                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46635                                     }
46636                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
46637                                         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));
46638                                     }
46639                                     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));
46640                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
46641                                 }
46642                             }
46643                         }
46644                     }
46645                     return undefined;
46646                 }
46647             }
46648             if (isJSLiteralType(objectType)) {
46649                 return anyType;
46650             }
46651             if (accessNode) {
46652                 var indexNode = getIndexNodeForAccessExpression(accessNode);
46653                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
46654                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
46655                 }
46656                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
46657                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
46658                 }
46659                 else {
46660                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46661                 }
46662             }
46663             if (isTypeAny(indexType)) {
46664                 return indexType;
46665             }
46666             return undefined;
46667             function errorIfWritingToReadonlyIndex(indexInfo) {
46668                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
46669                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
46670                 }
46671             }
46672         }
46673         function getIndexNodeForAccessExpression(accessNode) {
46674             return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
46675                 accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
46676                     accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
46677                         accessNode;
46678         }
46679         function isGenericObjectType(type) {
46680             if (type.flags & 3145728 /* UnionOrIntersection */) {
46681                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
46682                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
46683                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
46684                 }
46685                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
46686             }
46687             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type);
46688         }
46689         function isGenericIndexType(type) {
46690             if (type.flags & 3145728 /* UnionOrIntersection */) {
46691                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
46692                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
46693                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
46694                 }
46695                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
46696             }
46697             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
46698         }
46699         function isThisTypeParameter(type) {
46700             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
46701         }
46702         function getSimplifiedType(type, writing) {
46703             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
46704                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
46705                     type;
46706         }
46707         function distributeIndexOverObjectType(objectType, indexType, writing) {
46708             // (T | U)[K] -> T[K] | U[K] (reading)
46709             // (T | U)[K] -> T[K] & U[K] (writing)
46710             // (T & U)[K] -> T[K] & U[K]
46711             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
46712                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
46713                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
46714             }
46715         }
46716         function distributeObjectOverIndexType(objectType, indexType, writing) {
46717             // T[A | B] -> T[A] | T[B] (reading)
46718             // T[A | B] -> T[A] & T[B] (writing)
46719             if (indexType.flags & 1048576 /* Union */) {
46720                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
46721                 return writing ? getIntersectionType(types) : getUnionType(types);
46722             }
46723         }
46724         function unwrapSubstitution(type) {
46725             if (type.flags & 33554432 /* Substitution */) {
46726                 return type.substitute;
46727             }
46728             return type;
46729         }
46730         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
46731         // the type itself if no transformation is possible. The writing flag indicates that the type is
46732         // the target of an assignment.
46733         function getSimplifiedIndexedAccessType(type, writing) {
46734             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
46735             if (type[cache]) {
46736                 return type[cache] === circularConstraintType ? type : type[cache];
46737             }
46738             type[cache] = circularConstraintType;
46739             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
46740             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
46741             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
46742             var indexType = getSimplifiedType(type.indexType, writing);
46743             // T[A | B] -> T[A] | T[B] (reading)
46744             // T[A | B] -> T[A] & T[B] (writing)
46745             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
46746             if (distributedOverIndex) {
46747                 return type[cache] = distributedOverIndex;
46748             }
46749             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
46750             if (!(indexType.flags & 63176704 /* Instantiable */)) {
46751                 // (T | U)[K] -> T[K] | U[K] (reading)
46752                 // (T | U)[K] -> T[K] & U[K] (writing)
46753                 // (T & U)[K] -> T[K] & U[K]
46754                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
46755                 if (distributedOverObject) {
46756                     return type[cache] = distributedOverObject;
46757                 }
46758             }
46759             // So ultimately (reading):
46760             // ((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]
46761             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
46762             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
46763             // construct the type Box<T[X]>.
46764             if (isGenericMappedType(objectType)) {
46765                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
46766             }
46767             return type[cache] = type;
46768         }
46769         function getSimplifiedConditionalType(type, writing) {
46770             var checkType = type.checkType;
46771             var extendsType = type.extendsType;
46772             var trueType = getTrueTypeFromConditionalType(type);
46773             var falseType = getFalseTypeFromConditionalType(type);
46774             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
46775             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
46776                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46777                     return getSimplifiedType(trueType, writing);
46778                 }
46779                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
46780                     return neverType;
46781                 }
46782             }
46783             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
46784                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46785                     return neverType;
46786                 }
46787                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
46788                     return getSimplifiedType(falseType, writing);
46789                 }
46790             }
46791             return type;
46792         }
46793         /**
46794          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
46795          */
46796         function isIntersectionEmpty(type1, type2) {
46797             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
46798         }
46799         function substituteIndexedMappedType(objectType, index) {
46800             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
46801             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
46802             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
46803         }
46804         function getIndexedAccessType(objectType, indexType, accessNode, aliasSymbol, aliasTypeArguments) {
46805             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
46806         }
46807         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
46808             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
46809             if (objectType === wildcardType || indexType === wildcardType) {
46810                 return wildcardType;
46811             }
46812             // If the object type has a string index signature and no other members we know that the result will
46813             // always be the type of that index signature and we can simplify accordingly.
46814             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46815                 indexType = stringType;
46816             }
46817             // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
46818             // we are performing a higher-order index access where we cannot meaningfully access the properties of the
46819             // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
46820             // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
46821             // has always been resolved eagerly using the constraint type of 'this' at the given location.
46822             if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
46823                 if (objectType.flags & 3 /* AnyOrUnknown */) {
46824                     return objectType;
46825                 }
46826                 // Defer the operation by creating an indexed access type.
46827                 var id = objectType.id + "," + indexType.id;
46828                 var type = indexedAccessTypes.get(id);
46829                 if (!type) {
46830                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
46831                 }
46832                 return type;
46833             }
46834             // In the following we resolve T[K] to the type of the property in T selected by K.
46835             // We treat boolean as different from other unions to improve errors;
46836             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
46837             var apparentObjectType = getReducedApparentType(objectType);
46838             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
46839                 var propTypes = [];
46840                 var wasMissingProp = false;
46841                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
46842                     var t = _a[_i];
46843                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
46844                     if (propType) {
46845                         propTypes.push(propType);
46846                     }
46847                     else if (!accessNode) {
46848                         // If there's no error node, we can immeditely stop, since error reporting is off
46849                         return undefined;
46850                     }
46851                     else {
46852                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
46853                         wasMissingProp = true;
46854                     }
46855                 }
46856                 if (wasMissingProp) {
46857                     return undefined;
46858                 }
46859                 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46860             }
46861             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
46862         }
46863         function getTypeFromIndexedAccessTypeNode(node) {
46864             var links = getNodeLinks(node);
46865             if (!links.resolvedType) {
46866                 var objectType = getTypeFromTypeNode(node.objectType);
46867                 var indexType = getTypeFromTypeNode(node.indexType);
46868                 var potentialAlias = getAliasSymbolForTypeNode(node);
46869                 var resolved = getIndexedAccessType(objectType, indexType, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
46870                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
46871                     resolved.objectType === objectType &&
46872                     resolved.indexType === indexType ?
46873                     getConditionalFlowTypeOfType(resolved, node) : resolved;
46874             }
46875             return links.resolvedType;
46876         }
46877         function getTypeFromMappedTypeNode(node) {
46878             var links = getNodeLinks(node);
46879             if (!links.resolvedType) {
46880                 var type = createObjectType(32 /* Mapped */, node.symbol);
46881                 type.declaration = node;
46882                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
46883                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
46884                 links.resolvedType = type;
46885                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
46886                 // references itself through one or more type aliases.
46887                 getConstraintTypeFromMappedType(type);
46888             }
46889             return links.resolvedType;
46890         }
46891         function getActualTypeVariable(type) {
46892             if (type.flags & 33554432 /* Substitution */) {
46893                 return type.baseType;
46894             }
46895             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
46896                 type.indexType.flags & 33554432 /* Substitution */)) {
46897                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
46898             }
46899             return type;
46900         }
46901         function getConditionalType(root, mapper) {
46902             var result;
46903             var extraTypes;
46904             var _loop_12 = function () {
46905                 var checkType = instantiateType(root.checkType, mapper);
46906                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
46907                 var extendsType = instantiateType(root.extendsType, mapper);
46908                 if (checkType === wildcardType || extendsType === wildcardType) {
46909                     return { value: wildcardType };
46910                 }
46911                 var combinedMapper = void 0;
46912                 if (root.inferTypeParameters) {
46913                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
46914                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
46915                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
46916                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
46917                     // so in those cases we refain from performing inference and retain the uninfered type parameter
46918                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
46919                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
46920                         // conditional type instead of deferring resolution. Also, we always want strict function
46921                         // types rules (i.e. proper contravariance) for inferences.
46922                         inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
46923                     }
46924                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
46925                 }
46926                 // Instantiate the extends type including inferences for 'infer T' type parameters
46927                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
46928                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
46929                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
46930                     // Return falseType for a definitely false extends check. We check an instantiations of the two
46931                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
46932                     // possible (the wildcard type is assignable to and from all types). If those are not related,
46933                     // then no instantiations will be and we can just return the false branch type.
46934                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
46935                         // Return union of trueType and falseType for 'any' since it matches anything
46936                         if (checkType.flags & 1 /* Any */) {
46937                             (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
46938                         }
46939                         // If falseType is an immediately nested conditional type that isn't distributive or has an
46940                         // identical checkType, switch to that type and loop.
46941                         var falseType_1 = root.falseType;
46942                         if (falseType_1.flags & 16777216 /* Conditional */) {
46943                             var newRoot = falseType_1.root;
46944                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
46945                                 root = newRoot;
46946                                 return "continue";
46947                             }
46948                         }
46949                         result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
46950                         return "break";
46951                     }
46952                     // Return trueType for a definitely true extends check. We check instantiations of the two
46953                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
46954                     // that has no constraint. This ensures that, for example, the type
46955                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
46956                     // doesn't immediately resolve to 'string' instead of being deferred.
46957                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
46958                         result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
46959                         return "break";
46960                     }
46961                 }
46962                 // Return a deferred type for a check that is neither definitely true nor definitely false
46963                 var erasedCheckType = getActualTypeVariable(checkType);
46964                 result = createType(16777216 /* Conditional */);
46965                 result.root = root;
46966                 result.checkType = erasedCheckType;
46967                 result.extendsType = extendsType;
46968                 result.mapper = mapper;
46969                 result.combinedMapper = combinedMapper;
46970                 result.aliasSymbol = root.aliasSymbol;
46971                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
46972                 return "break";
46973             };
46974             // We loop here for an immediately nested conditional type in the false position, effectively treating
46975             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
46976             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
46977             while (true) {
46978                 var state_4 = _loop_12();
46979                 if (typeof state_4 === "object")
46980                     return state_4.value;
46981                 if (state_4 === "break")
46982                     break;
46983             }
46984             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
46985         }
46986         function getTrueTypeFromConditionalType(type) {
46987             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
46988         }
46989         function getFalseTypeFromConditionalType(type) {
46990             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
46991         }
46992         function getInferredTrueTypeFromConditionalType(type) {
46993             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
46994         }
46995         function getInferTypeParameters(node) {
46996             var result;
46997             if (node.locals) {
46998                 node.locals.forEach(function (symbol) {
46999                     if (symbol.flags & 262144 /* TypeParameter */) {
47000                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
47001                     }
47002                 });
47003             }
47004             return result;
47005         }
47006         function getTypeFromConditionalTypeNode(node) {
47007             var links = getNodeLinks(node);
47008             if (!links.resolvedType) {
47009                 var checkType = getTypeFromTypeNode(node.checkType);
47010                 var aliasSymbol = getAliasSymbolForTypeNode(node);
47011                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
47012                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
47013                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
47014                 var root = {
47015                     node: node,
47016                     checkType: checkType,
47017                     extendsType: getTypeFromTypeNode(node.extendsType),
47018                     trueType: getTypeFromTypeNode(node.trueType),
47019                     falseType: getTypeFromTypeNode(node.falseType),
47020                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
47021                     inferTypeParameters: getInferTypeParameters(node),
47022                     outerTypeParameters: outerTypeParameters,
47023                     instantiations: undefined,
47024                     aliasSymbol: aliasSymbol,
47025                     aliasTypeArguments: aliasTypeArguments
47026                 };
47027                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
47028                 if (outerTypeParameters) {
47029                     root.instantiations = ts.createMap();
47030                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
47031                 }
47032             }
47033             return links.resolvedType;
47034         }
47035         function getTypeFromInferTypeNode(node) {
47036             var links = getNodeLinks(node);
47037             if (!links.resolvedType) {
47038                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
47039             }
47040             return links.resolvedType;
47041         }
47042         function getIdentifierChain(node) {
47043             if (ts.isIdentifier(node)) {
47044                 return [node];
47045             }
47046             else {
47047                 return ts.append(getIdentifierChain(node.left), node.right);
47048             }
47049         }
47050         function getTypeFromImportTypeNode(node) {
47051             var links = getNodeLinks(node);
47052             if (!links.resolvedType) {
47053                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
47054                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
47055                     links.resolvedSymbol = unknownSymbol;
47056                     return links.resolvedType = errorType;
47057                 }
47058                 if (!ts.isLiteralImportTypeNode(node)) {
47059                     error(node.argument, ts.Diagnostics.String_literal_expected);
47060                     links.resolvedSymbol = unknownSymbol;
47061                     return links.resolvedType = errorType;
47062                 }
47063                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
47064                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
47065                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
47066                 if (!innerModuleSymbol) {
47067                     links.resolvedSymbol = unknownSymbol;
47068                     return links.resolvedType = errorType;
47069                 }
47070                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
47071                 if (!ts.nodeIsMissing(node.qualifier)) {
47072                     var nameStack = getIdentifierChain(node.qualifier);
47073                     var currentNamespace = moduleSymbol;
47074                     var current = void 0;
47075                     while (current = nameStack.shift()) {
47076                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
47077                         var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
47078                         if (!next) {
47079                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
47080                             return links.resolvedType = errorType;
47081                         }
47082                         getNodeLinks(current).resolvedSymbol = next;
47083                         getNodeLinks(current.parent).resolvedSymbol = next;
47084                         currentNamespace = next;
47085                     }
47086                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
47087                 }
47088                 else {
47089                     if (moduleSymbol.flags & targetMeaning) {
47090                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
47091                     }
47092                     else {
47093                         var errorMessage = targetMeaning === 111551 /* Value */
47094                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
47095                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
47096                         error(node, errorMessage, node.argument.literal.text);
47097                         links.resolvedSymbol = unknownSymbol;
47098                         links.resolvedType = errorType;
47099                     }
47100                 }
47101             }
47102             return links.resolvedType;
47103         }
47104         function resolveImportSymbolType(node, links, symbol, meaning) {
47105             var resolvedSymbol = resolveSymbol(symbol);
47106             links.resolvedSymbol = resolvedSymbol;
47107             if (meaning === 111551 /* Value */) {
47108                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
47109             }
47110             else {
47111                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
47112             }
47113         }
47114         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
47115             var links = getNodeLinks(node);
47116             if (!links.resolvedType) {
47117                 // Deferred resolution of members is handled by resolveObjectTypeMembers
47118                 var aliasSymbol = getAliasSymbolForTypeNode(node);
47119                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
47120                     links.resolvedType = emptyTypeLiteralType;
47121                 }
47122                 else {
47123                     var type = createObjectType(16 /* Anonymous */, node.symbol);
47124                     type.aliasSymbol = aliasSymbol;
47125                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
47126                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
47127                         type = createArrayType(type);
47128                     }
47129                     links.resolvedType = type;
47130                 }
47131             }
47132             return links.resolvedType;
47133         }
47134         function getAliasSymbolForTypeNode(node) {
47135             var host = node.parent;
47136             while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
47137                 host = host.parent;
47138             }
47139             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
47140         }
47141         function getTypeArgumentsForAliasSymbol(symbol) {
47142             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
47143         }
47144         function isNonGenericObjectType(type) {
47145             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
47146         }
47147         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
47148             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
47149         }
47150         function isSinglePropertyAnonymousObjectType(type) {
47151             return !!(type.flags & 524288 /* Object */) &&
47152                 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
47153                 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
47154         }
47155         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
47156             if (type.types.length === 2) {
47157                 var firstType = type.types[0];
47158                 var secondType = type.types[1];
47159                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
47160                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
47161                 }
47162                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
47163                     return getAnonymousPartialType(secondType);
47164                 }
47165                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
47166                     return getAnonymousPartialType(firstType);
47167                 }
47168             }
47169             function getAnonymousPartialType(type) {
47170                 // gets the type as if it had been spread, but where everything in the spread is made optional
47171                 var members = ts.createSymbolTable();
47172                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
47173                     var prop = _a[_i];
47174                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
47175                         // do nothing, skip privates
47176                     }
47177                     else if (isSpreadableProperty(prop)) {
47178                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47179                         var flags = 4 /* Property */ | 16777216 /* Optional */;
47180                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47181                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47182                         result.declarations = prop.declarations;
47183                         result.nameType = getSymbolLinks(prop).nameType;
47184                         result.syntheticOrigin = prop;
47185                         members.set(prop.escapedName, result);
47186                     }
47187                 }
47188                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
47189                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
47190                 return spread;
47191             }
47192         }
47193         /**
47194          * Since the source of spread types are object literals, which are not binary,
47195          * this function should be called in a left folding style, with left = previous result of getSpreadType
47196          * and right = the new element to be spread.
47197          */
47198         function getSpreadType(left, right, symbol, objectFlags, readonly) {
47199             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
47200                 return anyType;
47201             }
47202             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
47203                 return unknownType;
47204             }
47205             if (left.flags & 131072 /* Never */) {
47206                 return right;
47207             }
47208             if (right.flags & 131072 /* Never */) {
47209                 return left;
47210             }
47211             if (left.flags & 1048576 /* Union */) {
47212                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
47213                 if (merged) {
47214                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
47215                 }
47216                 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
47217             }
47218             if (right.flags & 1048576 /* Union */) {
47219                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
47220                 if (merged) {
47221                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
47222                 }
47223                 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
47224             }
47225             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
47226                 return left;
47227             }
47228             if (isGenericObjectType(left) || isGenericObjectType(right)) {
47229                 if (isEmptyObjectType(left)) {
47230                     return right;
47231                 }
47232                 // When the left type is an intersection, we may need to merge the last constituent of the
47233                 // intersection with the right type. For example when the left type is 'T & { a: string }'
47234                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
47235                 if (left.flags & 2097152 /* Intersection */) {
47236                     var types = left.types;
47237                     var lastLeft = types[types.length - 1];
47238                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
47239                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
47240                     }
47241                 }
47242                 return getIntersectionType([left, right]);
47243             }
47244             var members = ts.createSymbolTable();
47245             var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
47246             var stringIndexInfo;
47247             var numberIndexInfo;
47248             if (left === emptyObjectType) {
47249                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
47250                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
47251                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
47252             }
47253             else {
47254                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
47255                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
47256             }
47257             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
47258                 var rightProp = _a[_i];
47259                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
47260                     skippedPrivateMembers.set(rightProp.escapedName, true);
47261                 }
47262                 else if (isSpreadableProperty(rightProp)) {
47263                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
47264                 }
47265             }
47266             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
47267                 var leftProp = _c[_b];
47268                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
47269                     continue;
47270                 }
47271                 if (members.has(leftProp.escapedName)) {
47272                     var rightProp = members.get(leftProp.escapedName);
47273                     var rightType = getTypeOfSymbol(rightProp);
47274                     if (rightProp.flags & 16777216 /* Optional */) {
47275                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
47276                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
47277                         var result = createSymbol(flags, leftProp.escapedName);
47278                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
47279                         result.leftSpread = leftProp;
47280                         result.rightSpread = rightProp;
47281                         result.declarations = declarations;
47282                         result.nameType = getSymbolLinks(leftProp).nameType;
47283                         members.set(leftProp.escapedName, result);
47284                     }
47285                 }
47286                 else {
47287                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
47288                 }
47289             }
47290             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
47291             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
47292             return spread;
47293         }
47294         /** We approximate own properties as non-methods plus methods that are inside the object literal */
47295         function isSpreadableProperty(prop) {
47296             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
47297                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
47298                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
47299         }
47300         function getSpreadSymbol(prop, readonly) {
47301             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47302             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
47303                 return prop;
47304             }
47305             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
47306             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47307             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47308             result.declarations = prop.declarations;
47309             result.nameType = getSymbolLinks(prop).nameType;
47310             result.syntheticOrigin = prop;
47311             return result;
47312         }
47313         function getIndexInfoWithReadonly(info, readonly) {
47314             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
47315         }
47316         function createLiteralType(flags, value, symbol) {
47317             var type = createType(flags);
47318             type.symbol = symbol;
47319             type.value = value;
47320             return type;
47321         }
47322         function getFreshTypeOfLiteralType(type) {
47323             if (type.flags & 2944 /* Literal */) {
47324                 if (!type.freshType) {
47325                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
47326                     freshType.regularType = type;
47327                     freshType.freshType = freshType;
47328                     type.freshType = freshType;
47329                 }
47330                 return type.freshType;
47331             }
47332             return type;
47333         }
47334         function getRegularTypeOfLiteralType(type) {
47335             return type.flags & 2944 /* Literal */ ? type.regularType :
47336                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
47337                     type;
47338         }
47339         function isFreshLiteralType(type) {
47340             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
47341         }
47342         function getLiteralType(value, enumId, symbol) {
47343             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
47344             // where NNN is the text representation of a numeric literal and SSS are the characters
47345             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
47346             // EEE is a unique id for the containing enum type.
47347             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
47348             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
47349             var type = literalTypes.get(key);
47350             if (!type) {
47351                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
47352                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
47353                     (enumId ? 1024 /* EnumLiteral */ : 0);
47354                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
47355                 type.regularType = type;
47356             }
47357             return type;
47358         }
47359         function getTypeFromLiteralTypeNode(node) {
47360             var links = getNodeLinks(node);
47361             if (!links.resolvedType) {
47362                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
47363             }
47364             return links.resolvedType;
47365         }
47366         function createUniqueESSymbolType(symbol) {
47367             var type = createType(8192 /* UniqueESSymbol */);
47368             type.symbol = symbol;
47369             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
47370             return type;
47371         }
47372         function getESSymbolLikeTypeForNode(node) {
47373             if (ts.isValidESSymbolDeclaration(node)) {
47374                 var symbol = getSymbolOfNode(node);
47375                 var links = getSymbolLinks(symbol);
47376                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
47377             }
47378             return esSymbolType;
47379         }
47380         function getThisType(node) {
47381             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
47382             var parent = container && container.parent;
47383             if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
47384                 if (!ts.hasModifier(container, 32 /* Static */) &&
47385                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
47386                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
47387                 }
47388             }
47389             // inside x.prototype = { ... }
47390             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
47391                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
47392             }
47393             // /** @return {this} */
47394             // x.prototype.m = function() { ... }
47395             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
47396             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
47397                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
47398             }
47399             // inside constructor function C() { ... }
47400             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
47401                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
47402             }
47403             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
47404             return errorType;
47405         }
47406         function getTypeFromThisTypeNode(node) {
47407             var links = getNodeLinks(node);
47408             if (!links.resolvedType) {
47409                 links.resolvedType = getThisType(node);
47410             }
47411             return links.resolvedType;
47412         }
47413         function getTypeFromTypeNode(node) {
47414             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
47415         }
47416         function getTypeFromTypeNodeWorker(node) {
47417             switch (node.kind) {
47418                 case 125 /* AnyKeyword */:
47419                 case 295 /* JSDocAllType */:
47420                 case 296 /* JSDocUnknownType */:
47421                     return anyType;
47422                 case 148 /* UnknownKeyword */:
47423                     return unknownType;
47424                 case 143 /* StringKeyword */:
47425                     return stringType;
47426                 case 140 /* NumberKeyword */:
47427                     return numberType;
47428                 case 151 /* BigIntKeyword */:
47429                     return bigintType;
47430                 case 128 /* BooleanKeyword */:
47431                     return booleanType;
47432                 case 144 /* SymbolKeyword */:
47433                     return esSymbolType;
47434                 case 110 /* VoidKeyword */:
47435                     return voidType;
47436                 case 146 /* UndefinedKeyword */:
47437                     return undefinedType;
47438                 case 100 /* NullKeyword */:
47439                     return nullType;
47440                 case 137 /* NeverKeyword */:
47441                     return neverType;
47442                 case 141 /* ObjectKeyword */:
47443                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
47444                 case 183 /* ThisType */:
47445                 case 104 /* ThisKeyword */:
47446                     return getTypeFromThisTypeNode(node);
47447                 case 187 /* LiteralType */:
47448                     return getTypeFromLiteralTypeNode(node);
47449                 case 169 /* TypeReference */:
47450                     return getTypeFromTypeReference(node);
47451                 case 168 /* TypePredicate */:
47452                     return node.assertsModifier ? voidType : booleanType;
47453                 case 216 /* ExpressionWithTypeArguments */:
47454                     return getTypeFromTypeReference(node);
47455                 case 172 /* TypeQuery */:
47456                     return getTypeFromTypeQueryNode(node);
47457                 case 174 /* ArrayType */:
47458                 case 175 /* TupleType */:
47459                     return getTypeFromArrayOrTupleTypeNode(node);
47460                 case 176 /* OptionalType */:
47461                     return getTypeFromOptionalTypeNode(node);
47462                 case 178 /* UnionType */:
47463                     return getTypeFromUnionTypeNode(node);
47464                 case 179 /* IntersectionType */:
47465                     return getTypeFromIntersectionTypeNode(node);
47466                 case 297 /* JSDocNullableType */:
47467                     return getTypeFromJSDocNullableTypeNode(node);
47468                 case 299 /* JSDocOptionalType */:
47469                     return addOptionality(getTypeFromTypeNode(node.type));
47470                 case 182 /* ParenthesizedType */:
47471                 case 298 /* JSDocNonNullableType */:
47472                 case 294 /* JSDocTypeExpression */:
47473                     return getTypeFromTypeNode(node.type);
47474                 case 177 /* RestType */:
47475                     return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
47476                 case 301 /* JSDocVariadicType */:
47477                     return getTypeFromJSDocVariadicType(node);
47478                 case 170 /* FunctionType */:
47479                 case 171 /* ConstructorType */:
47480                 case 173 /* TypeLiteral */:
47481                 case 304 /* JSDocTypeLiteral */:
47482                 case 300 /* JSDocFunctionType */:
47483                 case 305 /* JSDocSignature */:
47484                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
47485                 case 184 /* TypeOperator */:
47486                     return getTypeFromTypeOperatorNode(node);
47487                 case 185 /* IndexedAccessType */:
47488                     return getTypeFromIndexedAccessTypeNode(node);
47489                 case 186 /* MappedType */:
47490                     return getTypeFromMappedTypeNode(node);
47491                 case 180 /* ConditionalType */:
47492                     return getTypeFromConditionalTypeNode(node);
47493                 case 181 /* InferType */:
47494                     return getTypeFromInferTypeNode(node);
47495                 case 188 /* ImportType */:
47496                     return getTypeFromImportTypeNode(node);
47497                 // This function assumes that an identifier or qualified name is a type expression
47498                 // Callers should first ensure this by calling isTypeNode
47499                 case 75 /* Identifier */:
47500                 case 153 /* QualifiedName */:
47501                     var symbol = getSymbolAtLocation(node);
47502                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
47503                 default:
47504                     return errorType;
47505             }
47506         }
47507         function instantiateList(items, mapper, instantiator) {
47508             if (items && items.length) {
47509                 for (var i = 0; i < items.length; i++) {
47510                     var item = items[i];
47511                     var mapped = instantiator(item, mapper);
47512                     if (item !== mapped) {
47513                         var result = i === 0 ? [] : items.slice(0, i);
47514                         result.push(mapped);
47515                         for (i++; i < items.length; i++) {
47516                             result.push(instantiator(items[i], mapper));
47517                         }
47518                         return result;
47519                     }
47520                 }
47521             }
47522             return items;
47523         }
47524         function instantiateTypes(types, mapper) {
47525             return instantiateList(types, mapper, instantiateType);
47526         }
47527         function instantiateSignatures(signatures, mapper) {
47528             return instantiateList(signatures, mapper, instantiateSignature);
47529         }
47530         function createTypeMapper(sources, targets) {
47531             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
47532         }
47533         function getMappedType(type, mapper) {
47534             switch (mapper.kind) {
47535                 case 0 /* Simple */:
47536                     return type === mapper.source ? mapper.target : type;
47537                 case 1 /* Array */:
47538                     var sources = mapper.sources;
47539                     var targets = mapper.targets;
47540                     for (var i = 0; i < sources.length; i++) {
47541                         if (type === sources[i]) {
47542                             return targets ? targets[i] : anyType;
47543                         }
47544                     }
47545                     return type;
47546                 case 2 /* Function */:
47547                     return mapper.func(type);
47548                 case 3 /* Composite */:
47549                 case 4 /* Merged */:
47550                     var t1 = getMappedType(type, mapper.mapper1);
47551                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
47552             }
47553         }
47554         function makeUnaryTypeMapper(source, target) {
47555             return { kind: 0 /* Simple */, source: source, target: target };
47556         }
47557         function makeArrayTypeMapper(sources, targets) {
47558             return { kind: 1 /* Array */, sources: sources, targets: targets };
47559         }
47560         function makeFunctionTypeMapper(func) {
47561             return { kind: 2 /* Function */, func: func };
47562         }
47563         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
47564             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
47565         }
47566         function createTypeEraser(sources) {
47567             return createTypeMapper(sources, /*targets*/ undefined);
47568         }
47569         /**
47570          * Maps forward-references to later types parameters to the empty object type.
47571          * This is used during inference when instantiating type parameter defaults.
47572          */
47573         function createBackreferenceMapper(context, index) {
47574             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
47575         }
47576         function combineTypeMappers(mapper1, mapper2) {
47577             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
47578         }
47579         function mergeTypeMappers(mapper1, mapper2) {
47580             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
47581         }
47582         function prependTypeMapping(source, target, mapper) {
47583             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
47584         }
47585         function appendTypeMapping(mapper, source, target) {
47586             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
47587         }
47588         function getRestrictiveTypeParameter(tp) {
47589             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
47590                 tp.restrictiveInstantiation.constraint = unknownType,
47591                 tp.restrictiveInstantiation);
47592         }
47593         function cloneTypeParameter(typeParameter) {
47594             var result = createTypeParameter(typeParameter.symbol);
47595             result.target = typeParameter;
47596             return result;
47597         }
47598         function instantiateTypePredicate(predicate, mapper) {
47599             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
47600         }
47601         function instantiateSignature(signature, mapper, eraseTypeParameters) {
47602             var freshTypeParameters;
47603             if (signature.typeParameters && !eraseTypeParameters) {
47604                 // First create a fresh set of type parameters, then include a mapping from the old to the
47605                 // new type parameters in the mapper function. Finally store this mapper in the new type
47606                 // parameters such that we can use it when instantiating constraints.
47607                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
47608                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
47609                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
47610                     var tp = freshTypeParameters_1[_i];
47611                     tp.mapper = mapper;
47612                 }
47613             }
47614             // Don't compute resolvedReturnType and resolvedTypePredicate now,
47615             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
47616             // See GH#17600.
47617             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
47618             /*resolvedReturnType*/ undefined, 
47619             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
47620             result.target = signature;
47621             result.mapper = mapper;
47622             return result;
47623         }
47624         function instantiateSymbol(symbol, mapper) {
47625             var links = getSymbolLinks(symbol);
47626             if (links.type && !couldContainTypeVariables(links.type)) {
47627                 // If the type of the symbol is already resolved, and if that type could not possibly
47628                 // be affected by instantiation, simply return the symbol itself.
47629                 return symbol;
47630             }
47631             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
47632                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
47633                 // type mappers. This ensures that original type identities are properly preserved and that aliases
47634                 // always reference a non-aliases.
47635                 symbol = links.target;
47636                 mapper = combineTypeMappers(links.mapper, mapper);
47637             }
47638             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
47639             // also transient so that we can just store data on it directly.
47640             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
47641             result.declarations = symbol.declarations;
47642             result.parent = symbol.parent;
47643             result.target = symbol;
47644             result.mapper = mapper;
47645             if (symbol.valueDeclaration) {
47646                 result.valueDeclaration = symbol.valueDeclaration;
47647             }
47648             if (links.nameType) {
47649                 result.nameType = links.nameType;
47650             }
47651             return result;
47652         }
47653         function getObjectTypeInstantiation(type, mapper) {
47654             var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
47655             var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
47656             var links = getNodeLinks(node);
47657             var typeParameters = links.outerTypeParameters;
47658             if (!typeParameters) {
47659                 // The first time an anonymous type is instantiated we compute and store a list of the type
47660                 // parameters that are in scope (and therefore potentially referenced). For type literals that
47661                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
47662                 // set of type parameters to those that are possibly referenced in the literal.
47663                 var declaration_1 = node;
47664                 if (ts.isInJSFile(declaration_1)) {
47665                     var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
47666                     if (paramTag) {
47667                         var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
47668                         if (paramSymbol) {
47669                             declaration_1 = paramSymbol.valueDeclaration;
47670                         }
47671                     }
47672                 }
47673                 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
47674                 if (isJSConstructor(declaration_1)) {
47675                     var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
47676                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
47677                 }
47678                 typeParameters = outerTypeParameters || ts.emptyArray;
47679                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
47680                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
47681                     typeParameters;
47682                 links.outerTypeParameters = typeParameters;
47683                 if (typeParameters.length) {
47684                     links.instantiations = ts.createMap();
47685                     links.instantiations.set(getTypeListId(typeParameters), target);
47686                 }
47687             }
47688             if (typeParameters.length) {
47689                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
47690                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47691                 // instantiation cache key from the type IDs of the type arguments.
47692                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
47693                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
47694                 var id = getTypeListId(typeArguments);
47695                 var result = links.instantiations.get(id);
47696                 if (!result) {
47697                     var newMapper = createTypeMapper(typeParameters, typeArguments);
47698                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
47699                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
47700                             instantiateAnonymousType(target, newMapper);
47701                     links.instantiations.set(id, result);
47702                 }
47703                 return result;
47704             }
47705             return type;
47706         }
47707         function maybeTypeParameterReference(node) {
47708             return !(node.kind === 153 /* QualifiedName */ ||
47709                 node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
47710                 node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
47711         }
47712         function isTypeParameterPossiblyReferenced(tp, node) {
47713             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
47714             // between the node and the type parameter declaration, if the node contains actual references to the
47715             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
47716             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
47717                 var container = tp.symbol.declarations[0].parent;
47718                 for (var n = node; n !== container; n = n.parent) {
47719                     if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
47720                         return true;
47721                     }
47722                 }
47723                 return !!ts.forEachChild(node, containsReference);
47724             }
47725             return true;
47726             function containsReference(node) {
47727                 switch (node.kind) {
47728                     case 183 /* ThisType */:
47729                         return !!tp.isThisType;
47730                     case 75 /* Identifier */:
47731                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
47732                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
47733                     case 172 /* TypeQuery */:
47734                         return true;
47735                 }
47736                 return !!ts.forEachChild(node, containsReference);
47737             }
47738         }
47739         function getHomomorphicTypeVariable(type) {
47740             var constraintType = getConstraintTypeFromMappedType(type);
47741             if (constraintType.flags & 4194304 /* Index */) {
47742                 var typeVariable = getActualTypeVariable(constraintType.type);
47743                 if (typeVariable.flags & 262144 /* TypeParameter */) {
47744                     return typeVariable;
47745                 }
47746             }
47747             return undefined;
47748         }
47749         function instantiateMappedType(type, mapper) {
47750             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
47751             // operation depends on T as follows:
47752             // * If T is a primitive type no mapping is performed and the result is simply T.
47753             // * If T is a union type we distribute the mapped type over the union.
47754             // * If T is an array we map to an array where the element type has been transformed.
47755             // * If T is a tuple we map to a tuple where the element types have been transformed.
47756             // * Otherwise we map to an object type where the type of each property has been transformed.
47757             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
47758             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
47759             // { [P in keyof A]: X } | undefined.
47760             var typeVariable = getHomomorphicTypeVariable(type);
47761             if (typeVariable) {
47762                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
47763                 if (typeVariable !== mappedTypeVariable) {
47764                     return mapType(getReducedType(mappedTypeVariable), function (t) {
47765                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
47766                             var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
47767                             return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
47768                                 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
47769                                     instantiateAnonymousType(type, replacementMapper);
47770                         }
47771                         return t;
47772                     });
47773                 }
47774             }
47775             return instantiateAnonymousType(type, mapper);
47776         }
47777         function getModifiedReadonlyState(state, modifiers) {
47778             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
47779         }
47780         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
47781             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
47782             return elementType === errorType ? errorType :
47783                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
47784         }
47785         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
47786             var minLength = tupleType.target.minLength;
47787             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
47788                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
47789             });
47790             var modifiers = getMappedTypeModifiers(mappedType);
47791             var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
47792                 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
47793                     minLength;
47794             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
47795             return ts.contains(elementTypes, errorType) ? errorType :
47796                 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
47797         }
47798         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
47799             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
47800             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
47801             var modifiers = getMappedTypeModifiers(type);
47802             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
47803                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
47804                     propType;
47805         }
47806         function instantiateAnonymousType(type, mapper) {
47807             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
47808             if (type.objectFlags & 32 /* Mapped */) {
47809                 result.declaration = type.declaration;
47810                 // C.f. instantiateSignature
47811                 var origTypeParameter = getTypeParameterFromMappedType(type);
47812                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
47813                 result.typeParameter = freshTypeParameter;
47814                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
47815                 freshTypeParameter.mapper = mapper;
47816             }
47817             result.target = type;
47818             result.mapper = mapper;
47819             result.aliasSymbol = type.aliasSymbol;
47820             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
47821             return result;
47822         }
47823         function getConditionalTypeInstantiation(type, mapper) {
47824             var root = type.root;
47825             if (root.outerTypeParameters) {
47826                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
47827                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47828                 // instantiation cache key from the type IDs of the type arguments.
47829                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
47830                 var id = getTypeListId(typeArguments);
47831                 var result = root.instantiations.get(id);
47832                 if (!result) {
47833                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
47834                     result = instantiateConditionalType(root, newMapper);
47835                     root.instantiations.set(id, result);
47836                 }
47837                 return result;
47838             }
47839             return type;
47840         }
47841         function instantiateConditionalType(root, mapper) {
47842             // Check if we have a conditional type where the check type is a naked type parameter. If so,
47843             // the conditional type is distributive over union types and when T is instantiated to a union
47844             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
47845             if (root.isDistributive) {
47846                 var checkType_1 = root.checkType;
47847                 var instantiatedType = getMappedType(checkType_1, mapper);
47848                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
47849                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
47850                 }
47851             }
47852             return getConditionalType(root, mapper);
47853         }
47854         function instantiateType(type, mapper) {
47855             if (!type || !mapper) {
47856                 return type;
47857             }
47858             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
47859                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
47860                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
47861                 // the recursion here by yielding the error type.
47862                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
47863                 return errorType;
47864             }
47865             totalInstantiationCount++;
47866             instantiationCount++;
47867             instantiationDepth++;
47868             var result = instantiateTypeWorker(type, mapper);
47869             instantiationDepth--;
47870             return result;
47871         }
47872         /**
47873          * This can be used to avoid the penalty on instantiation depth for types which result from immediate
47874          * simplification. It essentially removes the depth increase done in `instantiateType`.
47875          */
47876         function instantiateTypeWithoutDepthIncrease(type, mapper) {
47877             instantiationDepth--;
47878             var result = instantiateType(type, mapper);
47879             instantiationDepth++;
47880             return result;
47881         }
47882         function instantiateTypeWorker(type, mapper) {
47883             var flags = type.flags;
47884             if (flags & 262144 /* TypeParameter */) {
47885                 return getMappedType(type, mapper);
47886             }
47887             if (flags & 524288 /* Object */) {
47888                 var objectFlags = type.objectFlags;
47889                 if (objectFlags & 16 /* Anonymous */) {
47890                     // If the anonymous type originates in a declaration of a function, method, class, or
47891                     // interface, in an object type literal, or in an object literal expression, we may need
47892                     // to instantiate the type because it might reference a type parameter.
47893                     return couldContainTypeVariables(type) ?
47894                         getObjectTypeInstantiation(type, mapper) : type;
47895                 }
47896                 if (objectFlags & 32 /* Mapped */) {
47897                     return getObjectTypeInstantiation(type, mapper);
47898                 }
47899                 if (objectFlags & 4 /* Reference */) {
47900                     if (type.node) {
47901                         return getObjectTypeInstantiation(type, mapper);
47902                     }
47903                     var resolvedTypeArguments = type.resolvedTypeArguments;
47904                     var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
47905                     return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
47906                 }
47907                 return type;
47908             }
47909             if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) {
47910                 if (!couldContainTypeVariables(type)) {
47911                     return type;
47912                 }
47913                 var types = type.types;
47914                 var newTypes = instantiateTypes(types, mapper);
47915                 return newTypes === types
47916                     ? type
47917                     : (flags & 2097152 /* Intersection */)
47918                         ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper))
47919                         : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47920             }
47921             if (flags & 4194304 /* Index */) {
47922                 return getIndexType(instantiateType(type.type, mapper));
47923             }
47924             if (flags & 8388608 /* IndexedAccess */) {
47925                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47926             }
47927             if (flags & 16777216 /* Conditional */) {
47928                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
47929             }
47930             if (flags & 33554432 /* Substitution */) {
47931                 var maybeVariable = instantiateType(type.baseType, mapper);
47932                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
47933                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
47934                 }
47935                 else {
47936                     var sub = instantiateType(type.substitute, mapper);
47937                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
47938                         return maybeVariable;
47939                     }
47940                     return sub;
47941                 }
47942             }
47943             return type;
47944         }
47945         function getPermissiveInstantiation(type) {
47946             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
47947                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
47948         }
47949         function getRestrictiveInstantiation(type) {
47950             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
47951                 return type;
47952             }
47953             if (type.restrictiveInstantiation) {
47954                 return type.restrictiveInstantiation;
47955             }
47956             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
47957             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
47958             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
47959             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
47960             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
47961             // are constrained to `unknown` and produce tons of false positives/negatives!
47962             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
47963             return type.restrictiveInstantiation;
47964         }
47965         function instantiateIndexInfo(info, mapper) {
47966             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
47967         }
47968         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
47969         // that is subject to contextual typing.
47970         function isContextSensitive(node) {
47971             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
47972             switch (node.kind) {
47973                 case 201 /* FunctionExpression */:
47974                 case 202 /* ArrowFunction */:
47975                 case 161 /* MethodDeclaration */:
47976                 case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
47977                     return isContextSensitiveFunctionLikeDeclaration(node);
47978                 case 193 /* ObjectLiteralExpression */:
47979                     return ts.some(node.properties, isContextSensitive);
47980                 case 192 /* ArrayLiteralExpression */:
47981                     return ts.some(node.elements, isContextSensitive);
47982                 case 210 /* ConditionalExpression */:
47983                     return isContextSensitive(node.whenTrue) ||
47984                         isContextSensitive(node.whenFalse);
47985                 case 209 /* BinaryExpression */:
47986                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
47987                         (isContextSensitive(node.left) || isContextSensitive(node.right));
47988                 case 281 /* PropertyAssignment */:
47989                     return isContextSensitive(node.initializer);
47990                 case 200 /* ParenthesizedExpression */:
47991                     return isContextSensitive(node.expression);
47992                 case 274 /* JsxAttributes */:
47993                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
47994                 case 273 /* JsxAttribute */: {
47995                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
47996                     var initializer = node.initializer;
47997                     return !!initializer && isContextSensitive(initializer);
47998                 }
47999                 case 276 /* JsxExpression */: {
48000                     // It is possible to that node.expression is undefined (e.g <div x={} />)
48001                     var expression = node.expression;
48002                     return !!expression && isContextSensitive(expression);
48003                 }
48004             }
48005             return false;
48006         }
48007         function isContextSensitiveFunctionLikeDeclaration(node) {
48008             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
48009                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
48010         }
48011         function hasContextSensitiveParameters(node) {
48012             // Functions with type parameters are not context sensitive.
48013             if (!node.typeParameters) {
48014                 // Functions with any parameters that lack type annotations are context sensitive.
48015                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
48016                     return true;
48017                 }
48018                 if (node.kind !== 202 /* ArrowFunction */) {
48019                     // If the first parameter is not an explicit 'this' parameter, then the function has
48020                     // an implicit 'this' parameter which is subject to contextual typing.
48021                     var parameter = ts.firstOrUndefined(node.parameters);
48022                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
48023                         return true;
48024                     }
48025                 }
48026             }
48027             return false;
48028         }
48029         function hasContextSensitiveReturnExpression(node) {
48030             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
48031             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
48032         }
48033         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
48034             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
48035                 isContextSensitiveFunctionLikeDeclaration(func);
48036         }
48037         function getTypeWithoutSignatures(type) {
48038             if (type.flags & 524288 /* Object */) {
48039                 var resolved = resolveStructuredTypeMembers(type);
48040                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
48041                     var result = createObjectType(16 /* Anonymous */, type.symbol);
48042                     result.members = resolved.members;
48043                     result.properties = resolved.properties;
48044                     result.callSignatures = ts.emptyArray;
48045                     result.constructSignatures = ts.emptyArray;
48046                     return result;
48047                 }
48048             }
48049             else if (type.flags & 2097152 /* Intersection */) {
48050                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
48051             }
48052             return type;
48053         }
48054         // TYPE CHECKING
48055         function isTypeIdenticalTo(source, target) {
48056             return isTypeRelatedTo(source, target, identityRelation);
48057         }
48058         function compareTypesIdentical(source, target) {
48059             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
48060         }
48061         function compareTypesAssignable(source, target) {
48062             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
48063         }
48064         function compareTypesSubtypeOf(source, target) {
48065             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
48066         }
48067         function isTypeSubtypeOf(source, target) {
48068             return isTypeRelatedTo(source, target, subtypeRelation);
48069         }
48070         function isTypeAssignableTo(source, target) {
48071             return isTypeRelatedTo(source, target, assignableRelation);
48072         }
48073         // An object type S is considered to be derived from an object type T if
48074         // S is a union type and every constituent of S is derived from T,
48075         // T is a union type and S is derived from at least one constituent of T, or
48076         // S is a type variable with a base constraint that is derived from T,
48077         // T is one of the global types Object and Function and S is a subtype of T, or
48078         // T occurs directly or indirectly in an 'extends' clause of S.
48079         // Note that this check ignores type parameters and only considers the
48080         // inheritance hierarchy.
48081         function isTypeDerivedFrom(source, target) {
48082             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
48083                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
48084                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
48085                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
48086                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
48087                                 hasBaseType(source, getTargetType(target));
48088         }
48089         /**
48090          * This is *not* a bi-directional relationship.
48091          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
48092          *
48093          * 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.
48094          * It is used to check following cases:
48095          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
48096          *   - the types of `case` clause expressions and their respective `switch` expressions.
48097          *   - the type of an expression in a type assertion with the type being asserted.
48098          */
48099         function isTypeComparableTo(source, target) {
48100             return isTypeRelatedTo(source, target, comparableRelation);
48101         }
48102         function areTypesComparable(type1, type2) {
48103             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
48104         }
48105         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
48106             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
48107         }
48108         /**
48109          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
48110          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
48111          */
48112         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
48113             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
48114         }
48115         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
48116             if (isTypeRelatedTo(source, target, relation))
48117                 return true;
48118             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
48119                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
48120             }
48121             return false;
48122         }
48123         function isOrHasGenericConditional(type) {
48124             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
48125         }
48126         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
48127             if (!node || isOrHasGenericConditional(target))
48128                 return false;
48129             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
48130                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
48131                 return true;
48132             }
48133             switch (node.kind) {
48134                 case 276 /* JsxExpression */:
48135                 case 200 /* ParenthesizedExpression */:
48136                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
48137                 case 209 /* BinaryExpression */:
48138                     switch (node.operatorToken.kind) {
48139                         case 62 /* EqualsToken */:
48140                         case 27 /* CommaToken */:
48141                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
48142                     }
48143                     break;
48144                 case 193 /* ObjectLiteralExpression */:
48145                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
48146                 case 192 /* ArrayLiteralExpression */:
48147                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
48148                 case 274 /* JsxAttributes */:
48149                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
48150                 case 202 /* ArrowFunction */:
48151                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
48152             }
48153             return false;
48154         }
48155         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
48156             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
48157             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
48158             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
48159                 var signatures = _a[_i];
48160                 if (ts.some(signatures, function (s) {
48161                     var returnType = getReturnTypeOfSignature(s);
48162                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
48163                 })) {
48164                     var resultObj = errorOutputContainer || {};
48165                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
48166                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
48167                     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));
48168                     return true;
48169                 }
48170             }
48171             return false;
48172         }
48173         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48174             // Don't elaborate blocks
48175             if (ts.isBlock(node.body)) {
48176                 return false;
48177             }
48178             // Or functions with annotated parameter types
48179             if (ts.some(node.parameters, ts.hasType)) {
48180                 return false;
48181             }
48182             var sourceSig = getSingleCallSignature(source);
48183             if (!sourceSig) {
48184                 return false;
48185             }
48186             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
48187             if (!ts.length(targetSignatures)) {
48188                 return false;
48189             }
48190             var returnExpression = node.body;
48191             var sourceReturn = getReturnTypeOfSignature(sourceSig);
48192             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
48193             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
48194                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48195                 if (elaborated) {
48196                     return elaborated;
48197                 }
48198                 var resultObj = errorOutputContainer || {};
48199                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
48200                 if (resultObj.errors) {
48201                     if (target.symbol && ts.length(target.symbol.declarations)) {
48202                         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));
48203                     }
48204                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
48205                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
48206                         // an IPromise and a Promise that are slightly different
48207                         && !getTypeOfPropertyOfType(sourceReturn, "then")
48208                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
48209                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
48210                     }
48211                     return true;
48212                 }
48213             }
48214             return false;
48215         }
48216         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
48217             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
48218             if (idx) {
48219                 return idx;
48220             }
48221             if (target.flags & 1048576 /* Union */) {
48222                 var best = getBestMatchingType(source, target);
48223                 if (best) {
48224                     return getIndexedAccessTypeOrUndefined(best, nameType);
48225                 }
48226             }
48227         }
48228         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
48229             next.contextualType = sourcePropType;
48230             try {
48231                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
48232             }
48233             finally {
48234                 next.contextualType = undefined;
48235             }
48236         }
48237         /**
48238          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
48239          * 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`
48240          * Otherwise, we issue an error on _every_ element which fail the assignability check
48241          */
48242         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
48243             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
48244             var reportedError = false;
48245             for (var status = iterator.next(); !status.done; status = iterator.next()) {
48246                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
48247                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
48248                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
48249                     continue; // Don't elaborate on indexes on generic variables
48250                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
48251                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
48252                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48253                     if (elaborated) {
48254                         reportedError = true;
48255                     }
48256                     else {
48257                         // Issue error on the prop itself, since the prop couldn't elaborate the error
48258                         var resultObj = errorOutputContainer || {};
48259                         // Use the expression type, if available
48260                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
48261                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48262                         if (result && specificSource !== sourcePropType) {
48263                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
48264                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48265                         }
48266                         if (resultObj.errors) {
48267                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
48268                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
48269                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
48270                             var issuedElaboration = false;
48271                             if (!targetProp) {
48272                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
48273                                     getIndexInfoOfType(target, 0 /* String */) ||
48274                                     undefined;
48275                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
48276                                     issuedElaboration = true;
48277                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
48278                                 }
48279                             }
48280                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
48281                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
48282                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
48283                                     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)));
48284                                 }
48285                             }
48286                         }
48287                         reportedError = true;
48288                     }
48289                 }
48290             }
48291             return reportedError;
48292         }
48293         function generateJsxAttributes(node) {
48294             var _i, _a, prop;
48295             return __generator(this, function (_b) {
48296                 switch (_b.label) {
48297                     case 0:
48298                         if (!ts.length(node.properties))
48299                             return [2 /*return*/];
48300                         _i = 0, _a = node.properties;
48301                         _b.label = 1;
48302                     case 1:
48303                         if (!(_i < _a.length)) return [3 /*break*/, 4];
48304                         prop = _a[_i];
48305                         if (ts.isJsxSpreadAttribute(prop))
48306                             return [3 /*break*/, 3];
48307                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
48308                     case 2:
48309                         _b.sent();
48310                         _b.label = 3;
48311                     case 3:
48312                         _i++;
48313                         return [3 /*break*/, 1];
48314                     case 4: return [2 /*return*/];
48315                 }
48316             });
48317         }
48318         function generateJsxChildren(node, getInvalidTextDiagnostic) {
48319             var memberOffset, i, child, nameType, elem;
48320             return __generator(this, function (_a) {
48321                 switch (_a.label) {
48322                     case 0:
48323                         if (!ts.length(node.children))
48324                             return [2 /*return*/];
48325                         memberOffset = 0;
48326                         i = 0;
48327                         _a.label = 1;
48328                     case 1:
48329                         if (!(i < node.children.length)) return [3 /*break*/, 5];
48330                         child = node.children[i];
48331                         nameType = getLiteralType(i - memberOffset);
48332                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
48333                         if (!elem) return [3 /*break*/, 3];
48334                         return [4 /*yield*/, elem];
48335                     case 2:
48336                         _a.sent();
48337                         return [3 /*break*/, 4];
48338                     case 3:
48339                         memberOffset++;
48340                         _a.label = 4;
48341                     case 4:
48342                         i++;
48343                         return [3 /*break*/, 1];
48344                     case 5: return [2 /*return*/];
48345                 }
48346             });
48347         }
48348         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
48349             switch (child.kind) {
48350                 case 276 /* JsxExpression */:
48351                     // child is of the type of the expression
48352                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
48353                 case 11 /* JsxText */:
48354                     if (child.containsOnlyTriviaWhiteSpaces) {
48355                         break; // Whitespace only jsx text isn't real jsx text
48356                     }
48357                     // child is a string
48358                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
48359                 case 266 /* JsxElement */:
48360                 case 267 /* JsxSelfClosingElement */:
48361                 case 270 /* JsxFragment */:
48362                     // child is of type JSX.Element
48363                     return { errorNode: child, innerExpression: child, nameType: nameType };
48364                 default:
48365                     return ts.Debug.assertNever(child, "Found invalid jsx child");
48366             }
48367         }
48368         function getSemanticJsxChildren(children) {
48369             return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
48370         }
48371         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48372             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
48373             var invalidTextDiagnostic;
48374             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
48375                 var containingElement = node.parent.parent;
48376                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48377                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48378                 var childrenNameType = getLiteralType(childrenPropName);
48379                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
48380                 var validChildren = getSemanticJsxChildren(containingElement.children);
48381                 if (!ts.length(validChildren)) {
48382                     return result;
48383                 }
48384                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
48385                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
48386                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
48387                 if (moreThanOneRealChildren) {
48388                     if (arrayLikeTargetParts !== neverType) {
48389                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
48390                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
48391                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
48392                     }
48393                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48394                         // arity mismatch
48395                         result = true;
48396                         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));
48397                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48398                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48399                         }
48400                     }
48401                 }
48402                 else {
48403                     if (nonArrayLikeTargetParts !== neverType) {
48404                         var child = validChildren[0];
48405                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
48406                         if (elem_1) {
48407                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
48408                                 switch (_a.label) {
48409                                     case 0: return [4 /*yield*/, elem_1];
48410                                     case 1:
48411                                         _a.sent();
48412                                         return [2 /*return*/];
48413                                 }
48414                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
48415                         }
48416                     }
48417                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48418                         // arity mismatch
48419                         result = true;
48420                         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));
48421                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48422                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48423                         }
48424                     }
48425                 }
48426             }
48427             return result;
48428             function getInvalidTextualChildDiagnostic() {
48429                 if (!invalidTextDiagnostic) {
48430                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
48431                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48432                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48433                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
48434                     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;
48435                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
48436                 }
48437                 return invalidTextDiagnostic;
48438             }
48439         }
48440         function generateLimitedTupleElements(node, target) {
48441             var len, i, elem, nameType;
48442             return __generator(this, function (_a) {
48443                 switch (_a.label) {
48444                     case 0:
48445                         len = ts.length(node.elements);
48446                         if (!len)
48447                             return [2 /*return*/];
48448                         i = 0;
48449                         _a.label = 1;
48450                     case 1:
48451                         if (!(i < len)) return [3 /*break*/, 4];
48452                         // 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
48453                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
48454                             return [3 /*break*/, 3];
48455                         elem = node.elements[i];
48456                         if (ts.isOmittedExpression(elem))
48457                             return [3 /*break*/, 3];
48458                         nameType = getLiteralType(i);
48459                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
48460                     case 2:
48461                         _a.sent();
48462                         _a.label = 3;
48463                     case 3:
48464                         i++;
48465                         return [3 /*break*/, 1];
48466                     case 4: return [2 /*return*/];
48467                 }
48468             });
48469         }
48470         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48471             if (target.flags & 131068 /* Primitive */)
48472                 return false;
48473             if (isTupleLikeType(source)) {
48474                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
48475             }
48476             // recreate a tuple from the elements, if possible
48477             // Since we're re-doing the expression type, we need to reapply the contextual type
48478             var oldContext = node.contextualType;
48479             node.contextualType = target;
48480             try {
48481                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
48482                 node.contextualType = oldContext;
48483                 if (isTupleLikeType(tupleizedType)) {
48484                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
48485                 }
48486                 return false;
48487             }
48488             finally {
48489                 node.contextualType = oldContext;
48490             }
48491         }
48492         function generateObjectLiteralElements(node) {
48493             var _i, _a, prop, type, _b;
48494             return __generator(this, function (_c) {
48495                 switch (_c.label) {
48496                     case 0:
48497                         if (!ts.length(node.properties))
48498                             return [2 /*return*/];
48499                         _i = 0, _a = node.properties;
48500                         _c.label = 1;
48501                     case 1:
48502                         if (!(_i < _a.length)) return [3 /*break*/, 8];
48503                         prop = _a[_i];
48504                         if (ts.isSpreadAssignment(prop))
48505                             return [3 /*break*/, 7];
48506                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
48507                         if (!type || (type.flags & 131072 /* Never */)) {
48508                             return [3 /*break*/, 7];
48509                         }
48510                         _b = prop.kind;
48511                         switch (_b) {
48512                             case 164 /* SetAccessor */: return [3 /*break*/, 2];
48513                             case 163 /* GetAccessor */: return [3 /*break*/, 2];
48514                             case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
48515                             case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
48516                             case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
48517                         }
48518                         return [3 /*break*/, 6];
48519                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
48520                     case 3:
48521                         _c.sent();
48522                         return [3 /*break*/, 7];
48523                     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 }];
48524                     case 5:
48525                         _c.sent();
48526                         return [3 /*break*/, 7];
48527                     case 6:
48528                         ts.Debug.assertNever(prop);
48529                         _c.label = 7;
48530                     case 7:
48531                         _i++;
48532                         return [3 /*break*/, 1];
48533                     case 8: return [2 /*return*/];
48534                 }
48535             });
48536         }
48537         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48538             if (target.flags & 131068 /* Primitive */)
48539                 return false;
48540             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
48541         }
48542         /**
48543          * This is *not* a bi-directional relationship.
48544          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
48545          */
48546         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
48547             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
48548         }
48549         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
48550             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
48551             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
48552         }
48553         /**
48554          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
48555          */
48556         function isAnySignature(s) {
48557             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
48558                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
48559                 isTypeAny(getReturnTypeOfSignature(s));
48560         }
48561         /**
48562          * See signatureRelatedTo, compareSignaturesIdentical
48563          */
48564         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
48565             // TODO (drosen): De-duplicate code between related functions.
48566             if (source === target) {
48567                 return -1 /* True */;
48568             }
48569             if (isAnySignature(target)) {
48570                 return -1 /* True */;
48571             }
48572             var targetCount = getParameterCount(target);
48573             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
48574                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
48575             if (sourceHasMoreParameters) {
48576                 return 0 /* False */;
48577             }
48578             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
48579                 target = getCanonicalSignature(target);
48580                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
48581             }
48582             var sourceCount = getParameterCount(source);
48583             var sourceRestType = getNonArrayRestType(source);
48584             var targetRestType = getNonArrayRestType(target);
48585             if (sourceRestType || targetRestType) {
48586                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
48587             }
48588             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
48589                 // We're not able to relate misaligned complex rest parameters
48590                 return 0 /* False */;
48591             }
48592             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
48593             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
48594                 kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
48595             var result = -1 /* True */;
48596             var sourceThisType = getThisTypeOfSignature(source);
48597             if (sourceThisType && sourceThisType !== voidType) {
48598                 var targetThisType = getThisTypeOfSignature(target);
48599                 if (targetThisType) {
48600                     // void sources are assignable to anything.
48601                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
48602                         || compareTypes(targetThisType, sourceThisType, reportErrors);
48603                     if (!related) {
48604                         if (reportErrors) {
48605                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
48606                         }
48607                         return 0 /* False */;
48608                     }
48609                     result &= related;
48610                 }
48611             }
48612             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
48613             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
48614             for (var i = 0; i < paramCount; i++) {
48615                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
48616                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
48617                 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
48618                 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
48619                 // they naturally relate only contra-variantly). However, if the source and target parameters both have
48620                 // function types with a single call signature, we know we are relating two callback parameters. In
48621                 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
48622                 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
48623                 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
48624                 // with respect to T.
48625                 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
48626                 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
48627                 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
48628                     (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
48629                 var related = callbacks ?
48630                     compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
48631                     !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
48632                 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
48633                 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
48634                     related = 0 /* False */;
48635                 }
48636                 if (!related) {
48637                     if (reportErrors) {
48638                         errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
48639                     }
48640                     return 0 /* False */;
48641                 }
48642                 result &= related;
48643             }
48644             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
48645                 // If a signature resolution is already in-flight, skip issuing a circularity error
48646                 // here and just use the `any` type directly
48647                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
48648                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
48649                         : getReturnTypeOfSignature(target);
48650                 if (targetReturnType === voidType) {
48651                     return result;
48652                 }
48653                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
48654                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
48655                         : getReturnTypeOfSignature(source);
48656                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
48657                 var targetTypePredicate = getTypePredicateOfSignature(target);
48658                 if (targetTypePredicate) {
48659                     var sourceTypePredicate = getTypePredicateOfSignature(source);
48660                     if (sourceTypePredicate) {
48661                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
48662                     }
48663                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
48664                         if (reportErrors) {
48665                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
48666                         }
48667                         return 0 /* False */;
48668                     }
48669                 }
48670                 else {
48671                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
48672                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
48673                     // wouldn't be co-variant for T without this rule.
48674                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
48675                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
48676                     if (!result && reportErrors && incompatibleErrorReporter) {
48677                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
48678                     }
48679                 }
48680             }
48681             return result;
48682         }
48683         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
48684             if (source.kind !== target.kind) {
48685                 if (reportErrors) {
48686                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
48687                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48688                 }
48689                 return 0 /* False */;
48690             }
48691             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
48692                 if (source.parameterIndex !== target.parameterIndex) {
48693                     if (reportErrors) {
48694                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
48695                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48696                     }
48697                     return 0 /* False */;
48698                 }
48699             }
48700             var related = source.type === target.type ? -1 /* True */ :
48701                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
48702                     0 /* False */;
48703             if (related === 0 /* False */ && reportErrors) {
48704                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48705             }
48706             return related;
48707         }
48708         function isImplementationCompatibleWithOverload(implementation, overload) {
48709             var erasedSource = getErasedSignature(implementation);
48710             var erasedTarget = getErasedSignature(overload);
48711             // First see if the return types are compatible in either direction.
48712             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
48713             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
48714             if (targetReturnType === voidType
48715                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
48716                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
48717                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
48718             }
48719             return false;
48720         }
48721         function isEmptyResolvedType(t) {
48722             return t !== anyFunctionType &&
48723                 t.properties.length === 0 &&
48724                 t.callSignatures.length === 0 &&
48725                 t.constructSignatures.length === 0 &&
48726                 !t.stringIndexInfo &&
48727                 !t.numberIndexInfo;
48728         }
48729         function isEmptyObjectType(type) {
48730             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
48731                 type.flags & 67108864 /* NonPrimitive */ ? true :
48732                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
48733                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
48734                             false;
48735         }
48736         function isEmptyAnonymousObjectType(type) {
48737             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
48738         }
48739         function isStringIndexSignatureOnlyType(type) {
48740             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
48741                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
48742                 false;
48743         }
48744         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
48745             if (sourceSymbol === targetSymbol) {
48746                 return true;
48747             }
48748             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
48749             var entry = enumRelation.get(id);
48750             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
48751                 return !!(entry & 1 /* Succeeded */);
48752             }
48753             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
48754                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48755                 return false;
48756             }
48757             var targetEnumType = getTypeOfSymbol(targetSymbol);
48758             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
48759                 var property = _a[_i];
48760                 if (property.flags & 8 /* EnumMember */) {
48761                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
48762                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
48763                         if (errorReporter) {
48764                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
48765                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48766                         }
48767                         else {
48768                             enumRelation.set(id, 2 /* Failed */);
48769                         }
48770                         return false;
48771                     }
48772                 }
48773             }
48774             enumRelation.set(id, 1 /* Succeeded */);
48775             return true;
48776         }
48777         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
48778             var s = source.flags;
48779             var t = target.flags;
48780             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
48781                 return true;
48782             if (t & 131072 /* Never */)
48783                 return false;
48784             if (s & 132 /* StringLike */ && t & 4 /* String */)
48785                 return true;
48786             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
48787                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48788                 source.value === target.value)
48789                 return true;
48790             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
48791                 return true;
48792             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
48793                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48794                 source.value === target.value)
48795                 return true;
48796             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
48797                 return true;
48798             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
48799                 return true;
48800             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
48801                 return true;
48802             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48803                 return true;
48804             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
48805                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48806                     return true;
48807                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
48808                     source.value === target.value &&
48809                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
48810                     return true;
48811             }
48812             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
48813                 return true;
48814             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
48815                 return true;
48816             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
48817                 return true;
48818             if (relation === assignableRelation || relation === comparableRelation) {
48819                 if (s & 1 /* Any */)
48820                     return true;
48821                 // Type number or any numeric literal type is assignable to any numeric enum type or any
48822                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
48823                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
48824                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
48825                     return true;
48826             }
48827             return false;
48828         }
48829         function isTypeRelatedTo(source, target, relation) {
48830             if (isFreshLiteralType(source)) {
48831                 source = source.regularType;
48832             }
48833             if (isFreshLiteralType(target)) {
48834                 target = target.regularType;
48835             }
48836             if (source === target) {
48837                 return true;
48838             }
48839             if (relation !== identityRelation) {
48840                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
48841                     return true;
48842                 }
48843             }
48844             else {
48845                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
48846                     source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
48847                     return false;
48848             }
48849             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
48850                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
48851                 if (related !== undefined) {
48852                     return !!(related & 1 /* Succeeded */);
48853                 }
48854             }
48855             if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
48856                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
48857             }
48858             return false;
48859         }
48860         function isIgnoredJsxProperty(source, sourceProp) {
48861             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
48862         }
48863         function getNormalizedType(type, writing) {
48864             while (true) {
48865                 var t = isFreshLiteralType(type) ? type.regularType :
48866                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
48867                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
48868                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
48869                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
48870                                     type;
48871                 if (t === type)
48872                     break;
48873                 type = t;
48874             }
48875             return type;
48876         }
48877         /**
48878          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
48879          * @param source The left-hand-side of the relation.
48880          * @param target The right-hand-side of the relation.
48881          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
48882          * Used as both to determine which checks are performed and as a cache of previously computed results.
48883          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
48884          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
48885          * @param containingMessageChain A chain of errors to prepend any new errors found.
48886          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
48887          */
48888         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
48889             var errorInfo;
48890             var relatedInfo;
48891             var maybeKeys;
48892             var sourceStack;
48893             var targetStack;
48894             var maybeCount = 0;
48895             var depth = 0;
48896             var expandingFlags = 0 /* None */;
48897             var overflow = false;
48898             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
48899             var lastSkippedInfo;
48900             var incompatibleStack = [];
48901             var inPropertyCheck = false;
48902             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
48903             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
48904             if (incompatibleStack.length) {
48905                 reportIncompatibleStack();
48906             }
48907             if (overflow) {
48908                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
48909                 if (errorOutputContainer) {
48910                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48911                 }
48912             }
48913             else if (errorInfo) {
48914                 if (containingMessageChain) {
48915                     var chain = containingMessageChain();
48916                     if (chain) {
48917                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
48918                         errorInfo = chain;
48919                     }
48920                 }
48921                 var relatedInformation = void 0;
48922                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
48923                 if (headMessage && errorNode && !result && source.symbol) {
48924                     var links = getSymbolLinks(source.symbol);
48925                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
48926                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
48927                         if (helpfulRetry) {
48928                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
48929                             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);
48930                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
48931                         }
48932                     }
48933                 }
48934                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
48935                 if (relatedInfo) {
48936                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
48937                 }
48938                 if (errorOutputContainer) {
48939                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48940                 }
48941                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
48942                     diagnostics.add(diag);
48943                 }
48944             }
48945             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
48946                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
48947             }
48948             return result !== 0 /* False */;
48949             function resetErrorInfo(saved) {
48950                 errorInfo = saved.errorInfo;
48951                 lastSkippedInfo = saved.lastSkippedInfo;
48952                 incompatibleStack = saved.incompatibleStack;
48953                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
48954                 relatedInfo = saved.relatedInfo;
48955             }
48956             function captureErrorCalculationState() {
48957                 return {
48958                     errorInfo: errorInfo,
48959                     lastSkippedInfo: lastSkippedInfo,
48960                     incompatibleStack: incompatibleStack.slice(),
48961                     overrideNextErrorInfo: overrideNextErrorInfo,
48962                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
48963                 };
48964             }
48965             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
48966                 overrideNextErrorInfo++; // Suppress the next relation error
48967                 lastSkippedInfo = undefined; // Reset skipped info cache
48968                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
48969             }
48970             function reportIncompatibleStack() {
48971                 var stack = incompatibleStack;
48972                 incompatibleStack = [];
48973                 var info = lastSkippedInfo;
48974                 lastSkippedInfo = undefined;
48975                 if (stack.length === 1) {
48976                     reportError.apply(void 0, stack[0]);
48977                     if (info) {
48978                         // Actually do the last relation error
48979                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48980                     }
48981                     return;
48982                 }
48983                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
48984                 // we can build from left to right
48985                 var path = "";
48986                 var secondaryRootErrors = [];
48987                 while (stack.length) {
48988                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
48989                     switch (msg.code) {
48990                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
48991                             // Parenthesize a `new` if there is one
48992                             if (path.indexOf("new ") === 0) {
48993                                 path = "(" + path + ")";
48994                             }
48995                             var str = "" + args[0];
48996                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
48997                             if (path.length === 0) {
48998                                 path = "" + str;
48999                             }
49000                             // Otherwise write a dotted name if possible
49001                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
49002                                 path = path + "." + str;
49003                             }
49004                             // Failing that, check if the name is already a computed name
49005                             else if (str[0] === "[" && str[str.length - 1] === "]") {
49006                                 path = "" + path + str;
49007                             }
49008                             // And finally write out a computed name as a last resort
49009                             else {
49010                                 path = path + "[" + str + "]";
49011                             }
49012                             break;
49013                         }
49014                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
49015                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
49016                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
49017                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
49018                             if (path.length === 0) {
49019                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
49020                                 // to unify (the with no arguments bit is excessive for printback) and print them back
49021                                 var mappedMsg = msg;
49022                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
49023                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
49024                                 }
49025                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
49026                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
49027                                 }
49028                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
49029                             }
49030                             else {
49031                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
49032                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
49033                                     ? "new "
49034                                     : "";
49035                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
49036                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
49037                                     ? ""
49038                                     : "...";
49039                                 path = "" + prefix + path + "(" + params + ")";
49040                             }
49041                             break;
49042                         }
49043                         default:
49044                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
49045                     }
49046                 }
49047                 if (path) {
49048                     reportError(path[path.length - 1] === ")"
49049                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
49050                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
49051                 }
49052                 else {
49053                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
49054                     secondaryRootErrors.shift();
49055                 }
49056                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
49057                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
49058                     var originalValue = msg.elidedInCompatabilityPyramid;
49059                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
49060                     reportError.apply(void 0, __spreadArrays([msg], args));
49061                     msg.elidedInCompatabilityPyramid = originalValue;
49062                 }
49063                 if (info) {
49064                     // Actually do the last relation error
49065                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
49066                 }
49067             }
49068             function reportError(message, arg0, arg1, arg2, arg3) {
49069                 ts.Debug.assert(!!errorNode);
49070                 if (incompatibleStack.length)
49071                     reportIncompatibleStack();
49072                 if (message.elidedInCompatabilityPyramid)
49073                     return;
49074                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
49075             }
49076             function associateRelatedInfo(info) {
49077                 ts.Debug.assert(!!errorInfo);
49078                 if (!relatedInfo) {
49079                     relatedInfo = [info];
49080                 }
49081                 else {
49082                     relatedInfo.push(info);
49083                 }
49084             }
49085             function reportRelationError(message, source, target) {
49086                 if (incompatibleStack.length)
49087                     reportIncompatibleStack();
49088                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
49089                 if (target.flags & 262144 /* TypeParameter */) {
49090                     var constraint = getBaseConstraintOfType(target);
49091                     var constraintElab = constraint && isTypeAssignableTo(source, constraint);
49092                     if (constraintElab) {
49093                         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));
49094                     }
49095                     else {
49096                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType);
49097                     }
49098                 }
49099                 if (!message) {
49100                     if (relation === comparableRelation) {
49101                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
49102                     }
49103                     else if (sourceType === targetType) {
49104                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
49105                     }
49106                     else {
49107                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
49108                     }
49109                 }
49110                 reportError(message, sourceType, targetType);
49111             }
49112             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
49113                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
49114                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
49115                 if ((globalStringType === source && stringType === target) ||
49116                     (globalNumberType === source && numberType === target) ||
49117                     (globalBooleanType === source && booleanType === target) ||
49118                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
49119                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
49120                 }
49121             }
49122             /**
49123              * Try and elaborate array and tuple errors. Returns false
49124              * if we have found an elaboration, or we should ignore
49125              * any other elaborations when relating the `source` and
49126              * `target` types.
49127              */
49128             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
49129                 /**
49130                  * The spec for elaboration is:
49131                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
49132                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
49133                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
49134                  * - If the source an array then skip property elaborations if the target is a tuple.
49135                  */
49136                 if (isTupleType(source)) {
49137                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
49138                         if (reportErrors) {
49139                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
49140                         }
49141                         return false;
49142                     }
49143                     return isTupleType(target) || isArrayType(target);
49144                 }
49145                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
49146                     if (reportErrors) {
49147                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
49148                     }
49149                     return false;
49150                 }
49151                 if (isTupleType(target)) {
49152                     return isArrayType(source);
49153                 }
49154                 return true;
49155             }
49156             /**
49157              * Compare two types and return
49158              * * Ternary.True if they are related with no assumptions,
49159              * * Ternary.Maybe if they are related with assumptions of other relationships, or
49160              * * Ternary.False if they are not related.
49161              */
49162             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
49163                 if (reportErrors === void 0) { reportErrors = false; }
49164                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
49165                 // Before normalization: if `source` is type an object type, and `target` is primitive,
49166                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
49167                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
49168                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
49169                         return -1 /* True */;
49170                     }
49171                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
49172                     return 0 /* False */;
49173                 }
49174                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
49175                 // turn deferred type references into regular type references, simplify indexed access and
49176                 // conditional types, and resolve substitution types to either the substitution (on the source
49177                 // side) or the type variable (on the target side).
49178                 var source = getNormalizedType(originalSource, /*writing*/ false);
49179                 var target = getNormalizedType(originalTarget, /*writing*/ true);
49180                 if (source === target)
49181                     return -1 /* True */;
49182                 if (relation === identityRelation) {
49183                     return isIdenticalTo(source, target);
49184                 }
49185                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
49186                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
49187                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
49188                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
49189                 // the target is exactly the constraint.
49190                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
49191                     return -1 /* True */;
49192                 }
49193                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
49194                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
49195                 // First, see if we're even relating an object type to a union.
49196                 // Then see if the target is stripped down to a single non-union type.
49197                 // Note
49198                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
49199                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
49200                 //    when dealing with generics.
49201                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
49202                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
49203                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
49204                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
49205                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
49206                         if (source === nullStrippedTarget)
49207                             return -1 /* True */;
49208                         target = nullStrippedTarget;
49209                     }
49210                 }
49211                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
49212                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
49213                     return -1 /* True */;
49214                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49215                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
49216                 if (isPerformingExcessPropertyChecks) {
49217                     if (hasExcessProperties(source, target, reportErrors)) {
49218                         if (reportErrors) {
49219                             reportRelationError(headMessage, source, target);
49220                         }
49221                         return 0 /* False */;
49222                     }
49223                 }
49224                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
49225                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
49226                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
49227                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
49228                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
49229                     if (reportErrors) {
49230                         var calls = getSignaturesOfType(source, 0 /* Call */);
49231                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
49232                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
49233                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
49234                             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));
49235                         }
49236                         else {
49237                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
49238                         }
49239                     }
49240                     return 0 /* False */;
49241                 }
49242                 var result = 0 /* False */;
49243                 var saveErrorInfo = captureErrorCalculationState();
49244                 // Note that these checks are specifically ordered to produce correct results. In particular,
49245                 // we need to deconstruct unions before intersections (because unions are always at the top),
49246                 // and we need to handle "each" relations before "some" relations for the same kind of type.
49247                 if (source.flags & 1048576 /* Union */) {
49248                     result = relation === comparableRelation ?
49249                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
49250                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
49251                 }
49252                 else {
49253                     if (target.flags & 1048576 /* Union */) {
49254                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
49255                     }
49256                     else if (target.flags & 2097152 /* Intersection */) {
49257                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
49258                     }
49259                     else if (source.flags & 2097152 /* Intersection */) {
49260                         // Check to see if any constituents of the intersection are immediately related to the target.
49261                         //
49262                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
49263                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
49264                         // take care of this, or to not elaborate at all. For instance,
49265                         //
49266                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
49267                         //
49268                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
49269                         //          than to report that 'D' is not assignable to 'A' or 'B'.
49270                         //
49271                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
49272                         //          breaking the intersection apart.
49273                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
49274                     }
49275                     if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
49276                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
49277                             resetErrorInfo(saveErrorInfo);
49278                         }
49279                     }
49280                 }
49281                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
49282                     // The combined constraint of an intersection type is the intersection of the constraints of
49283                     // the constituents. When an intersection type contains instantiable types with union type
49284                     // constraints, there are situations where we need to examine the combined constraint. One is
49285                     // when the target is a union type. Another is when the intersection contains types belonging
49286                     // to one of the disjoint domains. For example, given type variables T and U, each with the
49287                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
49288                     // we need to check this constraint against a union on the target side. Also, given a type
49289                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
49290                     // 'string & number | number & number' which reduces to just 'number'.
49291                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
49292                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
49293                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
49294                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
49295                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
49296                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
49297                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
49298                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
49299                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49300                                 resetErrorInfo(saveErrorInfo);
49301                             }
49302                         }
49303                     }
49304                 }
49305                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
49306                 // an extra property check where the intersection is viewed as a single object. The following are motivating
49307                 // examples that all should be errors, but aren't without this extra property check:
49308                 //
49309                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
49310                 //
49311                 //   declare let wrong: { a: { y: string } };
49312                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
49313                 //
49314                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
49315                 //     x = y;  // Mismatched property in source intersection
49316                 //   }
49317                 //
49318                 // We suppress recursive intersection property checks because they can generate lots of work when relating
49319                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
49320                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
49321                     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 */); }))) {
49322                     inPropertyCheck = true;
49323                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
49324                     inPropertyCheck = false;
49325                 }
49326                 reportErrorResults(source, target, result, isComparingJsxAttributes);
49327                 return result;
49328                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
49329                     if (!result && reportErrors) {
49330                         source = originalSource.aliasSymbol ? originalSource : source;
49331                         target = originalTarget.aliasSymbol ? originalTarget : target;
49332                         var maybeSuppress = overrideNextErrorInfo > 0;
49333                         if (maybeSuppress) {
49334                             overrideNextErrorInfo--;
49335                         }
49336                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
49337                             var currentError = errorInfo;
49338                             tryElaborateArrayLikeErrors(source, target, reportErrors);
49339                             if (errorInfo !== currentError) {
49340                                 maybeSuppress = !!errorInfo;
49341                             }
49342                         }
49343                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
49344                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
49345                         }
49346                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
49347                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
49348                         }
49349                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
49350                             var targetTypes = target.types;
49351                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
49352                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
49353                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
49354                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
49355                                 // do not report top error
49356                                 return result;
49357                             }
49358                         }
49359                         else {
49360                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
49361                         }
49362                         if (!headMessage && maybeSuppress) {
49363                             lastSkippedInfo = [source, target];
49364                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
49365                             return result;
49366                         }
49367                         reportRelationError(headMessage, source, target);
49368                     }
49369                 }
49370             }
49371             function isIdenticalTo(source, target) {
49372                 var flags = source.flags & target.flags;
49373                 if (!(flags & 66584576 /* Substructure */)) {
49374                     return 0 /* False */;
49375                 }
49376                 if (flags & 3145728 /* UnionOrIntersection */) {
49377                     var result_5 = eachTypeRelatedToSomeType(source, target);
49378                     if (result_5) {
49379                         result_5 &= eachTypeRelatedToSomeType(target, source);
49380                     }
49381                     return result_5;
49382                 }
49383                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
49384             }
49385             function getTypeOfPropertyInTypes(types, name) {
49386                 var appendPropType = function (propTypes, type) {
49387                     type = getApparentType(type);
49388                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
49389                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
49390                     return ts.append(propTypes, propType);
49391                 };
49392                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
49393             }
49394             function hasExcessProperties(source, target, reportErrors) {
49395                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
49396                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
49397                 }
49398                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49399                 if ((relation === assignableRelation || relation === comparableRelation) &&
49400                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
49401                     return false;
49402                 }
49403                 var reducedTarget = target;
49404                 var checkTypes;
49405                 if (target.flags & 1048576 /* Union */) {
49406                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
49407                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
49408                 }
49409                 var _loop_13 = function (prop) {
49410                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
49411                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
49412                             if (reportErrors) {
49413                                 // Report error in terms of object types in the target as those are the only ones
49414                                 // we check in isKnownProperty.
49415                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
49416                                 // We know *exactly* where things went wrong when comparing the types.
49417                                 // Use this property as the error node as this will be more helpful in
49418                                 // reasoning about what went wrong.
49419                                 if (!errorNode)
49420                                     return { value: ts.Debug.fail() };
49421                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
49422                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
49423                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
49424                                     // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
49425                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
49426                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
49427                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
49428                                         errorNode = prop.valueDeclaration.name;
49429                                     }
49430                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
49431                                 }
49432                                 else {
49433                                     // use the property's value declaration if the property is assigned inside the literal itself
49434                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
49435                                     var suggestion = void 0;
49436                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
49437                                         var propDeclaration = prop.valueDeclaration;
49438                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
49439                                         errorNode = propDeclaration;
49440                                         var name = propDeclaration.name;
49441                                         if (ts.isIdentifier(name)) {
49442                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
49443                                         }
49444                                     }
49445                                     if (suggestion !== undefined) {
49446                                         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);
49447                                     }
49448                                     else {
49449                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
49450                                     }
49451                                 }
49452                             }
49453                             return { value: true };
49454                         }
49455                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
49456                             if (reportErrors) {
49457                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
49458                             }
49459                             return { value: true };
49460                         }
49461                     }
49462                 };
49463                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
49464                     var prop = _a[_i];
49465                     var state_5 = _loop_13(prop);
49466                     if (typeof state_5 === "object")
49467                         return state_5.value;
49468                 }
49469                 return false;
49470             }
49471             function shouldCheckAsExcessProperty(prop, container) {
49472                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
49473             }
49474             function eachTypeRelatedToSomeType(source, target) {
49475                 var result = -1 /* True */;
49476                 var sourceTypes = source.types;
49477                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
49478                     var sourceType = sourceTypes_1[_i];
49479                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
49480                     if (!related) {
49481                         return 0 /* False */;
49482                     }
49483                     result &= related;
49484                 }
49485                 return result;
49486             }
49487             function typeRelatedToSomeType(source, target, reportErrors) {
49488                 var targetTypes = target.types;
49489                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
49490                     return -1 /* True */;
49491                 }
49492                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
49493                     var type = targetTypes_1[_i];
49494                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
49495                     if (related) {
49496                         return related;
49497                     }
49498                 }
49499                 if (reportErrors) {
49500                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
49501                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
49502                 }
49503                 return 0 /* False */;
49504             }
49505             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
49506                 var result = -1 /* True */;
49507                 var targetTypes = target.types;
49508                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
49509                     var targetType = targetTypes_2[_i];
49510                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
49511                     if (!related) {
49512                         return 0 /* False */;
49513                     }
49514                     result &= related;
49515                 }
49516                 return result;
49517             }
49518             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
49519                 var sourceTypes = source.types;
49520                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
49521                     return -1 /* True */;
49522                 }
49523                 var len = sourceTypes.length;
49524                 for (var i = 0; i < len; i++) {
49525                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
49526                     if (related) {
49527                         return related;
49528                     }
49529                 }
49530                 return 0 /* False */;
49531             }
49532             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
49533                 var result = -1 /* True */;
49534                 var sourceTypes = source.types;
49535                 for (var i = 0; i < sourceTypes.length; i++) {
49536                     var sourceType = sourceTypes[i];
49537                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
49538                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
49539                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
49540                         if (related_1) {
49541                             result &= related_1;
49542                             continue;
49543                         }
49544                     }
49545                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
49546                     if (!related) {
49547                         return 0 /* False */;
49548                     }
49549                     result &= related;
49550                 }
49551                 return result;
49552             }
49553             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
49554                 if (sources === void 0) { sources = ts.emptyArray; }
49555                 if (targets === void 0) { targets = ts.emptyArray; }
49556                 if (variances === void 0) { variances = ts.emptyArray; }
49557                 if (sources.length !== targets.length && relation === identityRelation) {
49558                     return 0 /* False */;
49559                 }
49560                 var length = sources.length <= targets.length ? sources.length : targets.length;
49561                 var result = -1 /* True */;
49562                 for (var i = 0; i < length; i++) {
49563                     // When variance information isn't available we default to covariance. This happens
49564                     // in the process of computing variance information for recursive types and when
49565                     // comparing 'this' type arguments.
49566                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
49567                     var variance = varianceFlags & 7 /* VarianceMask */;
49568                     // We ignore arguments for independent type parameters (because they're never witnessed).
49569                     if (variance !== 4 /* Independent */) {
49570                         var s = sources[i];
49571                         var t = targets[i];
49572                         var related = -1 /* True */;
49573                         if (varianceFlags & 8 /* Unmeasurable */) {
49574                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
49575                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
49576                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
49577                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
49578                         }
49579                         else if (variance === 1 /* Covariant */) {
49580                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49581                         }
49582                         else if (variance === 2 /* Contravariant */) {
49583                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49584                         }
49585                         else if (variance === 3 /* Bivariant */) {
49586                             // In the bivariant case we first compare contravariantly without reporting
49587                             // errors. Then, if that doesn't succeed, we compare covariantly with error
49588                             // reporting. Thus, error elaboration will be based on the the covariant check,
49589                             // which is generally easier to reason about.
49590                             related = isRelatedTo(t, s, /*reportErrors*/ false);
49591                             if (!related) {
49592                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49593                             }
49594                         }
49595                         else {
49596                             // In the invariant case we first compare covariantly, and only when that
49597                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
49598                             // will typically be based on the covariant check.
49599                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49600                             if (related) {
49601                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49602                             }
49603                         }
49604                         if (!related) {
49605                             return 0 /* False */;
49606                         }
49607                         result &= related;
49608                     }
49609                 }
49610                 return result;
49611             }
49612             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
49613             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
49614             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
49615             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
49616             // and issue an error. Otherwise, actually compare the structure of the two types.
49617             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
49618                 if (overflow) {
49619                     return 0 /* False */;
49620                 }
49621                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
49622                 var entry = relation.get(id);
49623                 if (entry !== undefined) {
49624                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
49625                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
49626                         // as a failure, and should be updated as a reported failure by the bottom of this function.
49627                     }
49628                     else {
49629                         if (outofbandVarianceMarkerHandler) {
49630                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
49631                             var saved = entry & 24 /* ReportsMask */;
49632                             if (saved & 8 /* ReportsUnmeasurable */) {
49633                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
49634                             }
49635                             if (saved & 16 /* ReportsUnreliable */) {
49636                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
49637                             }
49638                         }
49639                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
49640                     }
49641                 }
49642                 if (!maybeKeys) {
49643                     maybeKeys = [];
49644                     sourceStack = [];
49645                     targetStack = [];
49646                 }
49647                 else {
49648                     for (var i = 0; i < maybeCount; i++) {
49649                         // If source and target are already being compared, consider them related with assumptions
49650                         if (id === maybeKeys[i]) {
49651                             return 1 /* Maybe */;
49652                         }
49653                     }
49654                     if (depth === 100) {
49655                         overflow = true;
49656                         return 0 /* False */;
49657                     }
49658                 }
49659                 var maybeStart = maybeCount;
49660                 maybeKeys[maybeCount] = id;
49661                 maybeCount++;
49662                 sourceStack[depth] = source;
49663                 targetStack[depth] = target;
49664                 depth++;
49665                 var saveExpandingFlags = expandingFlags;
49666                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
49667                     expandingFlags |= 1 /* Source */;
49668                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
49669                     expandingFlags |= 2 /* Target */;
49670                 var originalHandler;
49671                 var propagatingVarianceFlags = 0;
49672                 if (outofbandVarianceMarkerHandler) {
49673                     originalHandler = outofbandVarianceMarkerHandler;
49674                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
49675                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
49676                         return originalHandler(onlyUnreliable);
49677                     };
49678                 }
49679                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
49680                 if (outofbandVarianceMarkerHandler) {
49681                     outofbandVarianceMarkerHandler = originalHandler;
49682                 }
49683                 expandingFlags = saveExpandingFlags;
49684                 depth--;
49685                 if (result) {
49686                     if (result === -1 /* True */ || depth === 0) {
49687                         // If result is definitely true, record all maybe keys as having succeeded
49688                         for (var i = maybeStart; i < maybeCount; i++) {
49689                             relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
49690                         }
49691                         maybeCount = maybeStart;
49692                     }
49693                 }
49694                 else {
49695                     // A false result goes straight into global cache (when something is false under
49696                     // assumptions it will also be false without assumptions)
49697                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
49698                     maybeCount = maybeStart;
49699                 }
49700                 return result;
49701             }
49702             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
49703                 if (intersectionState & 4 /* PropertyCheck */) {
49704                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
49705                 }
49706                 var flags = source.flags & target.flags;
49707                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
49708                     if (flags & 4194304 /* Index */) {
49709                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
49710                     }
49711                     var result_6 = 0 /* False */;
49712                     if (flags & 8388608 /* IndexedAccess */) {
49713                         if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
49714                             if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
49715                                 return result_6;
49716                             }
49717                         }
49718                     }
49719                     if (flags & 16777216 /* Conditional */) {
49720                         if (source.root.isDistributive === target.root.isDistributive) {
49721                             if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
49722                                 if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
49723                                     if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
49724                                         if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
49725                                             return result_6;
49726                                         }
49727                                     }
49728                                 }
49729                             }
49730                         }
49731                     }
49732                     if (flags & 33554432 /* Substitution */) {
49733                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
49734                     }
49735                     return 0 /* False */;
49736                 }
49737                 var result;
49738                 var originalErrorInfo;
49739                 var varianceCheckFailed = false;
49740                 var saveErrorInfo = captureErrorCalculationState();
49741                 // We limit alias variance probing to only object and conditional types since their alias behavior
49742                 // is more predictable than other, interned types, which may or may not have an alias depending on
49743                 // the order in which things were checked.
49744                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
49745                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
49746                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
49747                     var variances = getAliasVariances(source.aliasSymbol);
49748                     if (variances === ts.emptyArray) {
49749                         return 1 /* Maybe */;
49750                     }
49751                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
49752                     if (varianceResult !== undefined) {
49753                         return varianceResult;
49754                     }
49755                 }
49756                 if (target.flags & 262144 /* TypeParameter */) {
49757                     // 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].
49758                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
49759                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
49760                             var templateType = getTemplateTypeFromMappedType(source);
49761                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
49762                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
49763                                 return result;
49764                             }
49765                         }
49766                     }
49767                 }
49768                 else if (target.flags & 4194304 /* Index */) {
49769                     // A keyof S is related to a keyof T if T is related to S.
49770                     if (source.flags & 4194304 /* Index */) {
49771                         if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
49772                             return result;
49773                         }
49774                     }
49775                     // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
49776                     // simplified form of T or, if T doesn't simplify, the constraint of T.
49777                     var constraint = getSimplifiedTypeOrConstraint(target.type);
49778                     if (constraint) {
49779                         // We require Ternary.True here such that circular constraints don't cause
49780                         // false positives. For example, given 'T extends { [K in keyof T]: string }',
49781                         // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
49782                         // related to other types.
49783                         if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
49784                             return -1 /* True */;
49785                         }
49786                     }
49787                 }
49788                 else if (target.flags & 8388608 /* IndexedAccess */) {
49789                     // A type S is related to a type T[K] if S is related to C, where C is the base
49790                     // constraint of T[K] for writing.
49791                     if (relation !== identityRelation) {
49792                         var objectType = target.objectType;
49793                         var indexType = target.indexType;
49794                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
49795                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
49796                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
49797                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
49798                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
49799                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
49800                                 return result;
49801                             }
49802                         }
49803                     }
49804                 }
49805                 else if (isGenericMappedType(target)) {
49806                     // A source type T is related to a target type { [P in X]: T[P] }
49807                     var template = getTemplateTypeFromMappedType(target);
49808                     var modifiers = getMappedTypeModifiers(target);
49809                     if (!(modifiers & 8 /* ExcludeOptional */)) {
49810                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
49811                             template.indexType === getTypeParameterFromMappedType(target)) {
49812                             return -1 /* True */;
49813                         }
49814                         if (!isGenericMappedType(source)) {
49815                             var targetConstraint = getConstraintTypeFromMappedType(target);
49816                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
49817                             var includeOptional = modifiers & 4 /* IncludeOptional */;
49818                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
49819                             // 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.
49820                             // 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.
49821                             if (includeOptional
49822                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
49823                                 : isRelatedTo(targetConstraint, sourceKeys)) {
49824                                 var typeParameter = getTypeParameterFromMappedType(target);
49825                                 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
49826                                 var indexedAccessType = getIndexedAccessType(source, indexingType);
49827                                 var templateType = getTemplateTypeFromMappedType(target);
49828                                 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
49829                                     return result;
49830                                 }
49831                             }
49832                             originalErrorInfo = errorInfo;
49833                             resetErrorInfo(saveErrorInfo);
49834                         }
49835                     }
49836                 }
49837                 if (source.flags & 8650752 /* TypeVariable */) {
49838                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
49839                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
49840                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
49841                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
49842                         }
49843                         if (result) {
49844                             resetErrorInfo(saveErrorInfo);
49845                             return result;
49846                         }
49847                     }
49848                     else {
49849                         var constraint = getConstraintOfType(source);
49850                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
49851                             // A type variable with no constraint is not related to the non-primitive object type.
49852                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
49853                                 resetErrorInfo(saveErrorInfo);
49854                                 return result;
49855                             }
49856                         }
49857                         // 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
49858                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49859                             resetErrorInfo(saveErrorInfo);
49860                             return result;
49861                         }
49862                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
49863                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
49864                             resetErrorInfo(saveErrorInfo);
49865                             return result;
49866                         }
49867                     }
49868                 }
49869                 else if (source.flags & 4194304 /* Index */) {
49870                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
49871                         resetErrorInfo(saveErrorInfo);
49872                         return result;
49873                     }
49874                 }
49875                 else if (source.flags & 16777216 /* Conditional */) {
49876                     if (target.flags & 16777216 /* Conditional */) {
49877                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
49878                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
49879                         // and Y1 is related to Y2.
49880                         var sourceParams = source.root.inferTypeParameters;
49881                         var sourceExtends = source.extendsType;
49882                         var mapper = void 0;
49883                         if (sourceParams) {
49884                             // If the source has infer type parameters, we instantiate them in the context of the target
49885                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
49886                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
49887                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
49888                             mapper = ctx.mapper;
49889                         }
49890                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
49891                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
49892                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
49893                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
49894                             }
49895                             if (result) {
49896                                 resetErrorInfo(saveErrorInfo);
49897                                 return result;
49898                             }
49899                         }
49900                     }
49901                     else {
49902                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
49903                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
49904                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
49905                         if (distributiveConstraint) {
49906                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
49907                                 resetErrorInfo(saveErrorInfo);
49908                                 return result;
49909                             }
49910                         }
49911                     }
49912                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
49913                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
49914                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
49915                     if (defaultConstraint) {
49916                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
49917                             resetErrorInfo(saveErrorInfo);
49918                             return result;
49919                         }
49920                     }
49921                 }
49922                 else {
49923                     // An empty object type is related to any mapped type that includes a '?' modifier.
49924                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
49925                         return -1 /* True */;
49926                     }
49927                     if (isGenericMappedType(target)) {
49928                         if (isGenericMappedType(source)) {
49929                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
49930                                 resetErrorInfo(saveErrorInfo);
49931                                 return result;
49932                             }
49933                         }
49934                         return 0 /* False */;
49935                     }
49936                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
49937                     if (relation !== identityRelation) {
49938                         source = getApparentType(source);
49939                     }
49940                     else if (isGenericMappedType(source)) {
49941                         return 0 /* False */;
49942                     }
49943                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
49944                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
49945                         // We have type references to the same generic type, and the type references are not marker
49946                         // type references (which are intended by be compared structurally). Obtain the variance
49947                         // information for the type parameters and relate the type arguments accordingly.
49948                         var variances = getVariances(source.target);
49949                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
49950                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
49951                         // recursive instantiations of the generic type.
49952                         if (variances === ts.emptyArray) {
49953                             return 1 /* Maybe */;
49954                         }
49955                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
49956                         if (varianceResult !== undefined) {
49957                             return varianceResult;
49958                         }
49959                     }
49960                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
49961                         if (relation !== identityRelation) {
49962                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
49963                         }
49964                         else {
49965                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
49966                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
49967                             return 0 /* False */;
49968                         }
49969                     }
49970                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
49971                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
49972                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
49973                         return 0 /* False */;
49974                     }
49975                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
49976                     // it may hold in a structural comparison.
49977                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
49978                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
49979                     // relates to X. Thus, we include intersection types on the source side here.
49980                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
49981                         // Report structural errors only if we haven't reported any errors yet
49982                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
49983                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
49984                         if (result) {
49985                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
49986                             if (result) {
49987                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
49988                                 if (result) {
49989                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49990                                     if (result) {
49991                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49992                                     }
49993                                 }
49994                             }
49995                         }
49996                         if (varianceCheckFailed && result) {
49997                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
49998                         }
49999                         else if (result) {
50000                             return result;
50001                         }
50002                     }
50003                     // If S is an object type and T is a discriminated union, S may be related to T if
50004                     // there exists a constituent of T for every combination of the discriminants of S
50005                     // with respect to T. We do not report errors here, as we will use the existing
50006                     // error result from checking each constituent of the union.
50007                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
50008                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
50009                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
50010                             var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
50011                             if (result_7) {
50012                                 return result_7;
50013                             }
50014                         }
50015                     }
50016                 }
50017                 return 0 /* False */;
50018                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
50019                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
50020                         return result;
50021                     }
50022                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
50023                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
50024                         // have to allow a structural fallback check
50025                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
50026                         // be assuming identity of the type parameter.
50027                         originalErrorInfo = undefined;
50028                         resetErrorInfo(saveErrorInfo);
50029                         return undefined;
50030                     }
50031                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
50032                     varianceCheckFailed = !allowStructuralFallback;
50033                     // The type arguments did not relate appropriately, but it may be because we have no variance
50034                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
50035                     // arguments). It might also be the case that the target type has a 'void' type argument for
50036                     // a covariant type parameter that is only used in return positions within the generic type
50037                     // (in which case any type argument is permitted on the source side). In those cases we proceed
50038                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
50039                     // related and we can return here.
50040                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
50041                         // In some cases generic types that are covariant in regular type checking mode become
50042                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
50043                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
50044                         // types are invariant, if any of the type parameters are invariant we reset the reported
50045                         // errors and instead force a structural comparison (which will include elaborations that
50046                         // reveal the reason).
50047                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
50048                         // we can return `False` early here to skip calculating the structural error message we don't need.
50049                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
50050                             return 0 /* False */;
50051                         }
50052                         // We remember the original error information so we can restore it in case the structural
50053                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
50054                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
50055                         originalErrorInfo = errorInfo;
50056                         resetErrorInfo(saveErrorInfo);
50057                     }
50058                 }
50059             }
50060             function reportUnmeasurableMarkers(p) {
50061                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
50062                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
50063                 }
50064                 return p;
50065             }
50066             function reportUnreliableMarkers(p) {
50067                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
50068                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
50069                 }
50070                 return p;
50071             }
50072             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
50073             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
50074             // that S and T are contra-variant whereas X and Y are co-variant.
50075             function mappedTypeRelatedTo(source, target, reportErrors) {
50076                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
50077                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
50078                 if (modifiersRelated) {
50079                     var result_8;
50080                     var targetConstraint = getConstraintTypeFromMappedType(target);
50081                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
50082                     if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
50083                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
50084                         return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
50085                     }
50086                 }
50087                 return 0 /* False */;
50088             }
50089             function typeRelatedToDiscriminatedType(source, target) {
50090                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
50091                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
50092                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
50093                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
50094                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
50095                 //    'target' are related to a property in 'source'.
50096                 //
50097                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
50098                 //       for examples.
50099                 var sourceProperties = getPropertiesOfType(source);
50100                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
50101                 if (!sourcePropertiesFiltered)
50102                     return 0 /* False */;
50103                 // Though we could compute the number of combinations as we generate
50104                 // the matrix, this would incur additional memory overhead due to
50105                 // array allocations. To reduce this overhead, we first compute
50106                 // the number of combinations to ensure we will not surpass our
50107                 // fixed limit before incurring the cost of any allocations:
50108                 var numCombinations = 1;
50109                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
50110                     var sourceProperty = sourcePropertiesFiltered_1[_i];
50111                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
50112                     if (numCombinations > 25) {
50113                         // We've reached the complexity limit.
50114                         return 0 /* False */;
50115                     }
50116                 }
50117                 // Compute the set of types for each discriminant property.
50118                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
50119                 var excludedProperties = ts.createUnderscoreEscapedMap();
50120                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
50121                     var sourceProperty = sourcePropertiesFiltered[i];
50122                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
50123                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
50124                         ? sourcePropertyType.types
50125                         : [sourcePropertyType];
50126                     excludedProperties.set(sourceProperty.escapedName, true);
50127                 }
50128                 // Match each combination of the cartesian product of discriminant properties to one or more
50129                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
50130                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
50131                 var matchingTypes = [];
50132                 var _loop_14 = function (combination) {
50133                     var hasMatch = false;
50134                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
50135                         var type = _a[_i];
50136                         var _loop_15 = function (i) {
50137                             var sourceProperty = sourcePropertiesFiltered[i];
50138                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
50139                             if (!targetProperty)
50140                                 return "continue-outer";
50141                             if (sourceProperty === targetProperty)
50142                                 return "continue";
50143                             // We compare the source property to the target in the context of a single discriminant type.
50144                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
50145                             // If the target property could not be found, or if the properties were not related,
50146                             // then this constituent is not a match.
50147                             if (!related) {
50148                                 return "continue-outer";
50149                             }
50150                         };
50151                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
50152                             var state_7 = _loop_15(i);
50153                             switch (state_7) {
50154                                 case "continue-outer": continue outer;
50155                             }
50156                         }
50157                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
50158                         hasMatch = true;
50159                     }
50160                     if (!hasMatch) {
50161                         return { value: 0 /* False */ };
50162                     }
50163                 };
50164                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
50165                     var combination = discriminantCombinations_1[_a];
50166                     var state_6 = _loop_14(combination);
50167                     if (typeof state_6 === "object")
50168                         return state_6.value;
50169                 }
50170                 // Compare the remaining non-discriminant properties of each match.
50171                 var result = -1 /* True */;
50172                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
50173                     var type = matchingTypes_1[_b];
50174                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
50175                     if (result) {
50176                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
50177                         if (result) {
50178                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
50179                             if (result) {
50180                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50181                                 if (result) {
50182                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50183                                 }
50184                             }
50185                         }
50186                     }
50187                     if (!result) {
50188                         return result;
50189                     }
50190                 }
50191                 return result;
50192             }
50193             function excludeProperties(properties, excludedProperties) {
50194                 if (!excludedProperties || properties.length === 0)
50195                     return properties;
50196                 var result;
50197                 for (var i = 0; i < properties.length; i++) {
50198                     if (!excludedProperties.has(properties[i].escapedName)) {
50199                         if (result) {
50200                             result.push(properties[i]);
50201                         }
50202                     }
50203                     else if (!result) {
50204                         result = properties.slice(0, i);
50205                     }
50206                 }
50207                 return result || properties;
50208             }
50209             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
50210                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
50211                 var source = getTypeOfSourceProperty(sourceProp);
50212                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
50213                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
50214                     var links = getSymbolLinks(targetProp);
50215                     ts.Debug.assertIsDefined(links.deferralParent);
50216                     ts.Debug.assertIsDefined(links.deferralConstituents);
50217                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
50218                     var result_9 = unionParent ? 0 /* False */ : -1 /* True */;
50219                     var targetTypes = links.deferralConstituents;
50220                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
50221                         var targetType = targetTypes_3[_i];
50222                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
50223                         if (!unionParent) {
50224                             if (!related) {
50225                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
50226                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50227                             }
50228                             result_9 &= related;
50229                         }
50230                         else {
50231                             if (related) {
50232                                 return related;
50233                             }
50234                         }
50235                     }
50236                     if (unionParent && !result_9 && targetIsOptional) {
50237                         result_9 = isRelatedTo(source, undefinedType);
50238                     }
50239                     if (unionParent && !result_9 && reportErrors) {
50240                         // The easiest way to get the right errors here is to un-defer (which may be costly)
50241                         // If it turns out this is too costly too often, we can replicate the error handling logic within
50242                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
50243                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
50244                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50245                     }
50246                     return result_9;
50247                 }
50248                 else {
50249                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
50250                 }
50251             }
50252             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
50253                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
50254                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
50255                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
50256                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
50257                         if (reportErrors) {
50258                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
50259                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
50260                             }
50261                             else {
50262                                 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));
50263                             }
50264                         }
50265                         return 0 /* False */;
50266                     }
50267                 }
50268                 else if (targetPropFlags & 16 /* Protected */) {
50269                     if (!isValidOverrideOf(sourceProp, targetProp)) {
50270                         if (reportErrors) {
50271                             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));
50272                         }
50273                         return 0 /* False */;
50274                     }
50275                 }
50276                 else if (sourcePropFlags & 16 /* Protected */) {
50277                     if (reportErrors) {
50278                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50279                     }
50280                     return 0 /* False */;
50281                 }
50282                 // If the target comes from a partial union prop, allow `undefined` in the target type
50283                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
50284                 if (!related) {
50285                     if (reportErrors) {
50286                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
50287                     }
50288                     return 0 /* False */;
50289                 }
50290                 // When checking for comparability, be more lenient with optional properties.
50291                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
50292                     // TypeScript 1.0 spec (April 2014): 3.8.3
50293                     // S is a subtype of a type T, and T is a supertype of S if ...
50294                     // S' and T are object types and, for each member M in T..
50295                     // M is a property and S' contains a property N where
50296                     // if M is a required property, N is also a required property
50297                     // (M - property in T)
50298                     // (N - property in S)
50299                     if (reportErrors) {
50300                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50301                     }
50302                     return 0 /* False */;
50303                 }
50304                 return related;
50305             }
50306             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
50307                 var shouldSkipElaboration = false;
50308                 // give specific error in case where private names have the same description
50309                 if (unmatchedProperty.valueDeclaration
50310                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
50311                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
50312                     && source.symbol
50313                     && source.symbol.flags & 32 /* Class */) {
50314                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
50315                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
50316                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
50317                         var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
50318                         var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
50319                         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));
50320                         return;
50321                     }
50322                 }
50323                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
50324                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
50325                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
50326                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
50327                 }
50328                 if (props.length === 1) {
50329                     var propName = symbolToString(unmatchedProperty);
50330                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
50331                     if (ts.length(unmatchedProperty.declarations)) {
50332                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
50333                     }
50334                     if (shouldSkipElaboration && errorInfo) {
50335                         overrideNextErrorInfo++;
50336                     }
50337                 }
50338                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
50339                     if (props.length > 5) { // arbitrary cutoff for too-long list form
50340                         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);
50341                     }
50342                     else {
50343                         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(", "));
50344                     }
50345                     if (shouldSkipElaboration && errorInfo) {
50346                         overrideNextErrorInfo++;
50347                     }
50348                 }
50349                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
50350             }
50351             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
50352                 if (relation === identityRelation) {
50353                     return propertiesIdenticalTo(source, target, excludedProperties);
50354                 }
50355                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
50356                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
50357                 if (unmatchedProperty) {
50358                     if (reportErrors) {
50359                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
50360                     }
50361                     return 0 /* False */;
50362                 }
50363                 if (isObjectLiteralType(target)) {
50364                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
50365                         var sourceProp = _a[_i];
50366                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
50367                             var sourceType = getTypeOfSymbol(sourceProp);
50368                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
50369                                 if (reportErrors) {
50370                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
50371                                 }
50372                                 return 0 /* False */;
50373                             }
50374                         }
50375                     }
50376                 }
50377                 var result = -1 /* True */;
50378                 if (isTupleType(target)) {
50379                     var targetRestType = getRestTypeOfTupleType(target);
50380                     if (targetRestType) {
50381                         if (!isTupleType(source)) {
50382                             return 0 /* False */;
50383                         }
50384                         var sourceRestType = getRestTypeOfTupleType(source);
50385                         if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
50386                             if (reportErrors) {
50387                                 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
50388                             }
50389                             return 0 /* False */;
50390                         }
50391                         var targetCount = getTypeReferenceArity(target) - 1;
50392                         var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
50393                         var sourceTypeArguments = getTypeArguments(source);
50394                         for (var i = targetCount; i < sourceCount; i++) {
50395                             var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
50396                             if (!related) {
50397                                 if (reportErrors) {
50398                                     reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
50399                                 }
50400                                 return 0 /* False */;
50401                             }
50402                             result &= related;
50403                         }
50404                     }
50405                 }
50406                 // 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_
50407                 // from the target union, across all members
50408                 var properties = getPropertiesOfType(target);
50409                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
50410                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
50411                     var targetProp = _c[_b];
50412                     var name = targetProp.escapedName;
50413                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
50414                         var sourceProp = getPropertyOfType(source, name);
50415                         if (sourceProp && sourceProp !== targetProp) {
50416                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
50417                             if (!related) {
50418                                 return 0 /* False */;
50419                             }
50420                             result &= related;
50421                         }
50422                     }
50423                 }
50424                 return result;
50425             }
50426             function propertiesIdenticalTo(source, target, excludedProperties) {
50427                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
50428                     return 0 /* False */;
50429                 }
50430                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
50431                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
50432                 if (sourceProperties.length !== targetProperties.length) {
50433                     return 0 /* False */;
50434                 }
50435                 var result = -1 /* True */;
50436                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
50437                     var sourceProp = sourceProperties_1[_i];
50438                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
50439                     if (!targetProp) {
50440                         return 0 /* False */;
50441                     }
50442                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
50443                     if (!related) {
50444                         return 0 /* False */;
50445                     }
50446                     result &= related;
50447                 }
50448                 return result;
50449             }
50450             function signaturesRelatedTo(source, target, kind, reportErrors) {
50451                 if (relation === identityRelation) {
50452                     return signaturesIdenticalTo(source, target, kind);
50453                 }
50454                 if (target === anyFunctionType || source === anyFunctionType) {
50455                     return -1 /* True */;
50456                 }
50457                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
50458                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
50459                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
50460                     0 /* Call */ : kind);
50461                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
50462                     0 /* Call */ : kind);
50463                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
50464                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
50465                         // An abstract constructor type is not assignable to a non-abstract constructor type
50466                         // as it would otherwise be possible to new an abstract class. Note that the assignability
50467                         // check we perform for an extends clause excludes construct signatures from the target,
50468                         // so this check never proceeds.
50469                         if (reportErrors) {
50470                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
50471                         }
50472                         return 0 /* False */;
50473                     }
50474                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
50475                         return 0 /* False */;
50476                     }
50477                 }
50478                 var result = -1 /* True */;
50479                 var saveErrorInfo = captureErrorCalculationState();
50480                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
50481                 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
50482                     // We have instantiations of the same anonymous type (which typically will be the type of a
50483                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
50484                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
50485                     // as they are known to always be the same.
50486                     for (var i = 0; i < targetSignatures.length; i++) {
50487                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
50488                         if (!related) {
50489                             return 0 /* False */;
50490                         }
50491                         result &= related;
50492                     }
50493                 }
50494                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
50495                     // For simple functions (functions with a single signature) we only erase type parameters for
50496                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
50497                     // in the context of the target signature before checking the relationship. Ideally we'd do
50498                     // this regardless of the number of signatures, but the potential costs are prohibitive due
50499                     // to the quadratic nature of the logic below.
50500                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
50501                     result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
50502                 }
50503                 else {
50504                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
50505                         var t = targetSignatures_1[_i];
50506                         // Only elaborate errors from the first failure
50507                         var shouldElaborateErrors = reportErrors;
50508                         for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
50509                             var s = sourceSignatures_1[_a];
50510                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
50511                             if (related) {
50512                                 result &= related;
50513                                 resetErrorInfo(saveErrorInfo);
50514                                 continue outer;
50515                             }
50516                             shouldElaborateErrors = false;
50517                         }
50518                         if (shouldElaborateErrors) {
50519                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
50520                         }
50521                         return 0 /* False */;
50522                     }
50523                 }
50524                 return result;
50525             }
50526             function reportIncompatibleCallSignatureReturn(siga, sigb) {
50527                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50528                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50529                 }
50530                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50531             }
50532             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
50533                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50534                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50535                 }
50536                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50537             }
50538             /**
50539              * See signatureAssignableTo, compareSignaturesIdentical
50540              */
50541             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
50542                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
50543             }
50544             function signaturesIdenticalTo(source, target, kind) {
50545                 var sourceSignatures = getSignaturesOfType(source, kind);
50546                 var targetSignatures = getSignaturesOfType(target, kind);
50547                 if (sourceSignatures.length !== targetSignatures.length) {
50548                     return 0 /* False */;
50549                 }
50550                 var result = -1 /* True */;
50551                 for (var i = 0; i < sourceSignatures.length; i++) {
50552                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
50553                     if (!related) {
50554                         return 0 /* False */;
50555                     }
50556                     result &= related;
50557                 }
50558                 return result;
50559             }
50560             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
50561                 var result = -1 /* True */;
50562                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
50563                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
50564                     var prop = props_2[_i];
50565                     // Skip over ignored JSX and symbol-named members
50566                     if (isIgnoredJsxProperty(source, prop)) {
50567                         continue;
50568                     }
50569                     var nameType = getSymbolLinks(prop).nameType;
50570                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
50571                         continue;
50572                     }
50573                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
50574                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
50575                         if (!related) {
50576                             if (reportErrors) {
50577                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
50578                             }
50579                             return 0 /* False */;
50580                         }
50581                         result &= related;
50582                     }
50583                 }
50584                 return result;
50585             }
50586             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
50587                 var related = isRelatedTo(sourceType, targetType, reportErrors);
50588                 if (!related && reportErrors) {
50589                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
50590                 }
50591                 return related;
50592             }
50593             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
50594                 if (relation === identityRelation) {
50595                     return indexTypesIdenticalTo(source, target, kind);
50596                 }
50597                 var targetType = getIndexTypeOfType(target, kind);
50598                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
50599                     // Index signature of type any permits assignment from everything but primitives
50600                     return -1 /* True */;
50601                 }
50602                 if (isGenericMappedType(source)) {
50603                     // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
50604                     // if T is related to U.
50605                     return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
50606                 }
50607                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
50608                 if (indexType) {
50609                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
50610                 }
50611                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
50612                     // Intersection constituents are never considered to have an inferred index signature
50613                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
50614                     if (related && kind === 0 /* String */) {
50615                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
50616                         if (numberIndexType) {
50617                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
50618                         }
50619                     }
50620                     return related;
50621                 }
50622                 if (reportErrors) {
50623                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
50624                 }
50625                 return 0 /* False */;
50626             }
50627             function indexTypesIdenticalTo(source, target, indexKind) {
50628                 var targetInfo = getIndexInfoOfType(target, indexKind);
50629                 var sourceInfo = getIndexInfoOfType(source, indexKind);
50630                 if (!sourceInfo && !targetInfo) {
50631                     return -1 /* True */;
50632                 }
50633                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
50634                     return isRelatedTo(sourceInfo.type, targetInfo.type);
50635                 }
50636                 return 0 /* False */;
50637             }
50638             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
50639                 if (!sourceSignature.declaration || !targetSignature.declaration) {
50640                     return true;
50641                 }
50642                 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50643                 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50644                 // A public, protected and private signature is assignable to a private signature.
50645                 if (targetAccessibility === 8 /* Private */) {
50646                     return true;
50647                 }
50648                 // A public and protected signature is assignable to a protected signature.
50649                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
50650                     return true;
50651                 }
50652                 // Only a public signature is assignable to public signature.
50653                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
50654                     return true;
50655                 }
50656                 if (reportErrors) {
50657                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
50658                 }
50659                 return false;
50660             }
50661         }
50662         function getBestMatchingType(source, target, isRelatedTo) {
50663             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
50664             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
50665                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
50666                 findBestTypeForObjectLiteral(source, target) ||
50667                 findBestTypeForInvokable(source, target) ||
50668                 findMostOverlappyType(source, target);
50669         }
50670         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
50671             // undefined=unknown, true=discriminated, false=not discriminated
50672             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
50673             var discriminable = target.types.map(function (_) { return undefined; });
50674             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
50675                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
50676                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
50677                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
50678                     continue;
50679                 }
50680                 var i = 0;
50681                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
50682                     var type = _c[_b];
50683                     var targetType = getTypeOfPropertyOfType(type, propertyName);
50684                     if (targetType && related(getDiscriminatingType(), targetType)) {
50685                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
50686                     }
50687                     else {
50688                         discriminable[i] = false;
50689                     }
50690                     i++;
50691                 }
50692             }
50693             var match = discriminable.indexOf(/*searchElement*/ true);
50694             // make sure exactly 1 matches before returning it
50695             return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
50696         }
50697         /**
50698          * A type is 'weak' if it is an object type with at least one optional property
50699          * and no required properties, call/construct signatures or index signatures
50700          */
50701         function isWeakType(type) {
50702             if (type.flags & 524288 /* Object */) {
50703                 var resolved = resolveStructuredTypeMembers(type);
50704                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
50705                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
50706                     resolved.properties.length > 0 &&
50707                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
50708             }
50709             if (type.flags & 2097152 /* Intersection */) {
50710                 return ts.every(type.types, isWeakType);
50711             }
50712             return false;
50713         }
50714         function hasCommonProperties(source, target, isComparingJsxAttributes) {
50715             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50716                 var prop = _a[_i];
50717                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
50718                     return true;
50719                 }
50720             }
50721             return false;
50722         }
50723         // Return a type reference where the source type parameter is replaced with the target marker
50724         // type, and flag the result as a marker type reference.
50725         function getMarkerTypeReference(type, source, target) {
50726             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
50727             result.objectFlags |= 8192 /* MarkerType */;
50728             return result;
50729         }
50730         function getAliasVariances(symbol) {
50731             var links = getSymbolLinks(symbol);
50732             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
50733                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
50734                 type.aliasTypeArgumentsContainsMarker = true;
50735                 return type;
50736             });
50737         }
50738         // Return an array containing the variance of each type parameter. The variance is effectively
50739         // a digest of the type comparisons that occur for each type argument when instantiations of the
50740         // generic type are structurally compared. We infer the variance information by comparing
50741         // instantiations of the generic type for type arguments with known relations. The function
50742         // returns the emptyArray singleton when invoked recursively for the given generic type.
50743         function getVariancesWorker(typeParameters, cache, createMarkerType) {
50744             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
50745             var variances = cache.variances;
50746             if (!variances) {
50747                 // The emptyArray singleton is used to signal a recursive invocation.
50748                 cache.variances = ts.emptyArray;
50749                 variances = [];
50750                 var _loop_16 = function (tp) {
50751                     var unmeasurable = false;
50752                     var unreliable = false;
50753                     var oldHandler = outofbandVarianceMarkerHandler;
50754                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
50755                     // We first compare instantiations where the type parameter is replaced with
50756                     // marker types that have a known subtype relationship. From this we can infer
50757                     // invariance, covariance, contravariance or bivariance.
50758                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
50759                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
50760                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
50761                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
50762                     // If the instantiations appear to be related bivariantly it may be because the
50763                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
50764                     // type). To determine this we compare instantiations where the type parameter is
50765                     // replaced with marker types that are known to be unrelated.
50766                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
50767                         variance = 4 /* Independent */;
50768                     }
50769                     outofbandVarianceMarkerHandler = oldHandler;
50770                     if (unmeasurable || unreliable) {
50771                         if (unmeasurable) {
50772                             variance |= 8 /* Unmeasurable */;
50773                         }
50774                         if (unreliable) {
50775                             variance |= 16 /* Unreliable */;
50776                         }
50777                     }
50778                     variances.push(variance);
50779                 };
50780                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
50781                     var tp = typeParameters_1[_i];
50782                     _loop_16(tp);
50783                 }
50784                 cache.variances = variances;
50785             }
50786             return variances;
50787         }
50788         function getVariances(type) {
50789             // Arrays and tuples are known to be covariant, no need to spend time computing this.
50790             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
50791                 return arrayVariances;
50792             }
50793             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
50794         }
50795         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
50796         // See comment at call in recursiveTypeRelatedTo for when this case matters.
50797         function hasCovariantVoidArgument(typeArguments, variances) {
50798             for (var i = 0; i < variances.length; i++) {
50799                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
50800                     return true;
50801                 }
50802             }
50803             return false;
50804         }
50805         function isUnconstrainedTypeParameter(type) {
50806             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
50807         }
50808         function isNonDeferredTypeReference(type) {
50809             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
50810         }
50811         function isTypeReferenceWithGenericArguments(type) {
50812             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
50813         }
50814         /**
50815          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
50816          *   where A.id=111 and number.id=12
50817          */
50818         function getTypeReferenceId(type, typeParameters, depth) {
50819             if (depth === void 0) { depth = 0; }
50820             var result = "" + type.target.id;
50821             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
50822                 var t = _a[_i];
50823                 if (isUnconstrainedTypeParameter(t)) {
50824                     var index = typeParameters.indexOf(t);
50825                     if (index < 0) {
50826                         index = typeParameters.length;
50827                         typeParameters.push(t);
50828                     }
50829                     result += "=" + index;
50830                 }
50831                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
50832                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
50833                 }
50834                 else {
50835                     result += "-" + t.id;
50836                 }
50837             }
50838             return result;
50839         }
50840         /**
50841          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
50842          * For other cases, the types ids are used.
50843          */
50844         function getRelationKey(source, target, intersectionState, relation) {
50845             if (relation === identityRelation && source.id > target.id) {
50846                 var temp = source;
50847                 source = target;
50848                 target = temp;
50849             }
50850             var postFix = intersectionState ? ":" + intersectionState : "";
50851             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
50852                 var typeParameters = [];
50853                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
50854             }
50855             return source.id + "," + target.id + postFix;
50856         }
50857         // Invoke the callback for each underlying property symbol of the given symbol and return the first
50858         // value that isn't undefined.
50859         function forEachProperty(prop, callback) {
50860             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
50861                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
50862                     var t = _a[_i];
50863                     var p = getPropertyOfType(t, prop.escapedName);
50864                     var result = p && forEachProperty(p, callback);
50865                     if (result) {
50866                         return result;
50867                     }
50868                 }
50869                 return undefined;
50870             }
50871             return callback(prop);
50872         }
50873         // Return the declaring class type of a property or undefined if property not declared in class
50874         function getDeclaringClass(prop) {
50875             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
50876         }
50877         // Return true if some underlying source property is declared in a class that derives
50878         // from the given base class.
50879         function isPropertyInClassDerivedFrom(prop, baseClass) {
50880             return forEachProperty(prop, function (sp) {
50881                 var sourceClass = getDeclaringClass(sp);
50882                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
50883             });
50884         }
50885         // Return true if source property is a valid override of protected parts of target property.
50886         function isValidOverrideOf(sourceProp, targetProp) {
50887             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
50888                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
50889         }
50890         // Return true if the given class derives from each of the declaring classes of the protected
50891         // constituents of the given property.
50892         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
50893             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
50894                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
50895         }
50896         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
50897         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
50898         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
50899         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
50900         // levels, but unequal at some level beyond that.
50901         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
50902         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
50903         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
50904         function isDeeplyNestedType(type, stack, depth) {
50905             // We track all object types that have an associated symbol (representing the origin of the type)
50906             if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
50907                 var symbol = type.symbol;
50908                 if (symbol) {
50909                     var count = 0;
50910                     for (var i = 0; i < depth; i++) {
50911                         var t = stack[i];
50912                         if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
50913                             count++;
50914                             if (count >= 5)
50915                                 return true;
50916                         }
50917                     }
50918                 }
50919             }
50920             if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
50921                 var root = getRootObjectTypeFromIndexedAccessChain(type);
50922                 var count = 0;
50923                 for (var i = 0; i < depth; i++) {
50924                     var t = stack[i];
50925                     if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
50926                         count++;
50927                         if (count >= 5)
50928                             return true;
50929                     }
50930                 }
50931             }
50932             return false;
50933         }
50934         /**
50935          * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
50936          */
50937         function getRootObjectTypeFromIndexedAccessChain(type) {
50938             var t = type;
50939             while (t.flags & 8388608 /* IndexedAccess */) {
50940                 t = t.objectType;
50941             }
50942             return t;
50943         }
50944         function isPropertyIdenticalTo(sourceProp, targetProp) {
50945             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
50946         }
50947         function compareProperties(sourceProp, targetProp, compareTypes) {
50948             // Two members are considered identical when
50949             // - they are public properties with identical names, optionality, and types,
50950             // - they are private or protected properties originating in the same declaration and having identical types
50951             if (sourceProp === targetProp) {
50952                 return -1 /* True */;
50953             }
50954             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
50955             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
50956             if (sourcePropAccessibility !== targetPropAccessibility) {
50957                 return 0 /* False */;
50958             }
50959             if (sourcePropAccessibility) {
50960                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
50961                     return 0 /* False */;
50962                 }
50963             }
50964             else {
50965                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
50966                     return 0 /* False */;
50967                 }
50968             }
50969             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
50970                 return 0 /* False */;
50971             }
50972             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
50973         }
50974         function isMatchingSignature(source, target, partialMatch) {
50975             var sourceParameterCount = getParameterCount(source);
50976             var targetParameterCount = getParameterCount(target);
50977             var sourceMinArgumentCount = getMinArgumentCount(source);
50978             var targetMinArgumentCount = getMinArgumentCount(target);
50979             var sourceHasRestParameter = hasEffectiveRestParameter(source);
50980             var targetHasRestParameter = hasEffectiveRestParameter(target);
50981             // A source signature matches a target signature if the two signatures have the same number of required,
50982             // optional, and rest parameters.
50983             if (sourceParameterCount === targetParameterCount &&
50984                 sourceMinArgumentCount === targetMinArgumentCount &&
50985                 sourceHasRestParameter === targetHasRestParameter) {
50986                 return true;
50987             }
50988             // A source signature partially matches a target signature if the target signature has no fewer required
50989             // parameters
50990             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
50991                 return true;
50992             }
50993             return false;
50994         }
50995         /**
50996          * See signatureRelatedTo, compareSignaturesIdentical
50997          */
50998         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
50999             // TODO (drosen): De-duplicate code between related functions.
51000             if (source === target) {
51001                 return -1 /* True */;
51002             }
51003             if (!(isMatchingSignature(source, target, partialMatch))) {
51004                 return 0 /* False */;
51005             }
51006             // Check that the two signatures have the same number of type parameters.
51007             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
51008                 return 0 /* False */;
51009             }
51010             // Check that type parameter constraints and defaults match. If they do, instantiate the source
51011             // signature with the type parameters of the target signature and continue the comparison.
51012             if (target.typeParameters) {
51013                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
51014                 for (var i = 0; i < target.typeParameters.length; i++) {
51015                     var s = source.typeParameters[i];
51016                     var t = target.typeParameters[i];
51017                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
51018                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
51019                         return 0 /* False */;
51020                     }
51021                 }
51022                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
51023             }
51024             var result = -1 /* True */;
51025             if (!ignoreThisTypes) {
51026                 var sourceThisType = getThisTypeOfSignature(source);
51027                 if (sourceThisType) {
51028                     var targetThisType = getThisTypeOfSignature(target);
51029                     if (targetThisType) {
51030                         var related = compareTypes(sourceThisType, targetThisType);
51031                         if (!related) {
51032                             return 0 /* False */;
51033                         }
51034                         result &= related;
51035                     }
51036                 }
51037             }
51038             var targetLen = getParameterCount(target);
51039             for (var i = 0; i < targetLen; i++) {
51040                 var s = getTypeAtPosition(source, i);
51041                 var t = getTypeAtPosition(target, i);
51042                 var related = compareTypes(t, s);
51043                 if (!related) {
51044                     return 0 /* False */;
51045                 }
51046                 result &= related;
51047             }
51048             if (!ignoreReturnTypes) {
51049                 var sourceTypePredicate = getTypePredicateOfSignature(source);
51050                 var targetTypePredicate = getTypePredicateOfSignature(target);
51051                 result &= sourceTypePredicate || targetTypePredicate ?
51052                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
51053                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51054             }
51055             return result;
51056         }
51057         function compareTypePredicatesIdentical(source, target, compareTypes) {
51058             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
51059                 source.type === target.type ? -1 /* True */ :
51060                     source.type && target.type ? compareTypes(source.type, target.type) :
51061                         0 /* False */;
51062         }
51063         function literalTypesWithSameBaseType(types) {
51064             var commonBaseType;
51065             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
51066                 var t = types_12[_i];
51067                 var baseType = getBaseTypeOfLiteralType(t);
51068                 if (!commonBaseType) {
51069                     commonBaseType = baseType;
51070                 }
51071                 if (baseType === t || baseType !== commonBaseType) {
51072                     return false;
51073                 }
51074             }
51075             return true;
51076         }
51077         // When the candidate types are all literal types with the same base type, return a union
51078         // of those literal types. Otherwise, return the leftmost type for which no type to the
51079         // right is a supertype.
51080         function getSupertypeOrUnion(types) {
51081             return literalTypesWithSameBaseType(types) ?
51082                 getUnionType(types) :
51083                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
51084         }
51085         function getCommonSupertype(types) {
51086             if (!strictNullChecks) {
51087                 return getSupertypeOrUnion(types);
51088             }
51089             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
51090             return primaryTypes.length ?
51091                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
51092                 getUnionType(types, 2 /* Subtype */);
51093         }
51094         // Return the leftmost type for which no type to the right is a subtype.
51095         function getCommonSubtype(types) {
51096             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
51097         }
51098         function isArrayType(type) {
51099             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
51100         }
51101         function isReadonlyArrayType(type) {
51102             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
51103         }
51104         function isMutableArrayOrTuple(type) {
51105             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
51106         }
51107         function getElementTypeOfArrayType(type) {
51108             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
51109         }
51110         function isArrayLikeType(type) {
51111             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
51112             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
51113             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
51114         }
51115         function isEmptyArrayLiteralType(type) {
51116             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
51117             return elementType === undefinedWideningType || elementType === implicitNeverType;
51118         }
51119         function isTupleLikeType(type) {
51120             return isTupleType(type) || !!getPropertyOfType(type, "0");
51121         }
51122         function isArrayOrTupleLikeType(type) {
51123             return isArrayLikeType(type) || isTupleLikeType(type);
51124         }
51125         function getTupleElementType(type, index) {
51126             var propType = getTypeOfPropertyOfType(type, "" + index);
51127             if (propType) {
51128                 return propType;
51129             }
51130             if (everyType(type, isTupleType)) {
51131                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
51132             }
51133             return undefined;
51134         }
51135         function isNeitherUnitTypeNorNever(type) {
51136             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
51137         }
51138         function isUnitType(type) {
51139             return !!(type.flags & 109440 /* Unit */);
51140         }
51141         function isLiteralType(type) {
51142             return type.flags & 16 /* Boolean */ ? true :
51143                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
51144                     isUnitType(type);
51145         }
51146         function getBaseTypeOfLiteralType(type) {
51147             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
51148                 type.flags & 128 /* StringLiteral */ ? stringType :
51149                     type.flags & 256 /* NumberLiteral */ ? numberType :
51150                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
51151                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
51152                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
51153                                     type;
51154         }
51155         function getWidenedLiteralType(type) {
51156             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
51157                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
51158                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
51159                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
51160                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
51161                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
51162                                     type;
51163         }
51164         function getWidenedUniqueESSymbolType(type) {
51165             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
51166                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
51167                     type;
51168         }
51169         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
51170             if (!isLiteralOfContextualType(type, contextualType)) {
51171                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
51172             }
51173             return type;
51174         }
51175         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
51176             if (type && isUnitType(type)) {
51177                 var contextualType = !contextualSignatureReturnType ? undefined :
51178                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
51179                         contextualSignatureReturnType;
51180                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51181             }
51182             return type;
51183         }
51184         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
51185             if (type && isUnitType(type)) {
51186                 var contextualType = !contextualSignatureReturnType ? undefined :
51187                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
51188                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51189             }
51190             return type;
51191         }
51192         /**
51193          * Check if a Type was written as a tuple type literal.
51194          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
51195          */
51196         function isTupleType(type) {
51197             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
51198         }
51199         function getRestTypeOfTupleType(type) {
51200             return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
51201         }
51202         function getRestArrayTypeOfTupleType(type) {
51203             var restType = getRestTypeOfTupleType(type);
51204             return restType && createArrayType(restType);
51205         }
51206         function getLengthOfTupleType(type) {
51207             return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
51208         }
51209         function isZeroBigInt(_a) {
51210             var value = _a.value;
51211             return value.base10Value === "0";
51212         }
51213         function getFalsyFlagsOfTypes(types) {
51214             var result = 0;
51215             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
51216                 var t = types_13[_i];
51217                 result |= getFalsyFlags(t);
51218             }
51219             return result;
51220         }
51221         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
51222         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
51223         // no flags for all other types (including non-falsy literal types).
51224         function getFalsyFlags(type) {
51225             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
51226                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
51227                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
51228                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
51229                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
51230                                 type.flags & 117724 /* PossiblyFalsy */;
51231         }
51232         function removeDefinitelyFalsyTypes(type) {
51233             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
51234                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
51235                 type;
51236         }
51237         function extractDefinitelyFalsyTypes(type) {
51238             return mapType(type, getDefinitelyFalsyPartOfType);
51239         }
51240         function getDefinitelyFalsyPartOfType(type) {
51241             return type.flags & 4 /* String */ ? emptyStringType :
51242                 type.flags & 8 /* Number */ ? zeroType :
51243                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
51244                         type === regularFalseType ||
51245                             type === falseType ||
51246                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
51247                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
51248                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
51249                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
51250                             neverType;
51251         }
51252         /**
51253          * Add undefined or null or both to a type if they are missing.
51254          * @param type - type to add undefined and/or null to if not present
51255          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
51256          */
51257         function getNullableType(type, flags) {
51258             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
51259             return missing === 0 ? type :
51260                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
51261                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
51262                         getUnionType([type, undefinedType, nullType]);
51263         }
51264         function getOptionalType(type) {
51265             ts.Debug.assert(strictNullChecks);
51266             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
51267         }
51268         function getGlobalNonNullableTypeInstantiation(type) {
51269             if (!deferredGlobalNonNullableTypeAlias) {
51270                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
51271             }
51272             // Use NonNullable global type alias if available to improve quick info/declaration emit
51273             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
51274                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
51275             }
51276             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
51277         }
51278         function getNonNullableType(type) {
51279             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
51280         }
51281         function addOptionalTypeMarker(type) {
51282             return strictNullChecks ? getUnionType([type, optionalType]) : type;
51283         }
51284         function isNotOptionalTypeMarker(type) {
51285             return type !== optionalType;
51286         }
51287         function removeOptionalTypeMarker(type) {
51288             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
51289         }
51290         function propagateOptionalTypeMarker(type, node, wasOptional) {
51291             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
51292         }
51293         function getOptionalExpressionType(exprType, expression) {
51294             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
51295                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
51296                     exprType;
51297         }
51298         /**
51299          * Is source potentially coercible to target type under `==`.
51300          * Assumes that `source` is a constituent of a union, hence
51301          * the boolean literal flag on the LHS, but not on the RHS.
51302          *
51303          * This does not fully replicate the semantics of `==`. The
51304          * intention is to catch cases that are clearly not right.
51305          *
51306          * Comparing (string | number) to number should not remove the
51307          * string element.
51308          *
51309          * Comparing (string | number) to 1 will remove the string
51310          * element, though this is not sound. This is a pragmatic
51311          * choice.
51312          *
51313          * @see narrowTypeByEquality
51314          *
51315          * @param source
51316          * @param target
51317          */
51318         function isCoercibleUnderDoubleEquals(source, target) {
51319             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
51320                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
51321         }
51322         /**
51323          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
51324          * with no call or construct signatures.
51325          */
51326         function isObjectTypeWithInferableIndex(type) {
51327             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
51328                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
51329                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
51330         }
51331         function createSymbolWithType(source, type) {
51332             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
51333             symbol.declarations = source.declarations;
51334             symbol.parent = source.parent;
51335             symbol.type = type;
51336             symbol.target = source;
51337             if (source.valueDeclaration) {
51338                 symbol.valueDeclaration = source.valueDeclaration;
51339             }
51340             var nameType = getSymbolLinks(source).nameType;
51341             if (nameType) {
51342                 symbol.nameType = nameType;
51343             }
51344             return symbol;
51345         }
51346         function transformTypeOfMembers(type, f) {
51347             var members = ts.createSymbolTable();
51348             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51349                 var property = _a[_i];
51350                 var original = getTypeOfSymbol(property);
51351                 var updated = f(original);
51352                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
51353             }
51354             return members;
51355         }
51356         /**
51357          * If the the provided object literal is subject to the excess properties check,
51358          * create a new that is exempt. Recursively mark object literal members as exempt.
51359          * Leave signatures alone since they are not subject to the check.
51360          */
51361         function getRegularTypeOfObjectLiteral(type) {
51362             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
51363                 return type;
51364             }
51365             var regularType = type.regularType;
51366             if (regularType) {
51367                 return regularType;
51368             }
51369             var resolved = type;
51370             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
51371             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
51372             regularNew.flags = resolved.flags;
51373             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
51374             type.regularType = regularNew;
51375             return regularNew;
51376         }
51377         function createWideningContext(parent, propertyName, siblings) {
51378             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
51379         }
51380         function getSiblingsOfContext(context) {
51381             if (!context.siblings) {
51382                 var siblings_1 = [];
51383                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
51384                     var type = _a[_i];
51385                     if (isObjectLiteralType(type)) {
51386                         var prop = getPropertyOfObjectType(type, context.propertyName);
51387                         if (prop) {
51388                             forEachType(getTypeOfSymbol(prop), function (t) {
51389                                 siblings_1.push(t);
51390                             });
51391                         }
51392                     }
51393                 }
51394                 context.siblings = siblings_1;
51395             }
51396             return context.siblings;
51397         }
51398         function getPropertiesOfContext(context) {
51399             if (!context.resolvedProperties) {
51400                 var names = ts.createMap();
51401                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
51402                     var t = _a[_i];
51403                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
51404                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
51405                             var prop = _c[_b];
51406                             names.set(prop.escapedName, prop);
51407                         }
51408                     }
51409                 }
51410                 context.resolvedProperties = ts.arrayFrom(names.values());
51411             }
51412             return context.resolvedProperties;
51413         }
51414         function getWidenedProperty(prop, context) {
51415             if (!(prop.flags & 4 /* Property */)) {
51416                 // Since get accessors already widen their return value there is no need to
51417                 // widen accessor based properties here.
51418                 return prop;
51419             }
51420             var original = getTypeOfSymbol(prop);
51421             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
51422             var widened = getWidenedTypeWithContext(original, propContext);
51423             return widened === original ? prop : createSymbolWithType(prop, widened);
51424         }
51425         function getUndefinedProperty(prop) {
51426             var cached = undefinedProperties.get(prop.escapedName);
51427             if (cached) {
51428                 return cached;
51429             }
51430             var result = createSymbolWithType(prop, undefinedType);
51431             result.flags |= 16777216 /* Optional */;
51432             undefinedProperties.set(prop.escapedName, result);
51433             return result;
51434         }
51435         function getWidenedTypeOfObjectLiteral(type, context) {
51436             var members = ts.createSymbolTable();
51437             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51438                 var prop = _a[_i];
51439                 members.set(prop.escapedName, getWidenedProperty(prop, context));
51440             }
51441             if (context) {
51442                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
51443                     var prop = _c[_b];
51444                     if (!members.has(prop.escapedName)) {
51445                         members.set(prop.escapedName, getUndefinedProperty(prop));
51446                     }
51447                 }
51448             }
51449             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
51450             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
51451             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
51452             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
51453             return result;
51454         }
51455         function getWidenedType(type) {
51456             return getWidenedTypeWithContext(type, /*context*/ undefined);
51457         }
51458         function getWidenedTypeWithContext(type, context) {
51459             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
51460                 if (context === undefined && type.widened) {
51461                     return type.widened;
51462                 }
51463                 var result = void 0;
51464                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
51465                     result = anyType;
51466                 }
51467                 else if (isObjectLiteralType(type)) {
51468                     result = getWidenedTypeOfObjectLiteral(type, context);
51469                 }
51470                 else if (type.flags & 1048576 /* Union */) {
51471                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
51472                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
51473                     // Widening an empty object literal transitions from a highly restrictive type to
51474                     // a highly inclusive one. For that reason we perform subtype reduction here if the
51475                     // union includes empty object types (e.g. reducing {} | string to just {}).
51476                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
51477                 }
51478                 else if (type.flags & 2097152 /* Intersection */) {
51479                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
51480                 }
51481                 else if (isArrayType(type) || isTupleType(type)) {
51482                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
51483                 }
51484                 if (result && context === undefined) {
51485                     type.widened = result;
51486                 }
51487                 return result || type;
51488             }
51489             return type;
51490         }
51491         /**
51492          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
51493          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
51494          * getWidenedType. But in some cases getWidenedType is called without reporting errors
51495          * (type argument inference is an example).
51496          *
51497          * The return value indicates whether an error was in fact reported. The particular circumstances
51498          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
51499          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
51500          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
51501          */
51502         function reportWideningErrorsInType(type) {
51503             var errorReported = false;
51504             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
51505                 if (type.flags & 1048576 /* Union */) {
51506                     if (ts.some(type.types, isEmptyObjectType)) {
51507                         errorReported = true;
51508                     }
51509                     else {
51510                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51511                             var t = _a[_i];
51512                             if (reportWideningErrorsInType(t)) {
51513                                 errorReported = true;
51514                             }
51515                         }
51516                     }
51517                 }
51518                 if (isArrayType(type) || isTupleType(type)) {
51519                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
51520                         var t = _c[_b];
51521                         if (reportWideningErrorsInType(t)) {
51522                             errorReported = true;
51523                         }
51524                     }
51525                 }
51526                 if (isObjectLiteralType(type)) {
51527                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
51528                         var p = _e[_d];
51529                         var t = getTypeOfSymbol(p);
51530                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
51531                             if (!reportWideningErrorsInType(t)) {
51532                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
51533                             }
51534                             errorReported = true;
51535                         }
51536                     }
51537                 }
51538             }
51539             return errorReported;
51540         }
51541         function reportImplicitAny(declaration, type, wideningKind) {
51542             var typeAsString = typeToString(getWidenedType(type));
51543             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
51544                 // Only report implicit any errors/suggestions in TS and ts-check JS files
51545                 return;
51546             }
51547             var diagnostic;
51548             switch (declaration.kind) {
51549                 case 209 /* BinaryExpression */:
51550                 case 159 /* PropertyDeclaration */:
51551                 case 158 /* PropertySignature */:
51552                     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;
51553                     break;
51554                 case 156 /* Parameter */:
51555                     var param = declaration;
51556                     if (ts.isIdentifier(param.name) &&
51557                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
51558                         param.parent.parameters.indexOf(param) > -1 &&
51559                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
51560                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
51561                         var newName = "arg" + param.parent.parameters.indexOf(param);
51562                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
51563                         return;
51564                     }
51565                     diagnostic = declaration.dotDotDotToken ?
51566                         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 :
51567                         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;
51568                     break;
51569                 case 191 /* BindingElement */:
51570                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
51571                     if (!noImplicitAny) {
51572                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
51573                         return;
51574                     }
51575                     break;
51576                 case 300 /* JSDocFunctionType */:
51577                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51578                     return;
51579                 case 244 /* FunctionDeclaration */:
51580                 case 161 /* MethodDeclaration */:
51581                 case 160 /* MethodSignature */:
51582                 case 163 /* GetAccessor */:
51583                 case 164 /* SetAccessor */:
51584                 case 201 /* FunctionExpression */:
51585                 case 202 /* ArrowFunction */:
51586                     if (noImplicitAny && !declaration.name) {
51587                         if (wideningKind === 3 /* GeneratorYield */) {
51588                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
51589                         }
51590                         else {
51591                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51592                         }
51593                         return;
51594                     }
51595                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
51596                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
51597                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
51598                     break;
51599                 case 186 /* MappedType */:
51600                     if (noImplicitAny) {
51601                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
51602                     }
51603                     return;
51604                 default:
51605                     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;
51606             }
51607             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
51608         }
51609         function reportErrorsFromWidening(declaration, type, wideningKind) {
51610             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
51611                 // Report implicit any error within type if possible, otherwise report error on declaration
51612                 if (!reportWideningErrorsInType(type)) {
51613                     reportImplicitAny(declaration, type, wideningKind);
51614                 }
51615             }
51616         }
51617         function applyToParameterTypes(source, target, callback) {
51618             var sourceCount = getParameterCount(source);
51619             var targetCount = getParameterCount(target);
51620             var sourceRestType = getEffectiveRestType(source);
51621             var targetRestType = getEffectiveRestType(target);
51622             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
51623             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
51624             var sourceThisType = getThisTypeOfSignature(source);
51625             if (sourceThisType) {
51626                 var targetThisType = getThisTypeOfSignature(target);
51627                 if (targetThisType) {
51628                     callback(sourceThisType, targetThisType);
51629                 }
51630             }
51631             for (var i = 0; i < paramCount; i++) {
51632                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
51633             }
51634             if (targetRestType) {
51635                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
51636             }
51637         }
51638         function applyToReturnTypes(source, target, callback) {
51639             var sourceTypePredicate = getTypePredicateOfSignature(source);
51640             var targetTypePredicate = getTypePredicateOfSignature(target);
51641             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
51642                 callback(sourceTypePredicate.type, targetTypePredicate.type);
51643             }
51644             else {
51645                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51646             }
51647         }
51648         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
51649             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
51650         }
51651         function cloneInferenceContext(context, extraFlags) {
51652             if (extraFlags === void 0) { extraFlags = 0; }
51653             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
51654         }
51655         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
51656             var context = {
51657                 inferences: inferences,
51658                 signature: signature,
51659                 flags: flags,
51660                 compareTypes: compareTypes,
51661                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
51662                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
51663             };
51664             return context;
51665         }
51666         function mapToInferredType(context, t, fix) {
51667             var inferences = context.inferences;
51668             for (var i = 0; i < inferences.length; i++) {
51669                 var inference = inferences[i];
51670                 if (t === inference.typeParameter) {
51671                     if (fix && !inference.isFixed) {
51672                         clearCachedInferences(inferences);
51673                         inference.isFixed = true;
51674                     }
51675                     return getInferredType(context, i);
51676                 }
51677             }
51678             return t;
51679         }
51680         function clearCachedInferences(inferences) {
51681             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
51682                 var inference = inferences_1[_i];
51683                 if (!inference.isFixed) {
51684                     inference.inferredType = undefined;
51685                 }
51686             }
51687         }
51688         function createInferenceInfo(typeParameter) {
51689             return {
51690                 typeParameter: typeParameter,
51691                 candidates: undefined,
51692                 contraCandidates: undefined,
51693                 inferredType: undefined,
51694                 priority: undefined,
51695                 topLevel: true,
51696                 isFixed: false
51697             };
51698         }
51699         function cloneInferenceInfo(inference) {
51700             return {
51701                 typeParameter: inference.typeParameter,
51702                 candidates: inference.candidates && inference.candidates.slice(),
51703                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
51704                 inferredType: inference.inferredType,
51705                 priority: inference.priority,
51706                 topLevel: inference.topLevel,
51707                 isFixed: inference.isFixed
51708             };
51709         }
51710         function cloneInferredPartOfContext(context) {
51711             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
51712             return inferences.length ?
51713                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
51714                 undefined;
51715         }
51716         function getMapperFromContext(context) {
51717             return context && context.mapper;
51718         }
51719         // Return true if the given type could possibly reference a type parameter for which
51720         // we perform type inference (i.e. a type parameter of a generic function). We cache
51721         // results for union and intersection types for performance reasons.
51722         function couldContainTypeVariables(type) {
51723             var objectFlags = ts.getObjectFlags(type);
51724             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
51725                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
51726             }
51727             var result = !!(type.flags & 63176704 /* Instantiable */ ||
51728                 objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
51729                 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
51730                 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
51731                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables));
51732             if (type.flags & 3899393 /* ObjectFlagsType */) {
51733                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
51734             }
51735             return result;
51736         }
51737         function isTypeParameterAtTopLevel(type, typeParameter) {
51738             return !!(type === typeParameter ||
51739                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
51740                 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
51741                     isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
51742         }
51743         /** Create an object with properties named in the string literal type. Every property has type `any` */
51744         function createEmptyObjectTypeFromStringLiteral(type) {
51745             var members = ts.createSymbolTable();
51746             forEachType(type, function (t) {
51747                 if (!(t.flags & 128 /* StringLiteral */)) {
51748                     return;
51749                 }
51750                 var name = ts.escapeLeadingUnderscores(t.value);
51751                 var literalProp = createSymbol(4 /* Property */, name);
51752                 literalProp.type = anyType;
51753                 if (t.symbol) {
51754                     literalProp.declarations = t.symbol.declarations;
51755                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
51756                 }
51757                 members.set(name, literalProp);
51758             });
51759             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
51760             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
51761         }
51762         /**
51763          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
51764          * an object type with the same set of properties as the source type, where the type of each
51765          * property is computed by inferring from the source property type to X for the type
51766          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
51767          */
51768         function inferTypeForHomomorphicMappedType(source, target, constraint) {
51769             var key = source.id + "," + target.id + "," + constraint.id;
51770             if (reverseMappedCache.has(key)) {
51771                 return reverseMappedCache.get(key);
51772             }
51773             reverseMappedCache.set(key, undefined);
51774             var type = createReverseMappedType(source, target, constraint);
51775             reverseMappedCache.set(key, type);
51776             return type;
51777         }
51778         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
51779         // an object literal type with at least one property of an inferable type. For example, an object
51780         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
51781         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
51782         function isPartiallyInferableType(type) {
51783             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
51784                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
51785         }
51786         function createReverseMappedType(source, target, constraint) {
51787             // We consider a source type reverse mappable if it has a string index signature or if
51788             // it has one or more properties and is of a partially inferable type.
51789             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
51790                 return undefined;
51791             }
51792             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
51793             // applied to the element type(s).
51794             if (isArrayType(source)) {
51795                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
51796             }
51797             if (isTupleType(source)) {
51798                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
51799                 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
51800                     getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
51801                 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
51802             }
51803             // For all other object types we infer a new object type where the reverse mapping has been
51804             // applied to the type of each property.
51805             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
51806             reversed.source = source;
51807             reversed.mappedType = target;
51808             reversed.constraintType = constraint;
51809             return reversed;
51810         }
51811         function getTypeOfReverseMappedSymbol(symbol) {
51812             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
51813         }
51814         function inferReverseMappedType(sourceType, target, constraint) {
51815             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
51816             var templateType = getTemplateTypeFromMappedType(target);
51817             var inference = createInferenceInfo(typeParameter);
51818             inferTypes([inference], sourceType, templateType);
51819             return getTypeFromInference(inference) || unknownType;
51820         }
51821         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51822             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
51823             return __generator(this, function (_a) {
51824                 switch (_a.label) {
51825                     case 0:
51826                         properties = getPropertiesOfType(target);
51827                         _i = 0, properties_2 = properties;
51828                         _a.label = 1;
51829                     case 1:
51830                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
51831                         targetProp = properties_2[_i];
51832                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
51833                         if (isStaticPrivateIdentifierProperty(targetProp)) {
51834                             return [3 /*break*/, 5];
51835                         }
51836                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
51837                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
51838                         if (!!sourceProp) return [3 /*break*/, 3];
51839                         return [4 /*yield*/, targetProp];
51840                     case 2:
51841                         _a.sent();
51842                         return [3 /*break*/, 5];
51843                     case 3:
51844                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
51845                         targetType = getTypeOfSymbol(targetProp);
51846                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
51847                         sourceType = getTypeOfSymbol(sourceProp);
51848                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
51849                         return [4 /*yield*/, targetProp];
51850                     case 4:
51851                         _a.sent();
51852                         _a.label = 5;
51853                     case 5:
51854                         _i++;
51855                         return [3 /*break*/, 1];
51856                     case 6: return [2 /*return*/];
51857                 }
51858             });
51859         }
51860         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51861             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
51862             if (!result.done)
51863                 return result.value;
51864         }
51865         function tupleTypesDefinitelyUnrelated(source, target) {
51866             return target.target.minLength > source.target.minLength ||
51867                 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
51868         }
51869         function typesDefinitelyUnrelated(source, target) {
51870             // Two tuple types with incompatible arities are definitely unrelated.
51871             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
51872             return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
51873                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
51874                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
51875         }
51876         function getTypeFromInference(inference) {
51877             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
51878                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
51879                     undefined;
51880         }
51881         function hasSkipDirectInferenceFlag(node) {
51882             return !!getNodeLinks(node).skipDirectInference;
51883         }
51884         function isFromInferenceBlockedSource(type) {
51885             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
51886         }
51887         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
51888             if (priority === void 0) { priority = 0; }
51889             if (contravariant === void 0) { contravariant = false; }
51890             var symbolOrTypeStack;
51891             var visited;
51892             var bivariant = false;
51893             var propagationType;
51894             var inferencePriority = 512 /* MaxValue */;
51895             var allowComplexConstraintInference = true;
51896             inferFromTypes(originalSource, originalTarget);
51897             function inferFromTypes(source, target) {
51898                 if (!couldContainTypeVariables(target)) {
51899                     return;
51900                 }
51901                 if (source === wildcardType) {
51902                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
51903                     // referenced in the target type, so we record it as the propagation type and infer from the
51904                     // target to itself. Then, as we find candidates we substitute the propagation type.
51905                     var savePropagationType = propagationType;
51906                     propagationType = source;
51907                     inferFromTypes(target, target);
51908                     propagationType = savePropagationType;
51909                     return;
51910                 }
51911                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
51912                     // Source and target are types originating in the same generic type alias declaration.
51913                     // Simply infer from source type arguments to target type arguments.
51914                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
51915                     return;
51916                 }
51917                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
51918                     // When source and target are the same union or intersection type, just relate each constituent
51919                     // type to itself.
51920                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
51921                         var t = _a[_i];
51922                         inferFromTypes(t, t);
51923                     }
51924                     return;
51925                 }
51926                 if (target.flags & 1048576 /* Union */) {
51927                     // First, infer between identically matching source and target constituents and remove the
51928                     // matching types.
51929                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
51930                     // Next, infer between closely matching source and target constituents and remove
51931                     // the matching types. Types closely match when they are instantiations of the same
51932                     // object type or instantiations of the same type alias.
51933                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
51934                     if (targets.length === 0) {
51935                         return;
51936                     }
51937                     target = getUnionType(targets);
51938                     if (sources.length === 0) {
51939                         // All source constituents have been matched and there is nothing further to infer from.
51940                         // However, simply making no inferences is undesirable because it could ultimately mean
51941                         // inferring a type parameter constraint. Instead, make a lower priority inference from
51942                         // the full source to whatever remains in the target. For example, when inferring from
51943                         // string to 'string | T', make a lower priority inference of string for T.
51944                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
51945                         return;
51946                     }
51947                     source = getUnionType(sources);
51948                 }
51949                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
51950                     // We reduce intersection types only when they contain naked type parameters. For example, when
51951                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
51952                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
51953                     // string[] on the source side and infer string for T.
51954                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
51955                     // in such scenarios.
51956                     if (!(source.flags & 1048576 /* Union */)) {
51957                         // Infer between identically matching source and target constituents and remove the matching types.
51958                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
51959                         if (sources.length === 0 || targets.length === 0) {
51960                             return;
51961                         }
51962                         source = getIntersectionType(sources);
51963                         target = getIntersectionType(targets);
51964                     }
51965                 }
51966                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
51967                     target = getActualTypeVariable(target);
51968                 }
51969                 if (target.flags & 8650752 /* TypeVariable */) {
51970                     // If target is a type parameter, make an inference, unless the source type contains
51971                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
51972                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
51973                     // it as an inference candidate. Hopefully, a better candidate will come along that does
51974                     // not contain anyFunctionType when we come back to this argument for its second round
51975                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
51976                     // when constructing types from type parameters that had no inference candidates).
51977                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
51978                         (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
51979                         return;
51980                     }
51981                     var inference = getInferenceInfoForType(target);
51982                     if (inference) {
51983                         if (!inference.isFixed) {
51984                             if (inference.priority === undefined || priority < inference.priority) {
51985                                 inference.candidates = undefined;
51986                                 inference.contraCandidates = undefined;
51987                                 inference.topLevel = true;
51988                                 inference.priority = priority;
51989                             }
51990                             if (priority === inference.priority) {
51991                                 var candidate = propagationType || source;
51992                                 // We make contravariant inferences only if we are in a pure contravariant position,
51993                                 // i.e. only if we have not descended into a bivariant position.
51994                                 if (contravariant && !bivariant) {
51995                                     if (!ts.contains(inference.contraCandidates, candidate)) {
51996                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
51997                                         clearCachedInferences(inferences);
51998                                     }
51999                                 }
52000                                 else if (!ts.contains(inference.candidates, candidate)) {
52001                                     inference.candidates = ts.append(inference.candidates, candidate);
52002                                     clearCachedInferences(inferences);
52003                                 }
52004                             }
52005                             if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
52006                                 inference.topLevel = false;
52007                                 clearCachedInferences(inferences);
52008                             }
52009                         }
52010                         inferencePriority = Math.min(inferencePriority, priority);
52011                         return;
52012                     }
52013                     else {
52014                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
52015                         var simplified = getSimplifiedType(target, /*writing*/ false);
52016                         if (simplified !== target) {
52017                             invokeOnce(source, simplified, inferFromTypes);
52018                         }
52019                         else if (target.flags & 8388608 /* IndexedAccess */) {
52020                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
52021                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
52022                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
52023                             if (indexType.flags & 63176704 /* Instantiable */) {
52024                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
52025                                 if (simplified_1 && simplified_1 !== target) {
52026                                     invokeOnce(source, simplified_1, inferFromTypes);
52027                                 }
52028                             }
52029                         }
52030                     }
52031                 }
52032                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
52033                     !(source.node && target.node)) {
52034                     // If source and target are references to the same generic type, infer from type arguments
52035                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52036                 }
52037                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
52038                     contravariant = !contravariant;
52039                     inferFromTypes(source.type, target.type);
52040                     contravariant = !contravariant;
52041                 }
52042                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
52043                     var empty = createEmptyObjectTypeFromStringLiteral(source);
52044                     contravariant = !contravariant;
52045                     inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
52046                     contravariant = !contravariant;
52047                 }
52048                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
52049                     inferFromTypes(source.objectType, target.objectType);
52050                     inferFromTypes(source.indexType, target.indexType);
52051                 }
52052                 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
52053                     inferFromTypes(source.checkType, target.checkType);
52054                     inferFromTypes(source.extendsType, target.extendsType);
52055                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
52056                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
52057                 }
52058                 else if (target.flags & 16777216 /* Conditional */) {
52059                     var savePriority = priority;
52060                     priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
52061                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
52062                     inferToMultipleTypes(source, targetTypes, target.flags);
52063                     priority = savePriority;
52064                 }
52065                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
52066                     inferToMultipleTypes(source, target.types, target.flags);
52067                 }
52068                 else if (source.flags & 1048576 /* Union */) {
52069                     // Source is a union or intersection type, infer from each constituent type
52070                     var sourceTypes = source.types;
52071                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
52072                         var sourceType = sourceTypes_2[_e];
52073                         inferFromTypes(sourceType, target);
52074                     }
52075                 }
52076                 else {
52077                     source = getReducedType(source);
52078                     if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
52079                         var apparentSource = getApparentType(source);
52080                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
52081                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
52082                         // with the simplified source.
52083                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
52084                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
52085                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
52086                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
52087                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
52088                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
52089                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
52090                             // remove this `allowComplexConstraintInference` flag.
52091                             allowComplexConstraintInference = false;
52092                             return inferFromTypes(apparentSource, target);
52093                         }
52094                         source = apparentSource;
52095                     }
52096                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
52097                         invokeOnce(source, target, inferFromObjectTypes);
52098                     }
52099                 }
52100                 if (source.flags & 25165824 /* Simplifiable */) {
52101                     var simplified = getSimplifiedType(source, contravariant);
52102                     if (simplified !== source) {
52103                         inferFromTypes(simplified, target);
52104                     }
52105                 }
52106             }
52107             function inferWithPriority(source, target, newPriority) {
52108                 var savePriority = priority;
52109                 priority |= newPriority;
52110                 inferFromTypes(source, target);
52111                 priority = savePriority;
52112             }
52113             function invokeOnce(source, target, action) {
52114                 var key = source.id + "," + target.id;
52115                 var status = visited && visited.get(key);
52116                 if (status !== undefined) {
52117                     inferencePriority = Math.min(inferencePriority, status);
52118                     return;
52119                 }
52120                 (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
52121                 var saveInferencePriority = inferencePriority;
52122                 inferencePriority = 512 /* MaxValue */;
52123                 action(source, target);
52124                 visited.set(key, inferencePriority);
52125                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52126             }
52127             function inferFromMatchingTypes(sources, targets, matches) {
52128                 var matchedSources;
52129                 var matchedTargets;
52130                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
52131                     var t = targets_1[_i];
52132                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
52133                         var s = sources_1[_a];
52134                         if (matches(s, t)) {
52135                             inferFromTypes(s, t);
52136                             matchedSources = ts.appendIfUnique(matchedSources, s);
52137                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
52138                         }
52139                     }
52140                 }
52141                 return [
52142                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
52143                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
52144                 ];
52145             }
52146             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
52147                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
52148                 for (var i = 0; i < count; i++) {
52149                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
52150                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
52151                     }
52152                     else {
52153                         inferFromTypes(sourceTypes[i], targetTypes[i]);
52154                     }
52155                 }
52156             }
52157             function inferFromContravariantTypes(source, target) {
52158                 if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
52159                     contravariant = !contravariant;
52160                     inferFromTypes(source, target);
52161                     contravariant = !contravariant;
52162                 }
52163                 else {
52164                     inferFromTypes(source, target);
52165                 }
52166             }
52167             function getInferenceInfoForType(type) {
52168                 if (type.flags & 8650752 /* TypeVariable */) {
52169                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
52170                         var inference = inferences_2[_i];
52171                         if (type === inference.typeParameter) {
52172                             return inference;
52173                         }
52174                     }
52175                 }
52176                 return undefined;
52177             }
52178             function getSingleTypeVariableFromIntersectionTypes(types) {
52179                 var typeVariable;
52180                 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
52181                     var type = types_14[_i];
52182                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
52183                     if (!t || typeVariable && t !== typeVariable) {
52184                         return undefined;
52185                     }
52186                     typeVariable = t;
52187                 }
52188                 return typeVariable;
52189             }
52190             function inferToMultipleTypes(source, targets, targetFlags) {
52191                 var typeVariableCount = 0;
52192                 if (targetFlags & 1048576 /* Union */) {
52193                     var nakedTypeVariable = void 0;
52194                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
52195                     var matched_1 = new Array(sources.length);
52196                     var inferenceCircularity = false;
52197                     // First infer to types that are not naked type variables. For each source type we
52198                     // track whether inferences were made from that particular type to some target with
52199                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
52200                     // parameter.
52201                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
52202                         var t = targets_2[_i];
52203                         if (getInferenceInfoForType(t)) {
52204                             nakedTypeVariable = t;
52205                             typeVariableCount++;
52206                         }
52207                         else {
52208                             for (var i = 0; i < sources.length; i++) {
52209                                 var saveInferencePriority = inferencePriority;
52210                                 inferencePriority = 512 /* MaxValue */;
52211                                 inferFromTypes(sources[i], t);
52212                                 if (inferencePriority === priority)
52213                                     matched_1[i] = true;
52214                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
52215                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52216                             }
52217                         }
52218                     }
52219                     if (typeVariableCount === 0) {
52220                         // If every target is an intersection of types containing a single naked type variable,
52221                         // make a lower priority inference to that type variable. This handles inferring from
52222                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
52223                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
52224                         if (intersectionTypeVariable) {
52225                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
52226                         }
52227                         return;
52228                     }
52229                     // If the target has a single naked type variable and no inference circularities were
52230                     // encountered above (meaning we explored the types fully), create a union of the source
52231                     // types from which no inferences have been made so far and infer from that union to the
52232                     // naked type variable.
52233                     if (typeVariableCount === 1 && !inferenceCircularity) {
52234                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
52235                         if (unmatched.length) {
52236                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
52237                             return;
52238                         }
52239                     }
52240                 }
52241                 else {
52242                     // We infer from types that are not naked type variables first so that inferences we
52243                     // make from nested naked type variables and given slightly higher priority by virtue
52244                     // of being first in the candidates array.
52245                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
52246                         var t = targets_3[_a];
52247                         if (getInferenceInfoForType(t)) {
52248                             typeVariableCount++;
52249                         }
52250                         else {
52251                             inferFromTypes(source, t);
52252                         }
52253                     }
52254                 }
52255                 // Inferences directly to naked type variables are given lower priority as they are
52256                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
52257                 // we want to infer string for T, not Promise<string> | string. For intersection types
52258                 // we only infer to single naked type variables.
52259                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
52260                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
52261                         var t = targets_4[_b];
52262                         if (getInferenceInfoForType(t)) {
52263                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
52264                         }
52265                     }
52266                 }
52267             }
52268             function inferToMappedType(source, target, constraintType) {
52269                 if (constraintType.flags & 1048576 /* Union */) {
52270                     var result = false;
52271                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
52272                         var type = _a[_i];
52273                         result = inferToMappedType(source, target, type) || result;
52274                     }
52275                     return result;
52276                 }
52277                 if (constraintType.flags & 4194304 /* Index */) {
52278                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
52279                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
52280                     // type and then make a secondary inference from that type to T. We make a secondary inference
52281                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
52282                     var inference = getInferenceInfoForType(constraintType.type);
52283                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
52284                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
52285                         if (inferredType) {
52286                             // We assign a lower priority to inferences made from types containing non-inferrable
52287                             // types because we may only have a partial result (i.e. we may have failed to make
52288                             // reverse inferences for some properties).
52289                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
52290                                 4 /* PartialHomomorphicMappedType */ :
52291                                 2 /* HomomorphicMappedType */);
52292                         }
52293                     }
52294                     return true;
52295                 }
52296                 if (constraintType.flags & 262144 /* TypeParameter */) {
52297                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
52298                     // parameter. First infer from 'keyof S' to K.
52299                     inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
52300                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
52301                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
52302                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
52303                     // Pick<T, K>.
52304                     var extendedConstraint = getConstraintOfType(constraintType);
52305                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
52306                         return true;
52307                     }
52308                     // If no inferences can be made to K's constraint, infer from a union of the property types
52309                     // in the source to the template type X.
52310                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
52311                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
52312                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
52313                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
52314                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
52315                     return true;
52316                 }
52317                 return false;
52318             }
52319             function inferFromObjectTypes(source, target) {
52320                 // If we are already processing another target type with the same associated symbol (such as
52321                 // an instantiation of the same generic type), we do not explore this target as it would yield
52322                 // no further inferences. We exclude the static side of classes from this check since it shares
52323                 // its symbol with the instance side which would lead to false positives.
52324                 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
52325                     !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
52326                 var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
52327                 if (symbolOrType) {
52328                     if (ts.contains(symbolOrTypeStack, symbolOrType)) {
52329                         inferencePriority = -1 /* Circularity */;
52330                         return;
52331                     }
52332                     (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
52333                     inferFromObjectTypesWorker(source, target);
52334                     symbolOrTypeStack.pop();
52335                 }
52336                 else {
52337                     inferFromObjectTypesWorker(source, target);
52338                 }
52339             }
52340             function inferFromObjectTypesWorker(source, target) {
52341                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
52342                     // If source and target are references to the same generic type, infer from type arguments
52343                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52344                     return;
52345                 }
52346                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
52347                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
52348                     // from S to T and from X to Y.
52349                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
52350                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
52351                 }
52352                 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
52353                     var constraintType = getConstraintTypeFromMappedType(target);
52354                     if (inferToMappedType(source, target, constraintType)) {
52355                         return;
52356                     }
52357                 }
52358                 // Infer from the members of source and target only if the two types are possibly related
52359                 if (!typesDefinitelyUnrelated(source, target)) {
52360                     if (isArrayType(source) || isTupleType(source)) {
52361                         if (isTupleType(target)) {
52362                             var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
52363                             var targetLength = getLengthOfTupleType(target);
52364                             var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
52365                             var targetRestType = getRestTypeOfTupleType(target);
52366                             var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
52367                             for (var i = 0; i < fixedLength; i++) {
52368                                 inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
52369                             }
52370                             if (targetRestType) {
52371                                 var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
52372                                 if (sourceRestType) {
52373                                     types.push(sourceRestType);
52374                                 }
52375                                 if (types.length) {
52376                                     inferFromTypes(getUnionType(types), targetRestType);
52377                                 }
52378                             }
52379                             return;
52380                         }
52381                         if (isArrayType(target)) {
52382                             inferFromIndexTypes(source, target);
52383                             return;
52384                         }
52385                     }
52386                     inferFromProperties(source, target);
52387                     inferFromSignatures(source, target, 0 /* Call */);
52388                     inferFromSignatures(source, target, 1 /* Construct */);
52389                     inferFromIndexTypes(source, target);
52390                 }
52391             }
52392             function inferFromProperties(source, target) {
52393                 var properties = getPropertiesOfObjectType(target);
52394                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
52395                     var targetProp = properties_3[_i];
52396                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
52397                     if (sourceProp) {
52398                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
52399                     }
52400                 }
52401             }
52402             function inferFromSignatures(source, target, kind) {
52403                 var sourceSignatures = getSignaturesOfType(source, kind);
52404                 var targetSignatures = getSignaturesOfType(target, kind);
52405                 var sourceLen = sourceSignatures.length;
52406                 var targetLen = targetSignatures.length;
52407                 var len = sourceLen < targetLen ? sourceLen : targetLen;
52408                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
52409                 for (var i = 0; i < len; i++) {
52410                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
52411                 }
52412             }
52413             function inferFromSignature(source, target, skipParameters) {
52414                 if (!skipParameters) {
52415                     var saveBivariant = bivariant;
52416                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
52417                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
52418                     bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
52419                     applyToParameterTypes(source, target, inferFromContravariantTypes);
52420                     bivariant = saveBivariant;
52421                 }
52422                 applyToReturnTypes(source, target, inferFromTypes);
52423             }
52424             function inferFromIndexTypes(source, target) {
52425                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
52426                 if (targetStringIndexType) {
52427                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
52428                         getImplicitIndexTypeOfType(source, 0 /* String */);
52429                     if (sourceIndexType) {
52430                         inferFromTypes(sourceIndexType, targetStringIndexType);
52431                     }
52432                 }
52433                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
52434                 if (targetNumberIndexType) {
52435                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
52436                         getIndexTypeOfType(source, 0 /* String */) ||
52437                         getImplicitIndexTypeOfType(source, 1 /* Number */);
52438                     if (sourceIndexType) {
52439                         inferFromTypes(sourceIndexType, targetNumberIndexType);
52440                     }
52441                 }
52442             }
52443         }
52444         function isTypeOrBaseIdenticalTo(s, t) {
52445             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
52446         }
52447         function isTypeCloselyMatchedBy(s, t) {
52448             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
52449                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
52450         }
52451         function hasPrimitiveConstraint(type) {
52452             var constraint = getConstraintOfTypeParameter(type);
52453             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
52454         }
52455         function isObjectLiteralType(type) {
52456             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
52457         }
52458         function isObjectOrArrayLiteralType(type) {
52459             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
52460         }
52461         function unionObjectAndArrayLiteralCandidates(candidates) {
52462             if (candidates.length > 1) {
52463                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
52464                 if (objectLiterals.length) {
52465                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
52466                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
52467                 }
52468             }
52469             return candidates;
52470         }
52471         function getContravariantInference(inference) {
52472             return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
52473         }
52474         function getCovariantInference(inference, signature) {
52475             // Extract all object and array literal types and replace them with a single widened and normalized type.
52476             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
52477             // We widen inferred literal types if
52478             // all inferences were made to top-level occurrences of the type parameter, and
52479             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
52480             // the type parameter was fixed during inference or does not occur at top-level in the return type.
52481             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
52482             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
52483                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
52484             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
52485                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
52486                     candidates;
52487             // If all inferences were made from a position that implies a combined result, infer a union type.
52488             // Otherwise, infer a common supertype.
52489             var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
52490                 getUnionType(baseCandidates, 2 /* Subtype */) :
52491                 getCommonSupertype(baseCandidates);
52492             return getWidenedType(unwidenedType);
52493         }
52494         function getInferredType(context, index) {
52495             var inference = context.inferences[index];
52496             if (!inference.inferredType) {
52497                 var inferredType = void 0;
52498                 var signature = context.signature;
52499                 if (signature) {
52500                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
52501                     if (inference.contraCandidates) {
52502                         var inferredContravariantType = getContravariantInference(inference);
52503                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
52504                         // unless the co-variant inference is a subtype and not 'never'.
52505                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
52506                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
52507                             inferredCovariantType : inferredContravariantType;
52508                     }
52509                     else if (inferredCovariantType) {
52510                         inferredType = inferredCovariantType;
52511                     }
52512                     else if (context.flags & 1 /* NoDefault */) {
52513                         // We use silentNeverType as the wildcard that signals no inferences.
52514                         inferredType = silentNeverType;
52515                     }
52516                     else {
52517                         // Infer either the default or the empty object type when no inferences were
52518                         // made. It is important to remember that in this case, inference still
52519                         // succeeds, meaning there is no error for not having inference candidates. An
52520                         // inference error only occurs when there are *conflicting* candidates, i.e.
52521                         // candidates with no common supertype.
52522                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
52523                         if (defaultType) {
52524                             // Instantiate the default type. Any forward reference to a type
52525                             // parameter should be instantiated to the empty object type.
52526                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
52527                         }
52528                     }
52529                 }
52530                 else {
52531                     inferredType = getTypeFromInference(inference);
52532                 }
52533                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
52534                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
52535                 if (constraint) {
52536                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
52537                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
52538                         inference.inferredType = inferredType = instantiatedConstraint;
52539                     }
52540                 }
52541             }
52542             return inference.inferredType;
52543         }
52544         function getDefaultTypeArgumentType(isInJavaScriptFile) {
52545             return isInJavaScriptFile ? anyType : unknownType;
52546         }
52547         function getInferredTypes(context) {
52548             var result = [];
52549             for (var i = 0; i < context.inferences.length; i++) {
52550                 result.push(getInferredType(context, i));
52551             }
52552             return result;
52553         }
52554         // EXPRESSION TYPE CHECKING
52555         function getCannotFindNameDiagnosticForName(node) {
52556             switch (node.escapedText) {
52557                 case "document":
52558                 case "console":
52559                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
52560                 case "$":
52561                     return compilerOptions.types
52562                         ? 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
52563                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
52564                 case "describe":
52565                 case "suite":
52566                 case "it":
52567                 case "test":
52568                     return compilerOptions.types
52569                         ? 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
52570                         : 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;
52571                 case "process":
52572                 case "require":
52573                 case "Buffer":
52574                 case "module":
52575                     return compilerOptions.types
52576                         ? 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
52577                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
52578                 case "Map":
52579                 case "Set":
52580                 case "Promise":
52581                 case "Symbol":
52582                 case "WeakMap":
52583                 case "WeakSet":
52584                 case "Iterator":
52585                 case "AsyncIterator":
52586                     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;
52587                 default:
52588                     if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
52589                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
52590                     }
52591                     else {
52592                         return ts.Diagnostics.Cannot_find_name_0;
52593                     }
52594             }
52595         }
52596         function getResolvedSymbol(node) {
52597             var links = getNodeLinks(node);
52598             if (!links.resolvedSymbol) {
52599                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
52600                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
52601                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
52602             }
52603             return links.resolvedSymbol;
52604         }
52605         function isInTypeQuery(node) {
52606             // TypeScript 1.0 spec (April 2014): 3.6.3
52607             // A type query consists of the keyword typeof followed by an expression.
52608             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
52609             return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
52610         }
52611         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
52612         // separated by dots). The key consists of the id of the symbol referenced by the
52613         // leftmost identifier followed by zero or more property names separated by dots.
52614         // The result is undefined if the reference isn't a dotted name. We prefix nodes
52615         // occurring in an apparent type position with '@' because the control flow type
52616         // of such nodes may be based on the apparent type instead of the declared type.
52617         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
52618             switch (node.kind) {
52619                 case 75 /* Identifier */:
52620                     var symbol = getResolvedSymbol(node);
52621                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
52622                 case 104 /* ThisKeyword */:
52623                     return "0";
52624                 case 218 /* NonNullExpression */:
52625                 case 200 /* ParenthesizedExpression */:
52626                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52627                 case 194 /* PropertyAccessExpression */:
52628                 case 195 /* ElementAccessExpression */:
52629                     var propName = getAccessedPropertyName(node);
52630                     if (propName !== undefined) {
52631                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52632                         return key && key + "." + propName;
52633                     }
52634             }
52635             return undefined;
52636         }
52637         function isMatchingReference(source, target) {
52638             switch (target.kind) {
52639                 case 200 /* ParenthesizedExpression */:
52640                 case 218 /* NonNullExpression */:
52641                     return isMatchingReference(source, target.expression);
52642             }
52643             switch (source.kind) {
52644                 case 75 /* Identifier */:
52645                     return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
52646                         (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
52647                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
52648                 case 104 /* ThisKeyword */:
52649                     return target.kind === 104 /* ThisKeyword */;
52650                 case 102 /* SuperKeyword */:
52651                     return target.kind === 102 /* SuperKeyword */;
52652                 case 218 /* NonNullExpression */:
52653                 case 200 /* ParenthesizedExpression */:
52654                     return isMatchingReference(source.expression, target);
52655                 case 194 /* PropertyAccessExpression */:
52656                 case 195 /* ElementAccessExpression */:
52657                     return ts.isAccessExpression(target) &&
52658                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
52659                         isMatchingReference(source.expression, target.expression);
52660             }
52661             return false;
52662         }
52663         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
52664         function containsTruthyCheck(source, target) {
52665             return isMatchingReference(source, target) ||
52666                 (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
52667                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
52668         }
52669         function getAccessedPropertyName(access) {
52670             return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
52671                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
52672                     undefined;
52673         }
52674         function containsMatchingReference(source, target) {
52675             while (ts.isAccessExpression(source)) {
52676                 source = source.expression;
52677                 if (isMatchingReference(source, target)) {
52678                     return true;
52679                 }
52680             }
52681             return false;
52682         }
52683         function optionalChainContainsReference(source, target) {
52684             while (ts.isOptionalChain(source)) {
52685                 source = source.expression;
52686                 if (isMatchingReference(source, target)) {
52687                     return true;
52688                 }
52689             }
52690             return false;
52691         }
52692         function isDiscriminantProperty(type, name) {
52693             if (type && type.flags & 1048576 /* Union */) {
52694                 var prop = getUnionOrIntersectionProperty(type, name);
52695                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
52696                     if (prop.isDiscriminantProperty === undefined) {
52697                         prop.isDiscriminantProperty =
52698                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
52699                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
52700                     }
52701                     return !!prop.isDiscriminantProperty;
52702                 }
52703             }
52704             return false;
52705         }
52706         function findDiscriminantProperties(sourceProperties, target) {
52707             var result;
52708             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
52709                 var sourceProperty = sourceProperties_2[_i];
52710                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
52711                     if (result) {
52712                         result.push(sourceProperty);
52713                         continue;
52714                     }
52715                     result = [sourceProperty];
52716                 }
52717             }
52718             return result;
52719         }
52720         function isOrContainsMatchingReference(source, target) {
52721             return isMatchingReference(source, target) || containsMatchingReference(source, target);
52722         }
52723         function hasMatchingArgument(callExpression, reference) {
52724             if (callExpression.arguments) {
52725                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
52726                     var argument = _a[_i];
52727                     if (isOrContainsMatchingReference(reference, argument)) {
52728                         return true;
52729                     }
52730                 }
52731             }
52732             if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
52733                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
52734                 return true;
52735             }
52736             return false;
52737         }
52738         function getFlowNodeId(flow) {
52739             if (!flow.id || flow.id < 0) {
52740                 flow.id = nextFlowId;
52741                 nextFlowId++;
52742             }
52743             return flow.id;
52744         }
52745         function typeMaybeAssignableTo(source, target) {
52746             if (!(source.flags & 1048576 /* Union */)) {
52747                 return isTypeAssignableTo(source, target);
52748             }
52749             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52750                 var t = _a[_i];
52751                 if (isTypeAssignableTo(t, target)) {
52752                     return true;
52753                 }
52754             }
52755             return false;
52756         }
52757         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
52758         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
52759         // we remove type string.
52760         function getAssignmentReducedType(declaredType, assignedType) {
52761             if (declaredType !== assignedType) {
52762                 if (assignedType.flags & 131072 /* Never */) {
52763                     return assignedType;
52764                 }
52765                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
52766                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
52767                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
52768                 }
52769                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
52770                 // For now, when that happens, we give up and don't narrow at all.  (This also
52771                 // means we'll never narrow for erroneous assignments where the assigned type
52772                 // is not assignable to the declared type.)
52773                 if (isTypeAssignableTo(assignedType, reducedType)) {
52774                     return reducedType;
52775                 }
52776             }
52777             return declaredType;
52778         }
52779         function getTypeFactsOfTypes(types) {
52780             var result = 0 /* None */;
52781             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
52782                 var t = types_15[_i];
52783                 result |= getTypeFacts(t);
52784             }
52785             return result;
52786         }
52787         function isFunctionObjectType(type) {
52788             // We do a quick check for a "bind" property before performing the more expensive subtype
52789             // check. This gives us a quicker out in the common case where an object type is not a function.
52790             var resolved = resolveStructuredTypeMembers(type);
52791             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
52792                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
52793         }
52794         function getTypeFacts(type) {
52795             var flags = type.flags;
52796             if (flags & 4 /* String */) {
52797                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
52798             }
52799             if (flags & 128 /* StringLiteral */) {
52800                 var isEmpty = type.value === "";
52801                 return strictNullChecks ?
52802                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
52803                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
52804             }
52805             if (flags & (8 /* Number */ | 32 /* Enum */)) {
52806                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
52807             }
52808             if (flags & 256 /* NumberLiteral */) {
52809                 var isZero = type.value === 0;
52810                 return strictNullChecks ?
52811                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
52812                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
52813             }
52814             if (flags & 64 /* BigInt */) {
52815                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
52816             }
52817             if (flags & 2048 /* BigIntLiteral */) {
52818                 var isZero = isZeroBigInt(type);
52819                 return strictNullChecks ?
52820                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
52821                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
52822             }
52823             if (flags & 16 /* Boolean */) {
52824                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
52825             }
52826             if (flags & 528 /* BooleanLike */) {
52827                 return strictNullChecks ?
52828                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
52829                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
52830             }
52831             if (flags & 524288 /* Object */) {
52832                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
52833                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
52834                     isFunctionObjectType(type) ?
52835                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
52836                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52837             }
52838             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
52839                 return 9830144 /* UndefinedFacts */;
52840             }
52841             if (flags & 65536 /* Null */) {
52842                 return 9363232 /* NullFacts */;
52843             }
52844             if (flags & 12288 /* ESSymbolLike */) {
52845                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
52846             }
52847             if (flags & 67108864 /* NonPrimitive */) {
52848                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52849             }
52850             if (flags & 131072 /* Never */) {
52851                 return 0 /* None */;
52852             }
52853             if (flags & 63176704 /* Instantiable */) {
52854                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
52855             }
52856             if (flags & 3145728 /* UnionOrIntersection */) {
52857                 return getTypeFactsOfTypes(type.types);
52858             }
52859             return 16777215 /* All */;
52860         }
52861         function getTypeWithFacts(type, include) {
52862             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
52863         }
52864         function getTypeWithDefault(type, defaultExpression) {
52865             if (defaultExpression) {
52866                 var defaultType = getTypeOfExpression(defaultExpression);
52867                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
52868             }
52869             return type;
52870         }
52871         function getTypeOfDestructuredProperty(type, name) {
52872             var nameType = getLiteralTypeFromPropertyName(name);
52873             if (!isTypeUsableAsPropertyName(nameType))
52874                 return errorType;
52875             var text = getPropertyNameFromType(nameType);
52876             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
52877                 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
52878                 getIndexTypeOfType(type, 0 /* String */) ||
52879                 errorType;
52880         }
52881         function getTypeOfDestructuredArrayElement(type, index) {
52882             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
52883                 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
52884                 errorType;
52885         }
52886         function getTypeOfDestructuredSpreadExpression(type) {
52887             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
52888         }
52889         function getAssignedTypeOfBinaryExpression(node) {
52890             var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
52891                 node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
52892             return isDestructuringDefaultAssignment ?
52893                 getTypeWithDefault(getAssignedType(node), node.right) :
52894                 getTypeOfExpression(node.right);
52895         }
52896         function isDestructuringAssignmentTarget(parent) {
52897             return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
52898                 parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
52899         }
52900         function getAssignedTypeOfArrayLiteralElement(node, element) {
52901             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
52902         }
52903         function getAssignedTypeOfSpreadExpression(node) {
52904             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
52905         }
52906         function getAssignedTypeOfPropertyAssignment(node) {
52907             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
52908         }
52909         function getAssignedTypeOfShorthandPropertyAssignment(node) {
52910             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
52911         }
52912         function getAssignedType(node) {
52913             var parent = node.parent;
52914             switch (parent.kind) {
52915                 case 231 /* ForInStatement */:
52916                     return stringType;
52917                 case 232 /* ForOfStatement */:
52918                     return checkRightHandSideOfForOf(parent) || errorType;
52919                 case 209 /* BinaryExpression */:
52920                     return getAssignedTypeOfBinaryExpression(parent);
52921                 case 203 /* DeleteExpression */:
52922                     return undefinedType;
52923                 case 192 /* ArrayLiteralExpression */:
52924                     return getAssignedTypeOfArrayLiteralElement(parent, node);
52925                 case 213 /* SpreadElement */:
52926                     return getAssignedTypeOfSpreadExpression(parent);
52927                 case 281 /* PropertyAssignment */:
52928                     return getAssignedTypeOfPropertyAssignment(parent);
52929                 case 282 /* ShorthandPropertyAssignment */:
52930                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
52931             }
52932             return errorType;
52933         }
52934         function getInitialTypeOfBindingElement(node) {
52935             var pattern = node.parent;
52936             var parentType = getInitialType(pattern.parent);
52937             var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
52938                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
52939                 !node.dotDotDotToken ?
52940                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
52941                     getTypeOfDestructuredSpreadExpression(parentType);
52942             return getTypeWithDefault(type, node.initializer);
52943         }
52944         function getTypeOfInitializer(node) {
52945             // Return the cached type if one is available. If the type of the variable was inferred
52946             // from its initializer, we'll already have cached the type. Otherwise we compute it now
52947             // without caching such that transient types are reflected.
52948             var links = getNodeLinks(node);
52949             return links.resolvedType || getTypeOfExpression(node);
52950         }
52951         function getInitialTypeOfVariableDeclaration(node) {
52952             if (node.initializer) {
52953                 return getTypeOfInitializer(node.initializer);
52954             }
52955             if (node.parent.parent.kind === 231 /* ForInStatement */) {
52956                 return stringType;
52957             }
52958             if (node.parent.parent.kind === 232 /* ForOfStatement */) {
52959                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
52960             }
52961             return errorType;
52962         }
52963         function getInitialType(node) {
52964             return node.kind === 242 /* VariableDeclaration */ ?
52965                 getInitialTypeOfVariableDeclaration(node) :
52966                 getInitialTypeOfBindingElement(node);
52967         }
52968         function isEmptyArrayAssignment(node) {
52969             return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
52970                 isEmptyArrayLiteral(node.initializer) ||
52971                 node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
52972                     isEmptyArrayLiteral(node.parent.right);
52973         }
52974         function getReferenceCandidate(node) {
52975             switch (node.kind) {
52976                 case 200 /* ParenthesizedExpression */:
52977                     return getReferenceCandidate(node.expression);
52978                 case 209 /* BinaryExpression */:
52979                     switch (node.operatorToken.kind) {
52980                         case 62 /* EqualsToken */:
52981                             return getReferenceCandidate(node.left);
52982                         case 27 /* CommaToken */:
52983                             return getReferenceCandidate(node.right);
52984                     }
52985             }
52986             return node;
52987         }
52988         function getReferenceRoot(node) {
52989             var parent = node.parent;
52990             return parent.kind === 200 /* ParenthesizedExpression */ ||
52991                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
52992                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
52993                 getReferenceRoot(parent) : node;
52994         }
52995         function getTypeOfSwitchClause(clause) {
52996             if (clause.kind === 277 /* CaseClause */) {
52997                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
52998             }
52999             return neverType;
53000         }
53001         function getSwitchClauseTypes(switchStatement) {
53002             var links = getNodeLinks(switchStatement);
53003             if (!links.switchTypes) {
53004                 links.switchTypes = [];
53005                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
53006                     var clause = _a[_i];
53007                     links.switchTypes.push(getTypeOfSwitchClause(clause));
53008                 }
53009             }
53010             return links.switchTypes;
53011         }
53012         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
53013             var witnesses = [];
53014             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
53015                 var clause = _a[_i];
53016                 if (clause.kind === 277 /* CaseClause */) {
53017                     if (ts.isStringLiteralLike(clause.expression)) {
53018                         witnesses.push(clause.expression.text);
53019                         continue;
53020                     }
53021                     return ts.emptyArray;
53022                 }
53023                 if (retainDefault)
53024                     witnesses.push(/*explicitDefaultStatement*/ undefined);
53025             }
53026             return witnesses;
53027         }
53028         function eachTypeContainedIn(source, types) {
53029             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
53030         }
53031         function isTypeSubsetOf(source, target) {
53032             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
53033         }
53034         function isTypeSubsetOfUnion(source, target) {
53035             if (source.flags & 1048576 /* Union */) {
53036                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
53037                     var t = _a[_i];
53038                     if (!containsType(target.types, t)) {
53039                         return false;
53040                     }
53041                 }
53042                 return true;
53043             }
53044             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
53045                 return true;
53046             }
53047             return containsType(target.types, source);
53048         }
53049         function forEachType(type, f) {
53050             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
53051         }
53052         function everyType(type, f) {
53053             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
53054         }
53055         function filterType(type, f) {
53056             if (type.flags & 1048576 /* Union */) {
53057                 var types = type.types;
53058                 var filtered = ts.filter(types, f);
53059                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
53060             }
53061             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
53062         }
53063         function countTypes(type) {
53064             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
53065         }
53066         function mapType(type, mapper, noReductions) {
53067             if (type.flags & 131072 /* Never */) {
53068                 return type;
53069             }
53070             if (!(type.flags & 1048576 /* Union */)) {
53071                 return mapper(type);
53072             }
53073             var mappedTypes;
53074             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
53075                 var t = _a[_i];
53076                 var mapped = mapper(t);
53077                 if (mapped) {
53078                     if (!mappedTypes) {
53079                         mappedTypes = [mapped];
53080                     }
53081                     else {
53082                         mappedTypes.push(mapped);
53083                     }
53084                 }
53085             }
53086             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
53087         }
53088         function extractTypesOfKind(type, kind) {
53089             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
53090         }
53091         // Return a new type in which occurrences of the string and number primitive types in
53092         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
53093         // literals in typeWithLiterals, respectively.
53094         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
53095             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
53096                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
53097                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
53098                 return mapType(typeWithPrimitives, function (t) {
53099                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
53100                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
53101                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
53102                 });
53103             }
53104             return typeWithPrimitives;
53105         }
53106         function isIncomplete(flowType) {
53107             return flowType.flags === 0;
53108         }
53109         function getTypeFromFlowType(flowType) {
53110             return flowType.flags === 0 ? flowType.type : flowType;
53111         }
53112         function createFlowType(type, incomplete) {
53113             return incomplete ? { flags: 0, type: type } : type;
53114         }
53115         // An evolving array type tracks the element types that have so far been seen in an
53116         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
53117         // array types are ultimately converted into manifest array types (using getFinalArrayType)
53118         // and never escape the getFlowTypeOfReference function.
53119         function createEvolvingArrayType(elementType) {
53120             var result = createObjectType(256 /* EvolvingArray */);
53121             result.elementType = elementType;
53122             return result;
53123         }
53124         function getEvolvingArrayType(elementType) {
53125             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
53126         }
53127         // When adding evolving array element types we do not perform subtype reduction. Instead,
53128         // we defer subtype reduction until the evolving array type is finalized into a manifest
53129         // array type.
53130         function addEvolvingArrayElementType(evolvingArrayType, node) {
53131             var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
53132             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
53133         }
53134         function createFinalArrayType(elementType) {
53135             return elementType.flags & 131072 /* Never */ ?
53136                 autoArrayType :
53137                 createArrayType(elementType.flags & 1048576 /* Union */ ?
53138                     getUnionType(elementType.types, 2 /* Subtype */) :
53139                     elementType);
53140         }
53141         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
53142         function getFinalArrayType(evolvingArrayType) {
53143             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
53144         }
53145         function finalizeEvolvingArrayType(type) {
53146             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
53147         }
53148         function getElementTypeOfEvolvingArrayType(type) {
53149             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
53150         }
53151         function isEvolvingArrayTypeList(types) {
53152             var hasEvolvingArrayType = false;
53153             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
53154                 var t = types_16[_i];
53155                 if (!(t.flags & 131072 /* Never */)) {
53156                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
53157                         return false;
53158                     }
53159                     hasEvolvingArrayType = true;
53160                 }
53161             }
53162             return hasEvolvingArrayType;
53163         }
53164         // At flow control branch or loop junctions, if the type along every antecedent code path
53165         // is an evolving array type, we construct a combined evolving array type. Otherwise we
53166         // finalize all evolving array types.
53167         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
53168             return isEvolvingArrayTypeList(types) ?
53169                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
53170                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
53171         }
53172         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
53173         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
53174         function isEvolvingArrayOperationTarget(node) {
53175             var root = getReferenceRoot(node);
53176             var parent = root.parent;
53177             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
53178                 parent.parent.kind === 196 /* CallExpression */
53179                     && ts.isIdentifier(parent.name)
53180                     && ts.isPushOrUnshiftIdentifier(parent.name));
53181             var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
53182                 parent.expression === root &&
53183                 parent.parent.kind === 209 /* BinaryExpression */ &&
53184                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
53185                 parent.parent.left === parent &&
53186                 !ts.isAssignmentTarget(parent.parent) &&
53187                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
53188             return isLengthPushOrUnshift || isElementAssignment;
53189         }
53190         function isDeclarationWithExplicitTypeAnnotation(declaration) {
53191             return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
53192                 declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
53193                 !!ts.getEffectiveTypeAnnotationNode(declaration);
53194         }
53195         function getExplicitTypeOfSymbol(symbol, diagnostic) {
53196             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
53197                 return getTypeOfSymbol(symbol);
53198             }
53199             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
53200                 var declaration = symbol.valueDeclaration;
53201                 if (declaration) {
53202                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
53203                         return getTypeOfSymbol(symbol);
53204                     }
53205                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
53206                         var statement = declaration.parent.parent;
53207                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
53208                         if (expressionType) {
53209                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
53210                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
53211                         }
53212                     }
53213                     if (diagnostic) {
53214                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
53215                     }
53216                 }
53217             }
53218         }
53219         // We require the dotted function name in an assertion expression to be comprised of identifiers
53220         // that reference function, method, class or value module symbols; or variable, property or
53221         // parameter symbols with declarations that have explicit type annotations. Such references are
53222         // resolvable with no possibility of triggering circularities in control flow analysis.
53223         function getTypeOfDottedName(node, diagnostic) {
53224             if (!(node.flags & 16777216 /* InWithStatement */)) {
53225                 switch (node.kind) {
53226                     case 75 /* Identifier */:
53227                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
53228                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
53229                     case 104 /* ThisKeyword */:
53230                         return getExplicitThisType(node);
53231                     case 102 /* SuperKeyword */:
53232                         return checkSuperExpression(node);
53233                     case 194 /* PropertyAccessExpression */:
53234                         var type = getTypeOfDottedName(node.expression, diagnostic);
53235                         var prop = type && getPropertyOfType(type, node.name.escapedText);
53236                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
53237                     case 200 /* ParenthesizedExpression */:
53238                         return getTypeOfDottedName(node.expression, diagnostic);
53239                 }
53240             }
53241         }
53242         function getEffectsSignature(node) {
53243             var links = getNodeLinks(node);
53244             var signature = links.effectsSignature;
53245             if (signature === undefined) {
53246                 // A call expression parented by an expression statement is a potential assertion. Other call
53247                 // expressions are potential type predicate function calls. In order to avoid triggering
53248                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
53249                 // target expression of an assertion.
53250                 var funcType = void 0;
53251                 if (node.parent.kind === 226 /* ExpressionStatement */) {
53252                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
53253                 }
53254                 else if (node.expression.kind !== 102 /* SuperKeyword */) {
53255                     if (ts.isOptionalChain(node)) {
53256                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
53257                     }
53258                     else {
53259                         funcType = checkNonNullExpression(node.expression);
53260                     }
53261                 }
53262                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
53263                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
53264                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
53265                         undefined;
53266                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
53267             }
53268             return signature === unknownSignature ? undefined : signature;
53269         }
53270         function hasTypePredicateOrNeverReturnType(signature) {
53271             return !!(getTypePredicateOfSignature(signature) ||
53272                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
53273         }
53274         function getTypePredicateArgument(predicate, callExpression) {
53275             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
53276                 return callExpression.arguments[predicate.parameterIndex];
53277             }
53278             var invokedExpression = ts.skipParentheses(callExpression.expression);
53279             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
53280         }
53281         function reportFlowControlError(node) {
53282             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
53283             var sourceFile = ts.getSourceFileOfNode(node);
53284             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
53285             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
53286         }
53287         function isReachableFlowNode(flow) {
53288             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
53289             lastFlowNode = flow;
53290             lastFlowNodeReachable = result;
53291             return result;
53292         }
53293         function isFalseExpression(expr) {
53294             var node = ts.skipParentheses(expr);
53295             return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
53296                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
53297         }
53298         function isReachableFlowNodeWorker(flow, noCacheCheck) {
53299             while (true) {
53300                 if (flow === lastFlowNode) {
53301                     return lastFlowNodeReachable;
53302                 }
53303                 var flags = flow.flags;
53304                 if (flags & 4096 /* Shared */) {
53305                     if (!noCacheCheck) {
53306                         var id = getFlowNodeId(flow);
53307                         var reachable = flowNodeReachable[id];
53308                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
53309                     }
53310                     noCacheCheck = false;
53311                 }
53312                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
53313                     flow = flow.antecedent;
53314                 }
53315                 else if (flags & 512 /* Call */) {
53316                     var signature = getEffectsSignature(flow.node);
53317                     if (signature) {
53318                         var predicate = getTypePredicateOfSignature(signature);
53319                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
53320                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
53321                             if (predicateArgument && isFalseExpression(predicateArgument)) {
53322                                 return false;
53323                             }
53324                         }
53325                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53326                             return false;
53327                         }
53328                     }
53329                     flow = flow.antecedent;
53330                 }
53331                 else if (flags & 4 /* BranchLabel */) {
53332                     // A branching point is reachable if any branch is reachable.
53333                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
53334                 }
53335                 else if (flags & 8 /* LoopLabel */) {
53336                     // A loop is reachable if the control flow path that leads to the top is reachable.
53337                     flow = flow.antecedents[0];
53338                 }
53339                 else if (flags & 128 /* SwitchClause */) {
53340                     // The control flow path representing an unmatched value in a switch statement with
53341                     // no default clause is unreachable if the switch statement is exhaustive.
53342                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
53343                         return false;
53344                     }
53345                     flow = flow.antecedent;
53346                 }
53347                 else if (flags & 1024 /* ReduceLabel */) {
53348                     // Cache is unreliable once we start adjusting labels
53349                     lastFlowNode = undefined;
53350                     var target = flow.target;
53351                     var saveAntecedents = target.antecedents;
53352                     target.antecedents = flow.antecedents;
53353                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
53354                     target.antecedents = saveAntecedents;
53355                     return result;
53356                 }
53357                 else {
53358                     return !(flags & 1 /* Unreachable */);
53359                 }
53360             }
53361         }
53362         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
53363             if (initialType === void 0) { initialType = declaredType; }
53364             var key;
53365             var keySet = false;
53366             var flowDepth = 0;
53367             if (flowAnalysisDisabled) {
53368                 return errorType;
53369             }
53370             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
53371                 return declaredType;
53372             }
53373             flowInvocationCount++;
53374             var sharedFlowStart = sharedFlowCount;
53375             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
53376             sharedFlowCount = sharedFlowStart;
53377             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
53378             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
53379             // on empty arrays are possible without implicit any errors and new element types can be inferred without
53380             // type mismatch errors.
53381             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
53382             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
53383                 return declaredType;
53384             }
53385             return resultType;
53386             function getOrSetCacheKey() {
53387                 if (keySet) {
53388                     return key;
53389                 }
53390                 keySet = true;
53391                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
53392             }
53393             function getTypeAtFlowNode(flow) {
53394                 if (flowDepth === 2000) {
53395                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
53396                     // and disable further control flow analysis in the containing function or module body.
53397                     flowAnalysisDisabled = true;
53398                     reportFlowControlError(reference);
53399                     return errorType;
53400                 }
53401                 flowDepth++;
53402                 while (true) {
53403                     var flags = flow.flags;
53404                     if (flags & 4096 /* Shared */) {
53405                         // We cache results of flow type resolution for shared nodes that were previously visited in
53406                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
53407                         // antecedent of more than one node.
53408                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
53409                             if (sharedFlowNodes[i] === flow) {
53410                                 flowDepth--;
53411                                 return sharedFlowTypes[i];
53412                             }
53413                         }
53414                     }
53415                     var type = void 0;
53416                     if (flags & 16 /* Assignment */) {
53417                         type = getTypeAtFlowAssignment(flow);
53418                         if (!type) {
53419                             flow = flow.antecedent;
53420                             continue;
53421                         }
53422                     }
53423                     else if (flags & 512 /* Call */) {
53424                         type = getTypeAtFlowCall(flow);
53425                         if (!type) {
53426                             flow = flow.antecedent;
53427                             continue;
53428                         }
53429                     }
53430                     else if (flags & 96 /* Condition */) {
53431                         type = getTypeAtFlowCondition(flow);
53432                     }
53433                     else if (flags & 128 /* SwitchClause */) {
53434                         type = getTypeAtSwitchClause(flow);
53435                     }
53436                     else if (flags & 12 /* Label */) {
53437                         if (flow.antecedents.length === 1) {
53438                             flow = flow.antecedents[0];
53439                             continue;
53440                         }
53441                         type = flags & 4 /* BranchLabel */ ?
53442                             getTypeAtFlowBranchLabel(flow) :
53443                             getTypeAtFlowLoopLabel(flow);
53444                     }
53445                     else if (flags & 256 /* ArrayMutation */) {
53446                         type = getTypeAtFlowArrayMutation(flow);
53447                         if (!type) {
53448                             flow = flow.antecedent;
53449                             continue;
53450                         }
53451                     }
53452                     else if (flags & 1024 /* ReduceLabel */) {
53453                         var target = flow.target;
53454                         var saveAntecedents = target.antecedents;
53455                         target.antecedents = flow.antecedents;
53456                         type = getTypeAtFlowNode(flow.antecedent);
53457                         target.antecedents = saveAntecedents;
53458                     }
53459                     else if (flags & 2 /* Start */) {
53460                         // Check if we should continue with the control flow of the containing function.
53461                         var container = flow.node;
53462                         if (container && container !== flowContainer &&
53463                             reference.kind !== 194 /* PropertyAccessExpression */ &&
53464                             reference.kind !== 195 /* ElementAccessExpression */ &&
53465                             reference.kind !== 104 /* ThisKeyword */) {
53466                             flow = container.flowNode;
53467                             continue;
53468                         }
53469                         // At the top of the flow we have the initial type.
53470                         type = initialType;
53471                     }
53472                     else {
53473                         // Unreachable code errors are reported in the binding phase. Here we
53474                         // simply return the non-auto declared type to reduce follow-on errors.
53475                         type = convertAutoToAny(declaredType);
53476                     }
53477                     if (flags & 4096 /* Shared */) {
53478                         // Record visited node and the associated type in the cache.
53479                         sharedFlowNodes[sharedFlowCount] = flow;
53480                         sharedFlowTypes[sharedFlowCount] = type;
53481                         sharedFlowCount++;
53482                     }
53483                     flowDepth--;
53484                     return type;
53485                 }
53486             }
53487             function getInitialOrAssignedType(flow) {
53488                 var node = flow.node;
53489                 return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
53490                     getInitialType(node) :
53491                     getAssignedType(node), reference);
53492             }
53493             function getTypeAtFlowAssignment(flow) {
53494                 var node = flow.node;
53495                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
53496                 // only need to evaluate the assigned type if the declared type is a union type.
53497                 if (isMatchingReference(reference, node)) {
53498                     if (!isReachableFlowNode(flow)) {
53499                         return unreachableNeverType;
53500                     }
53501                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
53502                         var flowType = getTypeAtFlowNode(flow.antecedent);
53503                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
53504                     }
53505                     if (declaredType === autoType || declaredType === autoArrayType) {
53506                         if (isEmptyArrayAssignment(node)) {
53507                             return getEvolvingArrayType(neverType);
53508                         }
53509                         var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
53510                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
53511                     }
53512                     if (declaredType.flags & 1048576 /* Union */) {
53513                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
53514                     }
53515                     return declaredType;
53516                 }
53517                 // We didn't have a direct match. However, if the reference is a dotted name, this
53518                 // may be an assignment to a left hand part of the reference. For example, for a
53519                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
53520                 // return the declared type.
53521                 if (containsMatchingReference(reference, node)) {
53522                     if (!isReachableFlowNode(flow)) {
53523                         return unreachableNeverType;
53524                     }
53525                     // A matching dotted name might also be an expando property on a function *expression*,
53526                     // in which case we continue control flow analysis back to the function's declaration
53527                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
53528                         var init = ts.getDeclaredExpandoInitializer(node);
53529                         if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
53530                             return getTypeAtFlowNode(flow.antecedent);
53531                         }
53532                     }
53533                     return declaredType;
53534                 }
53535                 // for (const _ in ref) acts as a nonnull on ref
53536                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
53537                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
53538                 }
53539                 // Assignment doesn't affect reference
53540                 return undefined;
53541             }
53542             function narrowTypeByAssertion(type, expr) {
53543                 var node = ts.skipParentheses(expr);
53544                 if (node.kind === 91 /* FalseKeyword */) {
53545                     return unreachableNeverType;
53546                 }
53547                 if (node.kind === 209 /* BinaryExpression */) {
53548                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
53549                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
53550                     }
53551                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
53552                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
53553                     }
53554                 }
53555                 return narrowType(type, node, /*assumeTrue*/ true);
53556             }
53557             function getTypeAtFlowCall(flow) {
53558                 var signature = getEffectsSignature(flow.node);
53559                 if (signature) {
53560                     var predicate = getTypePredicateOfSignature(signature);
53561                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
53562                         var flowType = getTypeAtFlowNode(flow.antecedent);
53563                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
53564                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
53565                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
53566                                 type;
53567                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
53568                     }
53569                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53570                         return unreachableNeverType;
53571                     }
53572                 }
53573                 return undefined;
53574             }
53575             function getTypeAtFlowArrayMutation(flow) {
53576                 if (declaredType === autoType || declaredType === autoArrayType) {
53577                     var node = flow.node;
53578                     var expr = node.kind === 196 /* CallExpression */ ?
53579                         node.expression.expression :
53580                         node.left.expression;
53581                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
53582                         var flowType = getTypeAtFlowNode(flow.antecedent);
53583                         var type = getTypeFromFlowType(flowType);
53584                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
53585                             var evolvedType_1 = type;
53586                             if (node.kind === 196 /* CallExpression */) {
53587                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
53588                                     var arg = _a[_i];
53589                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
53590                                 }
53591                             }
53592                             else {
53593                                 // 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)
53594                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
53595                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53596                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
53597                                 }
53598                             }
53599                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
53600                         }
53601                         return flowType;
53602                     }
53603                 }
53604                 return undefined;
53605             }
53606             function getTypeAtFlowCondition(flow) {
53607                 var flowType = getTypeAtFlowNode(flow.antecedent);
53608                 var type = getTypeFromFlowType(flowType);
53609                 if (type.flags & 131072 /* Never */) {
53610                     return flowType;
53611                 }
53612                 // If we have an antecedent type (meaning we're reachable in some way), we first
53613                 // attempt to narrow the antecedent type. If that produces the never type, and if
53614                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
53615                 // take the type guard as an indication that control *could* reach here once we
53616                 // have the complete type. We proceed by switching to the silent never type which
53617                 // doesn't report errors when operators are applied to it. Note that this is the
53618                 // *only* place a silent never type is ever generated.
53619                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
53620                 var nonEvolvingType = finalizeEvolvingArrayType(type);
53621                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
53622                 if (narrowedType === nonEvolvingType) {
53623                     return flowType;
53624                 }
53625                 var incomplete = isIncomplete(flowType);
53626                 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
53627                 return createFlowType(resultType, incomplete);
53628             }
53629             function getTypeAtSwitchClause(flow) {
53630                 var expr = flow.switchStatement.expression;
53631                 var flowType = getTypeAtFlowNode(flow.antecedent);
53632                 var type = getTypeFromFlowType(flowType);
53633                 if (isMatchingReference(reference, expr)) {
53634                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53635                 }
53636                 else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
53637                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53638                 }
53639                 else {
53640                     if (strictNullChecks) {
53641                         if (optionalChainContainsReference(expr, reference)) {
53642                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
53643                         }
53644                         else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
53645                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
53646                         }
53647                     }
53648                     if (isMatchingReferenceDiscriminant(expr, type)) {
53649                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
53650                     }
53651                 }
53652                 return createFlowType(type, isIncomplete(flowType));
53653             }
53654             function getTypeAtFlowBranchLabel(flow) {
53655                 var antecedentTypes = [];
53656                 var subtypeReduction = false;
53657                 var seenIncomplete = false;
53658                 var bypassFlow;
53659                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53660                     var antecedent = _a[_i];
53661                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
53662                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
53663                         bypassFlow = antecedent;
53664                         continue;
53665                     }
53666                     var flowType = getTypeAtFlowNode(antecedent);
53667                     var type = getTypeFromFlowType(flowType);
53668                     // If the type at a particular antecedent path is the declared type and the
53669                     // reference is known to always be assigned (i.e. when declared and initial types
53670                     // are the same), there is no reason to process more antecedents since the only
53671                     // possible outcome is subtypes that will be removed in the final union type anyway.
53672                     if (type === declaredType && declaredType === initialType) {
53673                         return type;
53674                     }
53675                     ts.pushIfUnique(antecedentTypes, type);
53676                     // If an antecedent type is not a subset of the declared type, we need to perform
53677                     // subtype reduction. This happens when a "foreign" type is injected into the control
53678                     // flow using the instanceof operator or a user defined type predicate.
53679                     if (!isTypeSubsetOf(type, declaredType)) {
53680                         subtypeReduction = true;
53681                     }
53682                     if (isIncomplete(flowType)) {
53683                         seenIncomplete = true;
53684                     }
53685                 }
53686                 if (bypassFlow) {
53687                     var flowType = getTypeAtFlowNode(bypassFlow);
53688                     var type = getTypeFromFlowType(flowType);
53689                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
53690                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
53691                     // the risk of circularities, we only want to perform them when they make a difference.
53692                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
53693                         if (type === declaredType && declaredType === initialType) {
53694                             return type;
53695                         }
53696                         antecedentTypes.push(type);
53697                         if (!isTypeSubsetOf(type, declaredType)) {
53698                             subtypeReduction = true;
53699                         }
53700                         if (isIncomplete(flowType)) {
53701                             seenIncomplete = true;
53702                         }
53703                     }
53704                 }
53705                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
53706             }
53707             function getTypeAtFlowLoopLabel(flow) {
53708                 // If we have previously computed the control flow type for the reference at
53709                 // this flow loop junction, return the cached type.
53710                 var id = getFlowNodeId(flow);
53711                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
53712                 var key = getOrSetCacheKey();
53713                 if (!key) {
53714                     // No cache key is generated when binding patterns are in unnarrowable situations
53715                     return declaredType;
53716                 }
53717                 var cached = cache.get(key);
53718                 if (cached) {
53719                     return cached;
53720                 }
53721                 // If this flow loop junction and reference are already being processed, return
53722                 // the union of the types computed for each branch so far, marked as incomplete.
53723                 // It is possible to see an empty array in cases where loops are nested and the
53724                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
53725                 // In such cases we restart the analysis of the inner loop, which will then see
53726                 // a non-empty in-process array for the outer loop and eventually terminate because
53727                 // the first antecedent of a loop junction is always the non-looping control flow
53728                 // path that leads to the top.
53729                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
53730                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
53731                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
53732                     }
53733                 }
53734                 // Add the flow loop junction and reference to the in-process stack and analyze
53735                 // each antecedent code path.
53736                 var antecedentTypes = [];
53737                 var subtypeReduction = false;
53738                 var firstAntecedentType;
53739                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53740                     var antecedent = _a[_i];
53741                     var flowType = void 0;
53742                     if (!firstAntecedentType) {
53743                         // The first antecedent of a loop junction is always the non-looping control
53744                         // flow path that leads to the top.
53745                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
53746                     }
53747                     else {
53748                         // All but the first antecedent are the looping control flow paths that lead
53749                         // back to the loop junction. We track these on the flow loop stack.
53750                         flowLoopNodes[flowLoopCount] = flow;
53751                         flowLoopKeys[flowLoopCount] = key;
53752                         flowLoopTypes[flowLoopCount] = antecedentTypes;
53753                         flowLoopCount++;
53754                         var saveFlowTypeCache = flowTypeCache;
53755                         flowTypeCache = undefined;
53756                         flowType = getTypeAtFlowNode(antecedent);
53757                         flowTypeCache = saveFlowTypeCache;
53758                         flowLoopCount--;
53759                         // If we see a value appear in the cache it is a sign that control flow analysis
53760                         // was restarted and completed by checkExpressionCached. We can simply pick up
53761                         // the resulting type and bail out.
53762                         var cached_1 = cache.get(key);
53763                         if (cached_1) {
53764                             return cached_1;
53765                         }
53766                     }
53767                     var type = getTypeFromFlowType(flowType);
53768                     ts.pushIfUnique(antecedentTypes, type);
53769                     // If an antecedent type is not a subset of the declared type, we need to perform
53770                     // subtype reduction. This happens when a "foreign" type is injected into the control
53771                     // flow using the instanceof operator or a user defined type predicate.
53772                     if (!isTypeSubsetOf(type, declaredType)) {
53773                         subtypeReduction = true;
53774                     }
53775                     // If the type at a particular antecedent path is the declared type there is no
53776                     // reason to process more antecedents since the only possible outcome is subtypes
53777                     // that will be removed in the final union type anyway.
53778                     if (type === declaredType) {
53779                         break;
53780                     }
53781                 }
53782                 // The result is incomplete if the first antecedent (the non-looping control flow path)
53783                 // is incomplete.
53784                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
53785                 if (isIncomplete(firstAntecedentType)) {
53786                     return createFlowType(result, /*incomplete*/ true);
53787                 }
53788                 cache.set(key, result);
53789                 return result;
53790             }
53791             function isMatchingReferenceDiscriminant(expr, computedType) {
53792                 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
53793                     return false;
53794                 }
53795                 var name = getAccessedPropertyName(expr);
53796                 if (name === undefined) {
53797                     return false;
53798                 }
53799                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
53800             }
53801             function narrowTypeByDiscriminant(type, access, narrowType) {
53802                 var propName = getAccessedPropertyName(access);
53803                 if (propName === undefined) {
53804                     return type;
53805                 }
53806                 var propType = getTypeOfPropertyOfType(type, propName);
53807                 if (!propType) {
53808                     return type;
53809                 }
53810                 var narrowedPropType = narrowType(propType);
53811                 return filterType(type, function (t) {
53812                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
53813                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
53814                 });
53815             }
53816             function narrowTypeByTruthiness(type, expr, assumeTrue) {
53817                 if (isMatchingReference(reference, expr)) {
53818                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
53819                 }
53820                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
53821                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53822                 }
53823                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
53824                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
53825                 }
53826                 return type;
53827             }
53828             function isTypePresencePossible(type, propName, assumeTrue) {
53829                 if (getIndexInfoOfType(type, 0 /* String */)) {
53830                     return true;
53831                 }
53832                 var prop = getPropertyOfType(type, propName);
53833                 if (prop) {
53834                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
53835                 }
53836                 return !assumeTrue;
53837             }
53838             function narrowByInKeyword(type, literal, assumeTrue) {
53839                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
53840                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
53841                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
53842                 }
53843                 return type;
53844             }
53845             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
53846                 switch (expr.operatorToken.kind) {
53847                     case 62 /* EqualsToken */:
53848                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
53849                     case 34 /* EqualsEqualsToken */:
53850                     case 35 /* ExclamationEqualsToken */:
53851                     case 36 /* EqualsEqualsEqualsToken */:
53852                     case 37 /* ExclamationEqualsEqualsToken */:
53853                         var operator_1 = expr.operatorToken.kind;
53854                         var left_1 = getReferenceCandidate(expr.left);
53855                         var right_1 = getReferenceCandidate(expr.right);
53856                         if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
53857                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
53858                         }
53859                         if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
53860                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
53861                         }
53862                         if (isMatchingReference(reference, left_1)) {
53863                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
53864                         }
53865                         if (isMatchingReference(reference, right_1)) {
53866                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
53867                         }
53868                         if (strictNullChecks) {
53869                             if (optionalChainContainsReference(left_1, reference)) {
53870                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
53871                             }
53872                             else if (optionalChainContainsReference(right_1, reference)) {
53873                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
53874                             }
53875                         }
53876                         if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
53877                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
53878                         }
53879                         if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
53880                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
53881                         }
53882                         if (isMatchingConstructorReference(left_1)) {
53883                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
53884                         }
53885                         if (isMatchingConstructorReference(right_1)) {
53886                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
53887                         }
53888                         break;
53889                     case 98 /* InstanceOfKeyword */:
53890                         return narrowTypeByInstanceof(type, expr, assumeTrue);
53891                     case 97 /* InKeyword */:
53892                         var target = getReferenceCandidate(expr.right);
53893                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
53894                             return narrowByInKeyword(type, expr.left, assumeTrue);
53895                         }
53896                         break;
53897                     case 27 /* CommaToken */:
53898                         return narrowType(type, expr.right, assumeTrue);
53899                 }
53900                 return type;
53901             }
53902             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
53903                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
53904                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
53905                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
53906                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
53907                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
53908                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
53909                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
53910                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
53911                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
53912                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
53913                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
53914                 var valueType = getTypeOfExpression(value);
53915                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
53916                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
53917                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
53918                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53919             }
53920             function narrowTypeByEquality(type, operator, value, assumeTrue) {
53921                 if (type.flags & 1 /* Any */) {
53922                     return type;
53923                 }
53924                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53925                     assumeTrue = !assumeTrue;
53926                 }
53927                 var valueType = getTypeOfExpression(value);
53928                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
53929                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53930                         return valueType;
53931                     }
53932                     if (valueType.flags & 524288 /* Object */) {
53933                         return nonPrimitiveType;
53934                     }
53935                     return type;
53936                 }
53937                 if (valueType.flags & 98304 /* Nullable */) {
53938                     if (!strictNullChecks) {
53939                         return type;
53940                     }
53941                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
53942                     var facts = doubleEquals ?
53943                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
53944                         valueType.flags & 65536 /* Null */ ?
53945                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
53946                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
53947                     return getTypeWithFacts(type, facts);
53948                 }
53949                 if (type.flags & 67637251 /* NotUnionOrUnit */) {
53950                     return type;
53951                 }
53952                 if (assumeTrue) {
53953                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
53954                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
53955                         function (t) { return areTypesComparable(t, valueType); };
53956                     var narrowedType = filterType(type, filterFn);
53957                     return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
53958                 }
53959                 if (isUnitType(valueType)) {
53960                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
53961                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
53962                 }
53963                 return type;
53964             }
53965             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
53966                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
53967                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53968                     assumeTrue = !assumeTrue;
53969                 }
53970                 var target = getReferenceCandidate(typeOfExpr.expression);
53971                 if (!isMatchingReference(reference, target)) {
53972                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
53973                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53974                     }
53975                     return type;
53976                 }
53977                 if (type.flags & 1 /* Any */ && literal.text === "function") {
53978                     return type;
53979                 }
53980                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
53981                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
53982                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
53983                     if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) {
53984                         var expr = typeOfExpr.parent.parent;
53985                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
53986                             return nonPrimitiveType;
53987                         }
53988                     }
53989                     return getUnionType([nonPrimitiveType, nullType]);
53990                 }
53991                 var facts = assumeTrue ?
53992                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
53993                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
53994                 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
53995                 function narrowTypeForTypeof(type) {
53996                     // We narrow a non-union type to an exact primitive type if the non-union type
53997                     // is a supertype of that primitive type. For example, type 'any' can be narrowed
53998                     // to one of the primitive types.
53999                     var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
54000                     if (targetType) {
54001                         if (isTypeSubtypeOf(type, targetType)) {
54002                             return type;
54003                         }
54004                         if (isTypeSubtypeOf(targetType, type)) {
54005                             return targetType;
54006                         }
54007                         if (type.flags & 63176704 /* Instantiable */) {
54008                             var constraint = getBaseConstraintOfType(type) || anyType;
54009                             if (isTypeSubtypeOf(targetType, constraint)) {
54010                                 return getIntersectionType([type, targetType]);
54011                             }
54012                         }
54013                     }
54014                     return type;
54015                 }
54016             }
54017             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
54018                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
54019                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
54020             }
54021             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
54022                 // We only narrow if all case expressions specify
54023                 // values with unit types, except for the case where
54024                 // `type` is unknown. In this instance we map object
54025                 // types to the nonPrimitive type and narrow with that.
54026                 var switchTypes = getSwitchClauseTypes(switchStatement);
54027                 if (!switchTypes.length) {
54028                     return type;
54029                 }
54030                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
54031                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
54032                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
54033                     var groundClauseTypes = void 0;
54034                     for (var i = 0; i < clauseTypes.length; i += 1) {
54035                         var t = clauseTypes[i];
54036                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
54037                             if (groundClauseTypes !== undefined) {
54038                                 groundClauseTypes.push(t);
54039                             }
54040                         }
54041                         else if (t.flags & 524288 /* Object */) {
54042                             if (groundClauseTypes === undefined) {
54043                                 groundClauseTypes = clauseTypes.slice(0, i);
54044                             }
54045                             groundClauseTypes.push(nonPrimitiveType);
54046                         }
54047                         else {
54048                             return type;
54049                         }
54050                     }
54051                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
54052                 }
54053                 var discriminantType = getUnionType(clauseTypes);
54054                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
54055                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
54056                 if (!hasDefaultClause) {
54057                     return caseType;
54058                 }
54059                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
54060                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
54061             }
54062             function getImpliedTypeFromTypeofCase(type, text) {
54063                 switch (text) {
54064                     case "function":
54065                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
54066                     case "object":
54067                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
54068                     default:
54069                         return typeofTypesByName.get(text) || type;
54070                 }
54071             }
54072             function narrowTypeForTypeofSwitch(candidate) {
54073                 return function (type) {
54074                     if (isTypeSubtypeOf(candidate, type)) {
54075                         return candidate;
54076                     }
54077                     if (type.flags & 63176704 /* Instantiable */) {
54078                         var constraint = getBaseConstraintOfType(type) || anyType;
54079                         if (isTypeSubtypeOf(candidate, constraint)) {
54080                             return getIntersectionType([type, candidate]);
54081                         }
54082                     }
54083                     return type;
54084                 };
54085             }
54086             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
54087                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
54088                 if (!switchWitnesses.length) {
54089                     return type;
54090                 }
54091                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
54092                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
54093                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
54094                 var clauseWitnesses;
54095                 var switchFacts;
54096                 if (defaultCaseLocation > -1) {
54097                     // We no longer need the undefined denoting an
54098                     // explicit default case. Remove the undefined and
54099                     // fix-up clauseStart and clauseEnd.  This means
54100                     // that we don't have to worry about undefined
54101                     // in the witness array.
54102                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
54103                     // The adjusted clause start and end after removing the `default` statement.
54104                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
54105                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
54106                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
54107                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
54108                 }
54109                 else {
54110                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
54111                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
54112                 }
54113                 if (hasDefaultClause) {
54114                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
54115                 }
54116                 /*
54117                   The implied type is the raw type suggested by a
54118                   value being caught in this clause.
54119
54120                   When the clause contains a default case we ignore
54121                   the implied type and try to narrow using any facts
54122                   we can learn: see `switchFacts`.
54123
54124                   Example:
54125                   switch (typeof x) {
54126                       case 'number':
54127                       case 'string': break;
54128                       default: break;
54129                       case 'number':
54130                       case 'boolean': break
54131                   }
54132
54133                   In the first clause (case `number` and `string`) the
54134                   implied type is number | string.
54135
54136                   In the default clause we de not compute an implied type.
54137
54138                   In the third clause (case `number` and `boolean`)
54139                   the naive implied type is number | boolean, however
54140                   we use the type facts to narrow the implied type to
54141                   boolean. We know that number cannot be selected
54142                   because it is caught in the first clause.
54143                 */
54144                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
54145                 if (impliedType.flags & 1048576 /* Union */) {
54146                     impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
54147                 }
54148                 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
54149             }
54150             function isMatchingConstructorReference(expr) {
54151                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
54152                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
54153                     isMatchingReference(reference, expr.expression);
54154             }
54155             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
54156                 // Do not narrow when checking inequality.
54157                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
54158                     return type;
54159                 }
54160                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
54161                 var identifierType = getTypeOfExpression(identifier);
54162                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
54163                     return type;
54164                 }
54165                 // Get the prototype property of the type identifier so we can find out its type.
54166                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
54167                 if (!prototypeProperty) {
54168                     return type;
54169                 }
54170                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
54171                 var prototypeType = getTypeOfSymbol(prototypeProperty);
54172                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
54173                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
54174                     return type;
54175                 }
54176                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
54177                 if (isTypeAny(type)) {
54178                     return candidate;
54179                 }
54180                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
54181                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
54182                 function isConstructedBy(source, target) {
54183                     // If either the source or target type are a class type then we need to check that they are the same exact type.
54184                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
54185                     // that defines the same set of properties as class `A`, in that case they are structurally the same
54186                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
54187                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
54188                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
54189                         return source.symbol === target.symbol;
54190                     }
54191                     // For all other types just check that the `source` type is a subtype of the `target` type.
54192                     return isTypeSubtypeOf(source, target);
54193                 }
54194             }
54195             function narrowTypeByInstanceof(type, expr, assumeTrue) {
54196                 var left = getReferenceCandidate(expr.left);
54197                 if (!isMatchingReference(reference, left)) {
54198                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
54199                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54200                     }
54201                     return type;
54202                 }
54203                 // Check that right operand is a function type with a prototype property
54204                 var rightType = getTypeOfExpression(expr.right);
54205                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
54206                     return type;
54207                 }
54208                 var targetType;
54209                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
54210                 if (prototypeProperty) {
54211                     // Target type is type of the prototype property
54212                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
54213                     if (!isTypeAny(prototypePropertyType)) {
54214                         targetType = prototypePropertyType;
54215                     }
54216                 }
54217                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
54218                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
54219                     return type;
54220                 }
54221                 if (!targetType) {
54222                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
54223                     targetType = constructSignatures.length ?
54224                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
54225                         emptyObjectType;
54226                 }
54227                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
54228             }
54229             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
54230                 if (!assumeTrue) {
54231                     return filterType(type, function (t) { return !isRelated(t, candidate); });
54232                 }
54233                 // If the current type is a union type, remove all constituents that couldn't be instances of
54234                 // the candidate type. If one or more constituents remain, return a union of those.
54235                 if (type.flags & 1048576 /* Union */) {
54236                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
54237                     if (!(assignableType.flags & 131072 /* Never */)) {
54238                         return assignableType;
54239                     }
54240                 }
54241                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
54242                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
54243                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
54244                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
54245                 // two types.
54246                 return isTypeSubtypeOf(candidate, type) ? candidate :
54247                     isTypeAssignableTo(type, candidate) ? type :
54248                         isTypeAssignableTo(candidate, type) ? candidate :
54249                             getIntersectionType([type, candidate]);
54250             }
54251             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
54252                 if (hasMatchingArgument(callExpression, reference)) {
54253                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
54254                     var predicate = signature && getTypePredicateOfSignature(signature);
54255                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
54256                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
54257                     }
54258                 }
54259                 return type;
54260             }
54261             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
54262                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
54263                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
54264                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
54265                     if (predicateArgument) {
54266                         if (isMatchingReference(reference, predicateArgument)) {
54267                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
54268                         }
54269                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
54270                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
54271                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54272                         }
54273                         if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) {
54274                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
54275                         }
54276                     }
54277                 }
54278                 return type;
54279             }
54280             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
54281             // will be a subtype or the same type as the argument.
54282             function narrowType(type, expr, assumeTrue) {
54283                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
54284                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
54285                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
54286                     return narrowTypeByOptionality(type, expr, assumeTrue);
54287                 }
54288                 switch (expr.kind) {
54289                     case 75 /* Identifier */:
54290                     case 104 /* ThisKeyword */:
54291                     case 102 /* SuperKeyword */:
54292                     case 194 /* PropertyAccessExpression */:
54293                     case 195 /* ElementAccessExpression */:
54294                         return narrowTypeByTruthiness(type, expr, assumeTrue);
54295                     case 196 /* CallExpression */:
54296                         return narrowTypeByCallExpression(type, expr, assumeTrue);
54297                     case 200 /* ParenthesizedExpression */:
54298                         return narrowType(type, expr.expression, assumeTrue);
54299                     case 209 /* BinaryExpression */:
54300                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
54301                     case 207 /* PrefixUnaryExpression */:
54302                         if (expr.operator === 53 /* ExclamationToken */) {
54303                             return narrowType(type, expr.operand, !assumeTrue);
54304                         }
54305                         break;
54306                 }
54307                 return type;
54308             }
54309             function narrowTypeByOptionality(type, expr, assumePresent) {
54310                 if (isMatchingReference(reference, expr)) {
54311                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
54312                 }
54313                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
54314                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
54315                 }
54316                 return type;
54317             }
54318         }
54319         function getTypeOfSymbolAtLocation(symbol, location) {
54320             symbol = symbol.exportSymbol || symbol;
54321             // If we have an identifier or a property access at the given location, if the location is
54322             // an dotted name expression, and if the location is not an assignment target, obtain the type
54323             // of the expression (which will reflect control flow analysis). If the expression indeed
54324             // resolved to the given symbol, return the narrowed type.
54325             if (location.kind === 75 /* Identifier */) {
54326                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
54327                     location = location.parent;
54328                 }
54329                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
54330                     var type = getTypeOfExpression(location);
54331                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
54332                         return type;
54333                     }
54334                 }
54335             }
54336             // The location isn't a reference to the given symbol, meaning we're being asked
54337             // a hypothetical question of what type the symbol would have if there was a reference
54338             // to it at the given location. Since we have no control flow information for the
54339             // hypothetical reference (control flow information is created and attached by the
54340             // binder), we simply return the declared type of the symbol.
54341             return getTypeOfSymbol(symbol);
54342         }
54343         function getControlFlowContainer(node) {
54344             return ts.findAncestor(node.parent, function (node) {
54345                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
54346                     node.kind === 250 /* ModuleBlock */ ||
54347                     node.kind === 290 /* SourceFile */ ||
54348                     node.kind === 159 /* PropertyDeclaration */;
54349             });
54350         }
54351         // Check if a parameter is assigned anywhere within its declaring function.
54352         function isParameterAssigned(symbol) {
54353             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
54354             var links = getNodeLinks(func);
54355             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
54356                 links.flags |= 8388608 /* AssignmentsMarked */;
54357                 if (!hasParentWithAssignmentsMarked(func)) {
54358                     markParameterAssignments(func);
54359                 }
54360             }
54361             return symbol.isAssigned || false;
54362         }
54363         function hasParentWithAssignmentsMarked(node) {
54364             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
54365         }
54366         function markParameterAssignments(node) {
54367             if (node.kind === 75 /* Identifier */) {
54368                 if (ts.isAssignmentTarget(node)) {
54369                     var symbol = getResolvedSymbol(node);
54370                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
54371                         symbol.isAssigned = true;
54372                     }
54373                 }
54374             }
54375             else {
54376                 ts.forEachChild(node, markParameterAssignments);
54377             }
54378         }
54379         function isConstVariable(symbol) {
54380             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
54381         }
54382         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
54383         function removeOptionalityFromDeclaredType(declaredType, declaration) {
54384             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
54385                 var annotationIncludesUndefined = strictNullChecks &&
54386                     declaration.kind === 156 /* Parameter */ &&
54387                     declaration.initializer &&
54388                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
54389                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
54390                 popTypeResolution();
54391                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
54392             }
54393             else {
54394                 reportCircularityError(declaration.symbol);
54395                 return declaredType;
54396             }
54397         }
54398         function isConstraintPosition(node) {
54399             var parent = node.parent;
54400             return parent.kind === 194 /* PropertyAccessExpression */ ||
54401                 parent.kind === 196 /* CallExpression */ && parent.expression === node ||
54402                 parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
54403                 parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
54404         }
54405         function typeHasNullableConstraint(type) {
54406             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
54407         }
54408         function getConstraintForLocation(type, node) {
54409             // When a node is the left hand expression of a property access, element access, or call expression,
54410             // and the type of the node includes type variables with constraints that are nullable, we fetch the
54411             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
54412             // the constraint type.
54413             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
54414                 return mapType(getWidenedType(type), getBaseConstraintOrType);
54415             }
54416             return type;
54417         }
54418         function isExportOrExportExpression(location) {
54419             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
54420         }
54421         function markAliasReferenced(symbol, location) {
54422             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
54423                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
54424                     markAliasSymbolAsReferenced(symbol);
54425                 }
54426                 else {
54427                     markConstEnumAliasAsReferenced(symbol);
54428                 }
54429             }
54430         }
54431         function checkIdentifier(node) {
54432             var symbol = getResolvedSymbol(node);
54433             if (symbol === unknownSymbol) {
54434                 return errorType;
54435             }
54436             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
54437             // Although in down-level emit of arrow function, we emit it using function expression which means that
54438             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
54439             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
54440             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
54441             // can explicitly bound arguments objects
54442             if (symbol === argumentsSymbol) {
54443                 var container = ts.getContainingFunction(node);
54444                 if (languageVersion < 2 /* ES2015 */) {
54445                     if (container.kind === 202 /* ArrowFunction */) {
54446                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
54447                     }
54448                     else if (ts.hasModifier(container, 256 /* Async */)) {
54449                         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);
54450                     }
54451                 }
54452                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
54453                 return getTypeOfSymbol(symbol);
54454             }
54455             // We should only mark aliases as referenced if there isn't a local value declaration
54456             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
54457             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
54458                 markAliasReferenced(symbol, node);
54459             }
54460             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
54461             var declaration = localOrExportSymbol.valueDeclaration;
54462             if (localOrExportSymbol.flags & 32 /* Class */) {
54463                 // Due to the emit for class decorators, any reference to the class from inside of the class body
54464                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
54465                 // behavior of class names in ES6.
54466                 if (declaration.kind === 245 /* ClassDeclaration */
54467                     && ts.nodeIsDecorated(declaration)) {
54468                     var container = ts.getContainingClass(node);
54469                     while (container !== undefined) {
54470                         if (container === declaration && container.name !== node) {
54471                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54472                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54473                             break;
54474                         }
54475                         container = ts.getContainingClass(container);
54476                     }
54477                 }
54478                 else if (declaration.kind === 214 /* ClassExpression */) {
54479                     // When we emit a class expression with static members that contain a reference
54480                     // to the constructor in the initializer, we will need to substitute that
54481                     // binding with an alias as the class name is not in scope.
54482                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54483                     while (container.kind !== 290 /* SourceFile */) {
54484                         if (container.parent === declaration) {
54485                             if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
54486                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54487                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54488                             }
54489                             break;
54490                         }
54491                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
54492                     }
54493                 }
54494             }
54495             checkNestedBlockScopedBinding(node, symbol);
54496             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
54497             var assignmentKind = ts.getAssignmentTargetKind(node);
54498             if (assignmentKind) {
54499                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
54500                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
54501                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
54502                     return errorType;
54503                 }
54504                 if (isReadonlySymbol(localOrExportSymbol)) {
54505                     if (localOrExportSymbol.flags & 3 /* Variable */) {
54506                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
54507                     }
54508                     else {
54509                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
54510                     }
54511                     return errorType;
54512                 }
54513             }
54514             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
54515             // We only narrow variables and parameters occurring in a non-assignment position. For all other
54516             // entities we simply return the declared type.
54517             if (localOrExportSymbol.flags & 3 /* Variable */) {
54518                 if (assignmentKind === 1 /* Definite */) {
54519                     return type;
54520                 }
54521             }
54522             else if (isAlias) {
54523                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
54524             }
54525             else {
54526                 return type;
54527             }
54528             if (!declaration) {
54529                 return type;
54530             }
54531             // The declaration container is the innermost function that encloses the declaration of the variable
54532             // or parameter. The flow container is the innermost function starting with which we analyze the control
54533             // flow graph to determine the control flow based type.
54534             var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
54535             var declarationContainer = getControlFlowContainer(declaration);
54536             var flowContainer = getControlFlowContainer(node);
54537             var isOuterVariable = flowContainer !== declarationContainer;
54538             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
54539             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
54540             // When the control flow originates in a function expression or arrow function and we are referencing
54541             // a const variable or parameter from an outer function, we extend the origin of the control flow
54542             // analysis to include the immediately enclosing function.
54543             while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
54544                 flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
54545                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
54546                 flowContainer = getControlFlowContainer(flowContainer);
54547             }
54548             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
54549             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
54550             // declaration container are the same).
54551             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
54552                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
54553                     isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
54554                 node.parent.kind === 218 /* NonNullExpression */ ||
54555                 declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
54556                 declaration.flags & 8388608 /* Ambient */;
54557             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
54558                 type === autoType || type === autoArrayType ? undefinedType :
54559                     getOptionalType(type);
54560             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
54561             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
54562             // from declaration to use, and when the variable's declared type doesn't include undefined but the
54563             // control flow based type does include undefined.
54564             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
54565                 if (flowType === autoType || flowType === autoArrayType) {
54566                     if (noImplicitAny) {
54567                         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));
54568                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54569                     }
54570                     return convertAutoToAny(flowType);
54571                 }
54572             }
54573             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
54574                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
54575                 // Return the declared type to reduce follow-on errors
54576                 return type;
54577             }
54578             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
54579         }
54580         function isInsideFunction(node, threshold) {
54581             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
54582         }
54583         function getPartOfForStatementContainingNode(node, container) {
54584             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
54585         }
54586         function checkNestedBlockScopedBinding(node, symbol) {
54587             if (languageVersion >= 2 /* ES2015 */ ||
54588                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
54589                 ts.isSourceFile(symbol.valueDeclaration) ||
54590                 symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
54591                 return;
54592             }
54593             // 1. walk from the use site up to the declaration and check
54594             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
54595             // 2. walk from the declaration up to the boundary of lexical environment and check
54596             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
54597             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
54598             var usedInFunction = isInsideFunction(node.parent, container);
54599             var current = container;
54600             var containedInIterationStatement = false;
54601             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
54602                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
54603                     containedInIterationStatement = true;
54604                     break;
54605                 }
54606                 current = current.parent;
54607             }
54608             if (containedInIterationStatement) {
54609                 if (usedInFunction) {
54610                     // mark iteration statement as containing block-scoped binding captured in some function
54611                     var capturesBlockScopeBindingInLoopBody = true;
54612                     if (ts.isForStatement(container)) {
54613                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54614                         if (varDeclList && varDeclList.parent === container) {
54615                             var part = getPartOfForStatementContainingNode(node.parent, container);
54616                             if (part) {
54617                                 var links = getNodeLinks(part);
54618                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
54619                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
54620                                 ts.pushIfUnique(capturedBindings, symbol);
54621                                 if (part === container.initializer) {
54622                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
54623                                 }
54624                             }
54625                         }
54626                     }
54627                     if (capturesBlockScopeBindingInLoopBody) {
54628                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
54629                     }
54630                 }
54631                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
54632                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
54633                 if (ts.isForStatement(container)) {
54634                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54635                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
54636                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
54637                     }
54638                 }
54639                 // set 'declared inside loop' bit on the block-scoped binding
54640                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
54641             }
54642             if (usedInFunction) {
54643                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
54644             }
54645         }
54646         function isBindingCapturedByNode(node, decl) {
54647             var links = getNodeLinks(node);
54648             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
54649         }
54650         function isAssignedInBodyOfForStatement(node, container) {
54651             // skip parenthesized nodes
54652             var current = node;
54653             while (current.parent.kind === 200 /* ParenthesizedExpression */) {
54654                 current = current.parent;
54655             }
54656             // check if node is used as LHS in some assignment expression
54657             var isAssigned = false;
54658             if (ts.isAssignmentTarget(current)) {
54659                 isAssigned = true;
54660             }
54661             else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
54662                 var expr = current.parent;
54663                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
54664             }
54665             if (!isAssigned) {
54666                 return false;
54667             }
54668             // at this point we know that node is the target of assignment
54669             // now check that modification happens inside the statement part of the ForStatement
54670             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
54671         }
54672         function captureLexicalThis(node, container) {
54673             getNodeLinks(node).flags |= 2 /* LexicalThis */;
54674             if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
54675                 var classNode = container.parent;
54676                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
54677             }
54678             else {
54679                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
54680             }
54681         }
54682         function findFirstSuperCall(n) {
54683             if (ts.isSuperCall(n)) {
54684                 return n;
54685             }
54686             else if (ts.isFunctionLike(n)) {
54687                 return undefined;
54688             }
54689             return ts.forEachChild(n, findFirstSuperCall);
54690         }
54691         /**
54692          * Return a cached result if super-statement is already found.
54693          * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
54694          *
54695          * @param constructor constructor-function to look for super statement
54696          */
54697         function getSuperCallInConstructor(constructor) {
54698             var links = getNodeLinks(constructor);
54699             // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
54700             if (links.hasSuperCall === undefined) {
54701                 links.superCall = findFirstSuperCall(constructor.body);
54702                 links.hasSuperCall = links.superCall ? true : false;
54703             }
54704             return links.superCall;
54705         }
54706         /**
54707          * Check if the given class-declaration extends null then return true.
54708          * Otherwise, return false
54709          * @param classDecl a class declaration to check if it extends null
54710          */
54711         function classDeclarationExtendsNull(classDecl) {
54712             var classSymbol = getSymbolOfNode(classDecl);
54713             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
54714             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
54715             return baseConstructorType === nullWideningType;
54716         }
54717         function checkThisBeforeSuper(node, container, diagnosticMessage) {
54718             var containingClassDecl = container.parent;
54719             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
54720             // If a containing class does not have extends clause or the class extends null
54721             // skip checking whether super statement is called before "this" accessing.
54722             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
54723                 var superCall = getSuperCallInConstructor(container);
54724                 // We should give an error in the following cases:
54725                 //      - No super-call
54726                 //      - "this" is accessing before super-call.
54727                 //          i.e super(this)
54728                 //              this.x; super();
54729                 // We want to make sure that super-call is done before accessing "this" so that
54730                 // "this" is not accessed as a parameter of the super-call.
54731                 if (!superCall || superCall.end > node.pos) {
54732                     // In ES6, super inside constructor of class-declaration has to precede "this" accessing
54733                     error(node, diagnosticMessage);
54734                 }
54735             }
54736         }
54737         function checkThisExpression(node) {
54738             // Stop at the first arrow function so that we can
54739             // tell whether 'this' needs to be captured.
54740             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
54741             var capturedByArrowFunction = false;
54742             if (container.kind === 162 /* Constructor */) {
54743                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
54744             }
54745             // Now skip arrow functions to get the "real" owner of 'this'.
54746             if (container.kind === 202 /* ArrowFunction */) {
54747                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
54748                 capturedByArrowFunction = true;
54749             }
54750             switch (container.kind) {
54751                 case 249 /* ModuleDeclaration */:
54752                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
54753                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54754                     break;
54755                 case 248 /* EnumDeclaration */:
54756                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
54757                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54758                     break;
54759                 case 162 /* Constructor */:
54760                     if (isInConstructorArgumentInitializer(node, container)) {
54761                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
54762                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54763                     }
54764                     break;
54765                 case 159 /* PropertyDeclaration */:
54766                 case 158 /* PropertySignature */:
54767                     if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
54768                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
54769                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54770                     }
54771                     break;
54772                 case 154 /* ComputedPropertyName */:
54773                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
54774                     break;
54775             }
54776             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
54777             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
54778                 captureLexicalThis(node, container);
54779             }
54780             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
54781             if (noImplicitThis) {
54782                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
54783                 if (type === globalThisType_1 && capturedByArrowFunction) {
54784                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
54785                 }
54786                 else if (!type) {
54787                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
54788                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
54789                     if (!ts.isSourceFile(container)) {
54790                         var outsideThis = tryGetThisTypeAt(container);
54791                         if (outsideThis && outsideThis !== globalThisType_1) {
54792                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
54793                         }
54794                     }
54795                 }
54796             }
54797             return type || anyType;
54798         }
54799         function tryGetThisTypeAt(node, includeGlobalThis, container) {
54800             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
54801             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
54802             var isInJS = ts.isInJSFile(node);
54803             if (ts.isFunctionLike(container) &&
54804                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
54805                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
54806                 // If this is a function in a JS file, it might be a class method.
54807                 var className = getClassNameFromPrototypeMethod(container);
54808                 if (isInJS && className) {
54809                     var classSymbol = checkExpression(className).symbol;
54810                     if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
54811                         var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
54812                         if (classType) {
54813                             return getFlowTypeOfReference(node, classType);
54814                         }
54815                     }
54816                 }
54817                 // Check if it's a constructor definition, can be either a variable decl or function decl
54818                 // i.e.
54819                 //   * /** @constructor */ function [name]() { ... }
54820                 //   * /** @constructor */ var x = function() { ... }
54821                 else if (isInJS &&
54822                     (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
54823                     ts.getJSDocClassTag(container)) {
54824                     var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
54825                     return getFlowTypeOfReference(node, classType);
54826                 }
54827                 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
54828                 if (thisType) {
54829                     return getFlowTypeOfReference(node, thisType);
54830                 }
54831             }
54832             if (ts.isClassLike(container.parent)) {
54833                 var symbol = getSymbolOfNode(container.parent);
54834                 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54835                 return getFlowTypeOfReference(node, type);
54836             }
54837             if (isInJS) {
54838                 var type = getTypeForThisExpressionFromJSDoc(container);
54839                 if (type && type !== errorType) {
54840                     return getFlowTypeOfReference(node, type);
54841                 }
54842             }
54843             if (ts.isSourceFile(container)) {
54844                 // look up in the source file's locals or exports
54845                 if (container.commonJsModuleIndicator) {
54846                     var fileSymbol = getSymbolOfNode(container);
54847                     return fileSymbol && getTypeOfSymbol(fileSymbol);
54848                 }
54849                 else if (includeGlobalThis) {
54850                     return getTypeOfSymbol(globalThisSymbol);
54851                 }
54852             }
54853         }
54854         function getExplicitThisType(node) {
54855             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54856             if (ts.isFunctionLike(container)) {
54857                 var signature = getSignatureFromDeclaration(container);
54858                 if (signature.thisParameter) {
54859                     return getExplicitTypeOfSymbol(signature.thisParameter);
54860                 }
54861             }
54862             if (ts.isClassLike(container.parent)) {
54863                 var symbol = getSymbolOfNode(container.parent);
54864                 return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54865             }
54866         }
54867         function getClassNameFromPrototypeMethod(container) {
54868             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
54869             if (container.kind === 201 /* FunctionExpression */ &&
54870                 ts.isBinaryExpression(container.parent) &&
54871                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
54872                 // Get the 'x' of 'x.prototype.y = container'
54873                 return container.parent // x.prototype.y = container
54874                     .left // x.prototype.y
54875                     .expression // x.prototype
54876                     .expression; // x
54877             }
54878             // x.prototype = { method() { } }
54879             else if (container.kind === 161 /* MethodDeclaration */ &&
54880                 container.parent.kind === 193 /* ObjectLiteralExpression */ &&
54881                 ts.isBinaryExpression(container.parent.parent) &&
54882                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
54883                 return container.parent.parent.left.expression;
54884             }
54885             // x.prototype = { method: function() { } }
54886             else if (container.kind === 201 /* FunctionExpression */ &&
54887                 container.parent.kind === 281 /* PropertyAssignment */ &&
54888                 container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
54889                 ts.isBinaryExpression(container.parent.parent.parent) &&
54890                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
54891                 return container.parent.parent.parent.left.expression;
54892             }
54893             // Object.defineProperty(x, "method", { value: function() { } });
54894             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
54895             // Object.defineProperty(x, "method", { get: () => function() { }) });
54896             else if (container.kind === 201 /* FunctionExpression */ &&
54897                 ts.isPropertyAssignment(container.parent) &&
54898                 ts.isIdentifier(container.parent.name) &&
54899                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
54900                 ts.isObjectLiteralExpression(container.parent.parent) &&
54901                 ts.isCallExpression(container.parent.parent.parent) &&
54902                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
54903                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54904                 return container.parent.parent.parent.arguments[0].expression;
54905             }
54906             // Object.defineProperty(x, "method", { value() { } });
54907             // Object.defineProperty(x, "method", { set(x: () => void) {} });
54908             // Object.defineProperty(x, "method", { get() { return () => {} } });
54909             else if (ts.isMethodDeclaration(container) &&
54910                 ts.isIdentifier(container.name) &&
54911                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
54912                 ts.isObjectLiteralExpression(container.parent) &&
54913                 ts.isCallExpression(container.parent.parent) &&
54914                 container.parent.parent.arguments[2] === container.parent &&
54915                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54916                 return container.parent.parent.arguments[0].expression;
54917             }
54918         }
54919         function getTypeForThisExpressionFromJSDoc(node) {
54920             var jsdocType = ts.getJSDocType(node);
54921             if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
54922                 var jsDocFunctionType = jsdocType;
54923                 if (jsDocFunctionType.parameters.length > 0 &&
54924                     jsDocFunctionType.parameters[0].name &&
54925                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
54926                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
54927                 }
54928             }
54929             var thisTag = ts.getJSDocThisTag(node);
54930             if (thisTag && thisTag.typeExpression) {
54931                 return getTypeFromTypeNode(thisTag.typeExpression);
54932             }
54933         }
54934         function isInConstructorArgumentInitializer(node, constructorDecl) {
54935             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
54936         }
54937         function checkSuperExpression(node) {
54938             var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
54939             var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
54940             var needToCaptureLexicalThis = false;
54941             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
54942             if (!isCallExpression) {
54943                 while (container && container.kind === 202 /* ArrowFunction */) {
54944                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
54945                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
54946                 }
54947             }
54948             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
54949             var nodeCheckFlag = 0;
54950             if (!canUseSuperExpression) {
54951                 // issue more specific error if super is used in computed property name
54952                 // class A { foo() { return "1" }}
54953                 // class B {
54954                 //     [super.foo()]() {}
54955                 // }
54956                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
54957                 if (current && current.kind === 154 /* ComputedPropertyName */) {
54958                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
54959                 }
54960                 else if (isCallExpression) {
54961                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
54962                 }
54963                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
54964                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
54965                 }
54966                 else {
54967                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
54968                 }
54969                 return errorType;
54970             }
54971             if (!isCallExpression && container.kind === 162 /* Constructor */) {
54972                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
54973             }
54974             if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
54975                 nodeCheckFlag = 512 /* SuperStatic */;
54976             }
54977             else {
54978                 nodeCheckFlag = 256 /* SuperInstance */;
54979             }
54980             getNodeLinks(node).flags |= nodeCheckFlag;
54981             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
54982             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
54983             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
54984             // uses an arrow function, which is permitted to reference `super`.
54985             //
54986             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
54987             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
54988             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
54989             //
54990             // The simplest case is reading a value, in which case we will emit something like the following:
54991             //
54992             //  // ts
54993             //  ...
54994             //  async asyncMethod() {
54995             //    let x = await super.asyncMethod();
54996             //    return x;
54997             //  }
54998             //  ...
54999             //
55000             //  // js
55001             //  ...
55002             //  asyncMethod() {
55003             //      const _super = Object.create(null, {
55004             //        asyncMethod: { get: () => super.asyncMethod },
55005             //      });
55006             //      return __awaiter(this, arguments, Promise, function *() {
55007             //          let x = yield _super.asyncMethod.call(this);
55008             //          return x;
55009             //      });
55010             //  }
55011             //  ...
55012             //
55013             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
55014             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
55015             //
55016             //  // ts
55017             //  ...
55018             //  async asyncMethod(ar: Promise<any[]>) {
55019             //      [super.a, super.b] = await ar;
55020             //  }
55021             //  ...
55022             //
55023             //  // js
55024             //  ...
55025             //  asyncMethod(ar) {
55026             //      const _super = Object.create(null, {
55027             //        a: { get: () => super.a, set: (v) => super.a = v },
55028             //        b: { get: () => super.b, set: (v) => super.b = v }
55029             //      };
55030             //      return __awaiter(this, arguments, Promise, function *() {
55031             //          [_super.a, _super.b] = yield ar;
55032             //      });
55033             //  }
55034             //  ...
55035             //
55036             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
55037             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
55038             //
55039             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
55040             if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
55041                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
55042                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
55043                 }
55044                 else {
55045                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
55046                 }
55047             }
55048             if (needToCaptureLexicalThis) {
55049                 // call expressions are allowed only in constructors so they should always capture correct 'this'
55050                 // super property access expressions can also appear in arrow functions -
55051                 // in this case they should also use correct lexical this
55052                 captureLexicalThis(node.parent, container);
55053             }
55054             if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
55055                 if (languageVersion < 2 /* ES2015 */) {
55056                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
55057                     return errorType;
55058                 }
55059                 else {
55060                     // for object literal assume that type of 'super' is 'any'
55061                     return anyType;
55062                 }
55063             }
55064             // at this point the only legal case for parent is ClassLikeDeclaration
55065             var classLikeDeclaration = container.parent;
55066             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
55067                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
55068                 return errorType;
55069             }
55070             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
55071             var baseClassType = classType && getBaseTypes(classType)[0];
55072             if (!baseClassType) {
55073                 return errorType;
55074             }
55075             if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
55076                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
55077                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
55078                 return errorType;
55079             }
55080             return nodeCheckFlag === 512 /* SuperStatic */
55081                 ? getBaseConstructorTypeOfClass(classType)
55082                 : getTypeWithThisArgument(baseClassType, classType.thisType);
55083             function isLegalUsageOfSuperExpression(container) {
55084                 if (!container) {
55085                     return false;
55086                 }
55087                 if (isCallExpression) {
55088                     // TS 1.0 SPEC (April 2014): 4.8.1
55089                     // Super calls are only permitted in constructors of derived classes
55090                     return container.kind === 162 /* Constructor */;
55091                 }
55092                 else {
55093                     // TS 1.0 SPEC (April 2014)
55094                     // 'super' property access is allowed
55095                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
55096                     // - In a static member function or static member accessor
55097                     // topmost container must be something that is directly nested in the class declaration\object literal expression
55098                     if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
55099                         if (ts.hasModifier(container, 32 /* Static */)) {
55100                             return container.kind === 161 /* MethodDeclaration */ ||
55101                                 container.kind === 160 /* MethodSignature */ ||
55102                                 container.kind === 163 /* GetAccessor */ ||
55103                                 container.kind === 164 /* SetAccessor */;
55104                         }
55105                         else {
55106                             return container.kind === 161 /* MethodDeclaration */ ||
55107                                 container.kind === 160 /* MethodSignature */ ||
55108                                 container.kind === 163 /* GetAccessor */ ||
55109                                 container.kind === 164 /* SetAccessor */ ||
55110                                 container.kind === 159 /* PropertyDeclaration */ ||
55111                                 container.kind === 158 /* PropertySignature */ ||
55112                                 container.kind === 162 /* Constructor */;
55113                         }
55114                     }
55115                 }
55116                 return false;
55117             }
55118         }
55119         function getContainingObjectLiteral(func) {
55120             return (func.kind === 161 /* MethodDeclaration */ ||
55121                 func.kind === 163 /* GetAccessor */ ||
55122                 func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
55123                 func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
55124                     undefined;
55125         }
55126         function getThisTypeArgument(type) {
55127             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
55128         }
55129         function getThisTypeFromContextualType(type) {
55130             return mapType(type, function (t) {
55131                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
55132             });
55133         }
55134         function getContextualThisParameterType(func) {
55135             if (func.kind === 202 /* ArrowFunction */) {
55136                 return undefined;
55137             }
55138             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55139                 var contextualSignature = getContextualSignature(func);
55140                 if (contextualSignature) {
55141                     var thisParameter = contextualSignature.thisParameter;
55142                     if (thisParameter) {
55143                         return getTypeOfSymbol(thisParameter);
55144                     }
55145                 }
55146             }
55147             var inJs = ts.isInJSFile(func);
55148             if (noImplicitThis || inJs) {
55149                 var containingLiteral = getContainingObjectLiteral(func);
55150                 if (containingLiteral) {
55151                     // We have an object literal method. Check if the containing object literal has a contextual type
55152                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
55153                     // any directly enclosing object literals.
55154                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
55155                     var literal = containingLiteral;
55156                     var type = contextualType;
55157                     while (type) {
55158                         var thisType = getThisTypeFromContextualType(type);
55159                         if (thisType) {
55160                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
55161                         }
55162                         if (literal.parent.kind !== 281 /* PropertyAssignment */) {
55163                             break;
55164                         }
55165                         literal = literal.parent.parent;
55166                         type = getApparentTypeOfContextualType(literal);
55167                     }
55168                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
55169                     // for 'this' is the non-null form of the contextual type for the containing object literal or
55170                     // the type of the object literal itself.
55171                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
55172                 }
55173                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
55174                 // contextual type for 'this' is 'obj'.
55175                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
55176                 if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
55177                     var target = parent.left;
55178                     if (ts.isAccessExpression(target)) {
55179                         var expression = target.expression;
55180                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
55181                         if (inJs && ts.isIdentifier(expression)) {
55182                             var sourceFile = ts.getSourceFileOfNode(parent);
55183                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
55184                                 return undefined;
55185                             }
55186                         }
55187                         return getWidenedType(checkExpressionCached(expression));
55188                     }
55189                 }
55190             }
55191             return undefined;
55192         }
55193         // Return contextual type of parameter or undefined if no contextual type is available
55194         function getContextuallyTypedParameterType(parameter) {
55195             var func = parameter.parent;
55196             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55197                 return undefined;
55198             }
55199             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
55200             if (iife && iife.arguments) {
55201                 var args = getEffectiveCallArguments(iife);
55202                 var indexOfParameter = func.parameters.indexOf(parameter);
55203                 if (parameter.dotDotDotToken) {
55204                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
55205                 }
55206                 var links = getNodeLinks(iife);
55207                 var cached = links.resolvedSignature;
55208                 links.resolvedSignature = anySignature;
55209                 var type = indexOfParameter < args.length ?
55210                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
55211                     parameter.initializer ? undefined : undefinedWideningType;
55212                 links.resolvedSignature = cached;
55213                 return type;
55214             }
55215             var contextualSignature = getContextualSignature(func);
55216             if (contextualSignature) {
55217                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
55218                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
55219                     getRestTypeAtPosition(contextualSignature, index) :
55220                     tryGetTypeAtPosition(contextualSignature, index);
55221             }
55222         }
55223         function getContextualTypeForVariableLikeDeclaration(declaration) {
55224             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
55225             if (typeNode) {
55226                 return getTypeFromTypeNode(typeNode);
55227             }
55228             switch (declaration.kind) {
55229                 case 156 /* Parameter */:
55230                     return getContextuallyTypedParameterType(declaration);
55231                 case 191 /* BindingElement */:
55232                     return getContextualTypeForBindingElement(declaration);
55233                 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
55234             }
55235         }
55236         function getContextualTypeForBindingElement(declaration) {
55237             var parent = declaration.parent.parent;
55238             var name = declaration.propertyName || declaration.name;
55239             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
55240                 parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
55241             if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
55242                 var nameType = getLiteralTypeFromPropertyName(name);
55243                 if (isTypeUsableAsPropertyName(nameType)) {
55244                     var text = getPropertyNameFromType(nameType);
55245                     return getTypeOfPropertyOfType(parentType, text);
55246                 }
55247             }
55248         }
55249         // In a variable, parameter or property declaration with a type annotation,
55250         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
55251         // Otherwise, in a parameter declaration of a contextually typed function expression,
55252         //   the contextual type of an initializer expression is the contextual type of the parameter.
55253         // Otherwise, in a variable or parameter declaration with a binding pattern name,
55254         //   the contextual type of an initializer expression is the type implied by the binding pattern.
55255         // Otherwise, in a binding pattern inside a variable or parameter declaration,
55256         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
55257         function getContextualTypeForInitializerExpression(node) {
55258             var declaration = node.parent;
55259             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
55260                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
55261                 if (result) {
55262                     return result;
55263                 }
55264                 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
55265                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
55266                 }
55267             }
55268             return undefined;
55269         }
55270         function getContextualTypeForReturnExpression(node) {
55271             var func = ts.getContainingFunction(node);
55272             if (func) {
55273                 var functionFlags = ts.getFunctionFlags(func);
55274                 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
55275                     return undefined;
55276                 }
55277                 var contextualReturnType = getContextualReturnType(func);
55278                 if (contextualReturnType) {
55279                     if (functionFlags & 2 /* Async */) { // Async function
55280                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise);
55281                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55282                     }
55283                     return contextualReturnType; // Regular function
55284                 }
55285             }
55286             return undefined;
55287         }
55288         function getContextualTypeForAwaitOperand(node) {
55289             var contextualType = getContextualType(node);
55290             if (contextualType) {
55291                 var contextualAwaitedType = getAwaitedType(contextualType);
55292                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55293             }
55294             return undefined;
55295         }
55296         function getContextualTypeForYieldOperand(node) {
55297             var func = ts.getContainingFunction(node);
55298             if (func) {
55299                 var functionFlags = ts.getFunctionFlags(func);
55300                 var contextualReturnType = getContextualReturnType(func);
55301                 if (contextualReturnType) {
55302                     return node.asteriskToken
55303                         ? contextualReturnType
55304                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
55305                 }
55306             }
55307             return undefined;
55308         }
55309         function isInParameterInitializerBeforeContainingFunction(node) {
55310             var inBindingInitializer = false;
55311             while (node.parent && !ts.isFunctionLike(node.parent)) {
55312                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
55313                     return true;
55314                 }
55315                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
55316                     inBindingInitializer = true;
55317                 }
55318                 node = node.parent;
55319             }
55320             return false;
55321         }
55322         function getContextualIterationType(kind, functionDecl) {
55323             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
55324             var contextualReturnType = getContextualReturnType(functionDecl);
55325             if (contextualReturnType) {
55326                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
55327                     || undefined;
55328             }
55329             return undefined;
55330         }
55331         function getContextualReturnType(functionDecl) {
55332             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
55333             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
55334             var returnType = getReturnTypeFromAnnotation(functionDecl);
55335             if (returnType) {
55336                 return returnType;
55337             }
55338             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
55339             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
55340             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
55341             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
55342                 return getReturnTypeOfSignature(signature);
55343             }
55344             return undefined;
55345         }
55346         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
55347         function getContextualTypeForArgument(callTarget, arg) {
55348             var args = getEffectiveCallArguments(callTarget);
55349             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
55350             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
55351         }
55352         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
55353             // If we're already in the process of resolving the given signature, don't resolve again as
55354             // that could cause infinite recursion. Instead, return anySignature.
55355             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
55356             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
55357                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
55358             }
55359             return getTypeAtPosition(signature, argIndex);
55360         }
55361         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
55362             if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
55363                 return getContextualTypeForArgument(template.parent, substitutionExpression);
55364             }
55365             return undefined;
55366         }
55367         function getContextualTypeForBinaryOperand(node, contextFlags) {
55368             var binaryExpression = node.parent;
55369             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
55370             switch (operatorToken.kind) {
55371                 case 62 /* EqualsToken */:
55372                     if (node !== right) {
55373                         return undefined;
55374                     }
55375                     var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
55376                     if (!contextSensitive) {
55377                         return undefined;
55378                     }
55379                     return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
55380                 case 56 /* BarBarToken */:
55381                 case 60 /* QuestionQuestionToken */:
55382                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
55383                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
55384                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
55385                     // by the type of the left operand, except for the special case of Javascript declarations of the form
55386                     // `namespace.prop = namespace.prop || {}`.
55387                     var type = getContextualType(binaryExpression, contextFlags);
55388                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
55389                         getTypeOfExpression(left) : type;
55390                 case 55 /* AmpersandAmpersandToken */:
55391                 case 27 /* CommaToken */:
55392                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
55393                 default:
55394                     return undefined;
55395             }
55396         }
55397         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
55398         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
55399         function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
55400             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
55401             switch (kind) {
55402                 case 0 /* None */:
55403                     return true;
55404                 case 5 /* Property */:
55405                 case 1 /* ExportsProperty */:
55406                 case 6 /* Prototype */:
55407                 case 3 /* PrototypeProperty */:
55408                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
55409                     // See `bindStaticPropertyAssignment` in `binder.ts`.
55410                     if (!binaryExpression.left.symbol) {
55411                         return true;
55412                     }
55413                     else {
55414                         var decl = binaryExpression.left.symbol.valueDeclaration;
55415                         if (!decl) {
55416                             return false;
55417                         }
55418                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
55419                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
55420                         if (overallAnnotation) {
55421                             return getTypeFromTypeNode(overallAnnotation);
55422                         }
55423                         else if (ts.isIdentifier(lhs.expression)) {
55424                             var id = lhs.expression;
55425                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
55426                             if (parentSymbol) {
55427                                 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
55428                                 if (annotated) {
55429                                     var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
55430                                     if (nameStr_1 !== undefined) {
55431                                         var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
55432                                         return type || false;
55433                                     }
55434                                 }
55435                                 return false;
55436                             }
55437                         }
55438                         return !ts.isInJSFile(decl);
55439                     }
55440                 case 2 /* ModuleExports */:
55441                 case 4 /* ThisProperty */:
55442                     if (!binaryExpression.symbol)
55443                         return true;
55444                     if (binaryExpression.symbol.valueDeclaration) {
55445                         var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
55446                         if (annotated) {
55447                             var type = getTypeFromTypeNode(annotated);
55448                             if (type) {
55449                                 return type;
55450                             }
55451                         }
55452                     }
55453                     if (kind === 2 /* ModuleExports */)
55454                         return false;
55455                     var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
55456                     if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
55457                         return false;
55458                     }
55459                     var thisType = checkThisExpression(thisAccess.expression);
55460                     var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
55461                     return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
55462                 case 7 /* ObjectDefinePropertyValue */:
55463                 case 8 /* ObjectDefinePropertyExports */:
55464                 case 9 /* ObjectDefinePrototypeProperty */:
55465                     return ts.Debug.fail("Does not apply");
55466                 default:
55467                     return ts.Debug.assertNever(kind);
55468             }
55469         }
55470         function isCircularMappedProperty(symbol) {
55471             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
55472         }
55473         function getTypeOfPropertyOfContextualType(type, name) {
55474             return mapType(type, function (t) {
55475                 if (isGenericMappedType(t)) {
55476                     var constraint = getConstraintTypeFromMappedType(t);
55477                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
55478                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
55479                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
55480                         return substituteIndexedMappedType(t, propertyNameType);
55481                     }
55482                 }
55483                 else if (t.flags & 3670016 /* StructuredType */) {
55484                     var prop = getPropertyOfType(t, name);
55485                     if (prop) {
55486                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
55487                     }
55488                     if (isTupleType(t)) {
55489                         var restType = getRestTypeOfTupleType(t);
55490                         if (restType && isNumericLiteralName(name) && +name >= 0) {
55491                             return restType;
55492                         }
55493                     }
55494                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
55495                         getIndexTypeOfContextualType(t, 0 /* String */);
55496                 }
55497                 return undefined;
55498             }, /*noReductions*/ true);
55499         }
55500         function getIndexTypeOfContextualType(type, kind) {
55501             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
55502         }
55503         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
55504         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
55505         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
55506         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
55507             ts.Debug.assert(ts.isObjectLiteralMethod(node));
55508             if (node.flags & 16777216 /* InWithStatement */) {
55509                 // We cannot answer semantic questions within a with block, do not proceed any further
55510                 return undefined;
55511             }
55512             return getContextualTypeForObjectLiteralElement(node, contextFlags);
55513         }
55514         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
55515             var objectLiteral = element.parent;
55516             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
55517             if (type) {
55518                 if (!hasNonBindableDynamicName(element)) {
55519                     // For a (non-symbol) computed property, there is no reason to look up the name
55520                     // in the type. It will just be "__computed", which does not appear in any
55521                     // SymbolTable.
55522                     var symbolName_3 = getSymbolOfNode(element).escapedName;
55523                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
55524                     if (propertyType) {
55525                         return propertyType;
55526                     }
55527                 }
55528                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
55529                     getIndexTypeOfContextualType(type, 0 /* String */);
55530             }
55531             return undefined;
55532         }
55533         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
55534         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
55535         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
55536         // type of T.
55537         function getContextualTypeForElementExpression(arrayContextualType, index) {
55538             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
55539                 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
55540         }
55541         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
55542         function getContextualTypeForConditionalOperand(node, contextFlags) {
55543             var conditional = node.parent;
55544             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
55545         }
55546         function getContextualTypeForChildJsxExpression(node, child) {
55547             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
55548             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
55549             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
55550             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
55551                 return undefined;
55552             }
55553             var realChildren = getSemanticJsxChildren(node.children);
55554             var childIndex = realChildren.indexOf(child);
55555             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
55556             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
55557                 if (isArrayLikeType(t)) {
55558                     return getIndexedAccessType(t, getLiteralType(childIndex));
55559                 }
55560                 else {
55561                     return t;
55562                 }
55563             }, /*noReductions*/ true));
55564         }
55565         function getContextualTypeForJsxExpression(node) {
55566             var exprParent = node.parent;
55567             return ts.isJsxAttributeLike(exprParent)
55568                 ? getContextualType(node)
55569                 : ts.isJsxElement(exprParent)
55570                     ? getContextualTypeForChildJsxExpression(exprParent, node)
55571                     : undefined;
55572         }
55573         function getContextualTypeForJsxAttribute(attribute) {
55574             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
55575             // which is a type of the parameter of the signature we are trying out.
55576             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
55577             if (ts.isJsxAttribute(attribute)) {
55578                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
55579                 if (!attributesType || isTypeAny(attributesType)) {
55580                     return undefined;
55581                 }
55582                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
55583             }
55584             else {
55585                 return getContextualType(attribute.parent);
55586             }
55587         }
55588         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
55589         // expressions we check to those that don't depend on their contextual type in order not to cause
55590         // recursive (and possibly infinite) invocations of getContextualType.
55591         function isPossiblyDiscriminantValue(node) {
55592             switch (node.kind) {
55593                 case 10 /* StringLiteral */:
55594                 case 8 /* NumericLiteral */:
55595                 case 9 /* BigIntLiteral */:
55596                 case 14 /* NoSubstitutionTemplateLiteral */:
55597                 case 106 /* TrueKeyword */:
55598                 case 91 /* FalseKeyword */:
55599                 case 100 /* NullKeyword */:
55600                 case 75 /* Identifier */:
55601                 case 146 /* UndefinedKeyword */:
55602                     return true;
55603                 case 194 /* PropertyAccessExpression */:
55604                 case 200 /* ParenthesizedExpression */:
55605                     return isPossiblyDiscriminantValue(node.expression);
55606                 case 276 /* JsxExpression */:
55607                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
55608             }
55609             return false;
55610         }
55611         function discriminateContextualTypeByObjectMembers(node, contextualType) {
55612             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);
55613         }
55614         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
55615             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);
55616         }
55617         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
55618         // be "pushed" onto a node using the contextualType property.
55619         function getApparentTypeOfContextualType(node, contextFlags) {
55620             var contextualType = ts.isObjectLiteralMethod(node) ?
55621                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
55622                 getContextualType(node, contextFlags);
55623             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
55624             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
55625                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
55626                 if (apparentType.flags & 1048576 /* Union */) {
55627                     if (ts.isObjectLiteralExpression(node)) {
55628                         return discriminateContextualTypeByObjectMembers(node, apparentType);
55629                     }
55630                     else if (ts.isJsxAttributes(node)) {
55631                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
55632                     }
55633                 }
55634                 return apparentType;
55635             }
55636         }
55637         // If the given contextual type contains instantiable types and if a mapper representing
55638         // return type inferences is available, instantiate those types using that mapper.
55639         function instantiateContextualType(contextualType, node, contextFlags) {
55640             if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
55641                 var inferenceContext = getInferenceContext(node);
55642                 // If no inferences have been made, nothing is gained from instantiating as type parameters
55643                 // would just be replaced with their defaults similar to the apparent type.
55644                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
55645                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
55646                     // types as well as arguments to the left in a function call.
55647                     if (contextFlags && contextFlags & 1 /* Signature */) {
55648                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
55649                     }
55650                     // For other purposes (e.g. determining whether to produce literal types) we only
55651                     // incorporate inferences made from the return type in a function call.
55652                     if (inferenceContext.returnMapper) {
55653                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
55654                     }
55655                 }
55656             }
55657             return contextualType;
55658         }
55659         // This function is similar to instantiateType, except that (a) it only instantiates types that
55660         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
55661         // no reductions on instantiated union types.
55662         function instantiateInstantiableTypes(type, mapper) {
55663             if (type.flags & 63176704 /* Instantiable */) {
55664                 return instantiateType(type, mapper);
55665             }
55666             if (type.flags & 1048576 /* Union */) {
55667                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
55668             }
55669             if (type.flags & 2097152 /* Intersection */) {
55670                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
55671             }
55672             return type;
55673         }
55674         /**
55675          * Whoa! Do you really want to use this function?
55676          *
55677          * Unless you're trying to get the *non-apparent* type for a
55678          * value-literal type or you're authoring relevant portions of this algorithm,
55679          * you probably meant to use 'getApparentTypeOfContextualType'.
55680          * Otherwise this may not be very useful.
55681          *
55682          * In cases where you *are* working on this function, you should understand
55683          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
55684          *
55685          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
55686          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
55687          *
55688          * @param node the expression whose contextual type will be returned.
55689          * @returns the contextual type of an expression.
55690          */
55691         function getContextualType(node, contextFlags) {
55692             if (node.flags & 16777216 /* InWithStatement */) {
55693                 // We cannot answer semantic questions within a with block, do not proceed any further
55694                 return undefined;
55695             }
55696             if (node.contextualType) {
55697                 return node.contextualType;
55698             }
55699             var parent = node.parent;
55700             switch (parent.kind) {
55701                 case 242 /* VariableDeclaration */:
55702                 case 156 /* Parameter */:
55703                 case 159 /* PropertyDeclaration */:
55704                 case 158 /* PropertySignature */:
55705                 case 191 /* BindingElement */:
55706                     return getContextualTypeForInitializerExpression(node);
55707                 case 202 /* ArrowFunction */:
55708                 case 235 /* ReturnStatement */:
55709                     return getContextualTypeForReturnExpression(node);
55710                 case 212 /* YieldExpression */:
55711                     return getContextualTypeForYieldOperand(parent);
55712                 case 206 /* AwaitExpression */:
55713                     return getContextualTypeForAwaitOperand(parent);
55714                 case 196 /* CallExpression */:
55715                     if (parent.expression.kind === 96 /* ImportKeyword */) {
55716                         return stringType;
55717                     }
55718                 /* falls through */
55719                 case 197 /* NewExpression */:
55720                     return getContextualTypeForArgument(parent, node);
55721                 case 199 /* TypeAssertionExpression */:
55722                 case 217 /* AsExpression */:
55723                     return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
55724                 case 209 /* BinaryExpression */:
55725                     return getContextualTypeForBinaryOperand(node, contextFlags);
55726                 case 281 /* PropertyAssignment */:
55727                 case 282 /* ShorthandPropertyAssignment */:
55728                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
55729                 case 283 /* SpreadAssignment */:
55730                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
55731                 case 192 /* ArrayLiteralExpression */: {
55732                     var arrayLiteral = parent;
55733                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
55734                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
55735                 }
55736                 case 210 /* ConditionalExpression */:
55737                     return getContextualTypeForConditionalOperand(node, contextFlags);
55738                 case 221 /* TemplateSpan */:
55739                     ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
55740                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
55741                 case 200 /* ParenthesizedExpression */: {
55742                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
55743                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
55744                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
55745                 }
55746                 case 276 /* JsxExpression */:
55747                     return getContextualTypeForJsxExpression(parent);
55748                 case 273 /* JsxAttribute */:
55749                 case 275 /* JsxSpreadAttribute */:
55750                     return getContextualTypeForJsxAttribute(parent);
55751                 case 268 /* JsxOpeningElement */:
55752                 case 267 /* JsxSelfClosingElement */:
55753                     return getContextualJsxElementAttributesType(parent, contextFlags);
55754             }
55755             return undefined;
55756         }
55757         function getInferenceContext(node) {
55758             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
55759             return ancestor && ancestor.inferenceContext;
55760         }
55761         function getContextualJsxElementAttributesType(node, contextFlags) {
55762             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
55763                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
55764                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
55765                 // (as below) instead!
55766                 return node.parent.contextualType;
55767             }
55768             return getContextualTypeForArgumentAtIndex(node, 0);
55769         }
55770         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
55771             return getJsxReferenceKind(node) !== 0 /* Component */
55772                 ? getJsxPropsTypeFromCallSignature(signature, node)
55773                 : getJsxPropsTypeFromClassType(signature, node);
55774         }
55775         function getJsxPropsTypeFromCallSignature(sig, context) {
55776             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
55777             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
55778             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55779             if (intrinsicAttribs !== errorType) {
55780                 propsType = intersectTypes(intrinsicAttribs, propsType);
55781             }
55782             return propsType;
55783         }
55784         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
55785             if (sig.unionSignatures) {
55786                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
55787                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
55788                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
55789                 // 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.
55790                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
55791                 var results = [];
55792                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
55793                     var signature = _a[_i];
55794                     var instance = getReturnTypeOfSignature(signature);
55795                     if (isTypeAny(instance)) {
55796                         return instance;
55797                     }
55798                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
55799                     if (!propType) {
55800                         return;
55801                     }
55802                     results.push(propType);
55803                 }
55804                 return getIntersectionType(results);
55805             }
55806             var instanceType = getReturnTypeOfSignature(sig);
55807             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
55808         }
55809         function getStaticTypeOfReferencedJsxConstructor(context) {
55810             if (isJsxIntrinsicIdentifier(context.tagName)) {
55811                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
55812                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55813                 return getOrCreateTypeFromSignature(fakeSignature);
55814             }
55815             var tagType = checkExpressionCached(context.tagName);
55816             if (tagType.flags & 128 /* StringLiteral */) {
55817                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
55818                 if (!result) {
55819                     return errorType;
55820                 }
55821                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55822                 return getOrCreateTypeFromSignature(fakeSignature);
55823             }
55824             return tagType;
55825         }
55826         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
55827             var managedSym = getJsxLibraryManagedAttributes(ns);
55828             if (managedSym) {
55829                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
55830                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
55831                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
55832                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
55833                     return createTypeReference(declaredManagedType, args);
55834                 }
55835                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
55836                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
55837                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
55838                 }
55839             }
55840             return attributesType;
55841         }
55842         function getJsxPropsTypeFromClassType(sig, context) {
55843             var ns = getJsxNamespaceAt(context);
55844             var forcedLookupLocation = getJsxElementPropertiesName(ns);
55845             var attributesType = forcedLookupLocation === undefined
55846                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
55847                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
55848                 : forcedLookupLocation === ""
55849                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
55850                     ? getReturnTypeOfSignature(sig)
55851                     // Otherwise get the type of the property on the signature return type
55852                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
55853             if (!attributesType) {
55854                 // There is no property named 'props' on this instance type
55855                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
55856                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
55857                 }
55858                 return unknownType;
55859             }
55860             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
55861             if (isTypeAny(attributesType)) {
55862                 // Props is of type 'any' or unknown
55863                 return attributesType;
55864             }
55865             else {
55866                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
55867                 var apparentAttributesType = attributesType;
55868                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
55869                 if (intrinsicClassAttribs !== errorType) {
55870                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
55871                     var hostClassType = getReturnTypeOfSignature(sig);
55872                     apparentAttributesType = intersectTypes(typeParams
55873                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
55874                         : intrinsicClassAttribs, apparentAttributesType);
55875                 }
55876                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55877                 if (intrinsicAttribs !== errorType) {
55878                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
55879                 }
55880                 return apparentAttributesType;
55881             }
55882         }
55883         // If the given type is an object or union type with a single signature, and if that signature has at
55884         // least as many parameters as the given function, return the signature. Otherwise return undefined.
55885         function getContextualCallSignature(type, node) {
55886             var signatures = getSignaturesOfType(type, 0 /* Call */);
55887             if (signatures.length === 1) {
55888                 var signature = signatures[0];
55889                 if (!isAritySmaller(signature, node)) {
55890                     return signature;
55891                 }
55892             }
55893         }
55894         /** If the contextual signature has fewer parameters than the function expression, do not use it */
55895         function isAritySmaller(signature, target) {
55896             var targetParameterCount = 0;
55897             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
55898                 var param = target.parameters[targetParameterCount];
55899                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
55900                     break;
55901                 }
55902             }
55903             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
55904                 targetParameterCount--;
55905             }
55906             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
55907         }
55908         function isFunctionExpressionOrArrowFunction(node) {
55909             return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
55910         }
55911         function getContextualSignatureForFunctionLikeDeclaration(node) {
55912             // Only function expressions, arrow functions, and object literal methods are contextually typed.
55913             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
55914                 ? getContextualSignature(node)
55915                 : undefined;
55916         }
55917         // Return the contextual signature for a given expression node. A contextual type provides a
55918         // contextual signature if it has a single call signature and if that call signature is non-generic.
55919         // If the contextual type is a union type, get the signature from each type possible and if they are
55920         // all identical ignoring their return type, the result is same signature but with return type as
55921         // union type of return types from these signatures
55922         function getContextualSignature(node) {
55923             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55924             var typeTagSignature = getSignatureOfTypeTag(node);
55925             if (typeTagSignature) {
55926                 return typeTagSignature;
55927             }
55928             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
55929             if (!type) {
55930                 return undefined;
55931             }
55932             if (!(type.flags & 1048576 /* Union */)) {
55933                 return getContextualCallSignature(type, node);
55934             }
55935             var signatureList;
55936             var types = type.types;
55937             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
55938                 var current = types_17[_i];
55939                 var signature = getContextualCallSignature(current, node);
55940                 if (signature) {
55941                     if (!signatureList) {
55942                         // This signature will contribute to contextual union signature
55943                         signatureList = [signature];
55944                     }
55945                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
55946                         // Signatures aren't identical, do not use
55947                         return undefined;
55948                     }
55949                     else {
55950                         // Use this signature for contextual union signature
55951                         signatureList.push(signature);
55952                     }
55953                 }
55954             }
55955             // Result is union of signatures collected (return type is union of return types of this signature set)
55956             if (signatureList) {
55957                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
55958             }
55959         }
55960         function checkSpreadExpression(node, checkMode) {
55961             if (languageVersion < 2 /* ES2015 */) {
55962                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
55963             }
55964             var arrayOrIterableType = checkExpression(node.expression, checkMode);
55965             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
55966         }
55967         function hasDefaultValue(node) {
55968             return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
55969                 (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
55970         }
55971         function checkArrayLiteral(node, checkMode, forceTuple) {
55972             var elements = node.elements;
55973             var elementCount = elements.length;
55974             var elementTypes = [];
55975             var hasEndingSpreadElement = false;
55976             var hasNonEndingSpreadElement = false;
55977             var contextualType = getApparentTypeOfContextualType(node);
55978             var inDestructuringPattern = ts.isAssignmentTarget(node);
55979             var inConstContext = isConstContext(node);
55980             for (var i = 0; i < elementCount; i++) {
55981                 var e = elements[i];
55982                 var spread = e.kind === 213 /* SpreadElement */ && e.expression;
55983                 var spreadType = spread && checkExpression(spread, checkMode, forceTuple);
55984                 if (spreadType && isTupleType(spreadType)) {
55985                     elementTypes.push.apply(elementTypes, getTypeArguments(spreadType));
55986                     if (spreadType.target.hasRestElement) {
55987                         if (i === elementCount - 1)
55988                             hasEndingSpreadElement = true;
55989                         else
55990                             hasNonEndingSpreadElement = true;
55991                     }
55992                 }
55993                 else {
55994                     if (inDestructuringPattern && spreadType) {
55995                         // Given the following situation:
55996                         //    var c: {};
55997                         //    [...c] = ["", 0];
55998                         //
55999                         // c is represented in the tree as a spread element in an array literal.
56000                         // But c really functions as a rest element, and its purpose is to provide
56001                         // a contextual type for the right hand side of the assignment. Therefore,
56002                         // instead of calling checkExpression on "...c", which will give an error
56003                         // if c is not iterable/array-like, we need to act as if we are trying to
56004                         // get the contextual element type from it. So we do something similar to
56005                         // getContextualTypeForElementExpression, which will crucially not error
56006                         // if there is no index type / iterated type.
56007                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
56008                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
56009                         if (restElementType) {
56010                             elementTypes.push(restElementType);
56011                         }
56012                     }
56013                     else {
56014                         var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
56015                         var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
56016                         elementTypes.push(type);
56017                     }
56018                     if (spread) { // tuples are done above, so these are only arrays
56019                         if (i === elementCount - 1)
56020                             hasEndingSpreadElement = true;
56021                         else
56022                             hasNonEndingSpreadElement = true;
56023                     }
56024                 }
56025             }
56026             if (!hasNonEndingSpreadElement) {
56027                 var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0);
56028                 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
56029                 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
56030                 var tupleResult = void 0;
56031                 if (inDestructuringPattern && minLength > 0) {
56032                     var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
56033                     type.pattern = node;
56034                     return type;
56035                 }
56036                 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) {
56037                     return createArrayLiteralType(tupleResult);
56038                 }
56039                 else if (forceTuple) {
56040                     return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
56041                 }
56042             }
56043             return createArrayLiteralType(createArrayType(elementTypes.length ?
56044                 getUnionType(elementTypes, 2 /* Subtype */) :
56045                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
56046         }
56047         function createArrayLiteralType(type) {
56048             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
56049                 return type;
56050             }
56051             var literalType = type.literalType;
56052             if (!literalType) {
56053                 literalType = type.literalType = cloneTypeReference(type);
56054                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56055             }
56056             return literalType;
56057         }
56058         function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
56059             if (elementCount === void 0) { elementCount = elementTypes.length; }
56060             if (readonly === void 0) { readonly = false; }
56061             // Infer a tuple type when the contextual type is or contains a tuple-like type
56062             if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
56063                 return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
56064             }
56065         }
56066         function isNumericName(name) {
56067             switch (name.kind) {
56068                 case 154 /* ComputedPropertyName */:
56069                     return isNumericComputedName(name);
56070                 case 75 /* Identifier */:
56071                     return isNumericLiteralName(name.escapedText);
56072                 case 8 /* NumericLiteral */:
56073                 case 10 /* StringLiteral */:
56074                     return isNumericLiteralName(name.text);
56075                 default:
56076                     return false;
56077             }
56078         }
56079         function isNumericComputedName(name) {
56080             // It seems odd to consider an expression of type Any to result in a numeric name,
56081             // but this behavior is consistent with checkIndexedAccess
56082             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
56083         }
56084         function isInfinityOrNaNString(name) {
56085             return name === "Infinity" || name === "-Infinity" || name === "NaN";
56086         }
56087         function isNumericLiteralName(name) {
56088             // The intent of numeric names is that
56089             //     - they are names with text in a numeric form, and that
56090             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
56091             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
56092             //
56093             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
56094             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
56095             //
56096             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
56097             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
56098             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
56099             // because their 'ToString' representation is not equal to their original text.
56100             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
56101             //
56102             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
56103             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
56104             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
56105             //
56106             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
56107             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
56108             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
56109             return (+name).toString() === name;
56110         }
56111         function checkComputedPropertyName(node) {
56112             var links = getNodeLinks(node.expression);
56113             if (!links.resolvedType) {
56114                 links.resolvedType = checkExpression(node.expression);
56115                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
56116                 // type, and any union of these types (like string | number).
56117                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
56118                     !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
56119                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
56120                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
56121                 }
56122                 else {
56123                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
56124                 }
56125             }
56126             return links.resolvedType;
56127         }
56128         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
56129             var propTypes = [];
56130             for (var i = 0; i < properties.length; i++) {
56131                 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
56132                     propTypes.push(getTypeOfSymbol(properties[i]));
56133                 }
56134             }
56135             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
56136             return createIndexInfo(unionType, isConstContext(node));
56137         }
56138         function getImmediateAliasedSymbol(symbol) {
56139             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
56140             var links = getSymbolLinks(symbol);
56141             if (!links.immediateTarget) {
56142                 var node = getDeclarationOfAliasSymbol(symbol);
56143                 if (!node)
56144                     return ts.Debug.fail();
56145                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
56146             }
56147             return links.immediateTarget;
56148         }
56149         function checkObjectLiteral(node, checkMode) {
56150             var inDestructuringPattern = ts.isAssignmentTarget(node);
56151             // Grammar checking
56152             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
56153             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56154             var propertiesTable = ts.createSymbolTable();
56155             var propertiesArray = [];
56156             var spread = emptyObjectType;
56157             var contextualType = getApparentTypeOfContextualType(node);
56158             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
56159                 (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
56160             var inConstContext = isConstContext(node);
56161             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
56162             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
56163             var enumTag = ts.getJSDocEnumTag(node);
56164             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
56165             var objectFlags = freshObjectLiteralFlag;
56166             var patternWithComputedProperties = false;
56167             var hasComputedStringProperty = false;
56168             var hasComputedNumberProperty = false;
56169             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
56170             // As otherwise they may not be checked until exports for the type at this position are retrieved,
56171             // which may never occur.
56172             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
56173                 var elem = _a[_i];
56174                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
56175                     checkComputedPropertyName(elem.name);
56176                 }
56177             }
56178             var offset = 0;
56179             for (var i = 0; i < node.properties.length; i++) {
56180                 var memberDecl = node.properties[i];
56181                 var member = getSymbolOfNode(memberDecl);
56182                 var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
56183                     checkComputedPropertyName(memberDecl.name) : undefined;
56184                 if (memberDecl.kind === 281 /* PropertyAssignment */ ||
56185                     memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
56186                     ts.isObjectLiteralMethod(memberDecl)) {
56187                     var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
56188                         memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
56189                             checkObjectLiteralMethod(memberDecl, checkMode);
56190                     if (isInJavascript) {
56191                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
56192                         if (jsDocType) {
56193                             checkTypeAssignableTo(type, jsDocType, memberDecl);
56194                             type = jsDocType;
56195                         }
56196                         else if (enumTag && enumTag.typeExpression) {
56197                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
56198                         }
56199                     }
56200                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
56201                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
56202                     var prop = nameType ?
56203                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
56204                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
56205                     if (nameType) {
56206                         prop.nameType = nameType;
56207                     }
56208                     if (inDestructuringPattern) {
56209                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
56210                         // for the property, make the property optional.
56211                         var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
56212                             (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
56213                         if (isOptional) {
56214                             prop.flags |= 16777216 /* Optional */;
56215                         }
56216                     }
56217                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
56218                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
56219                         // binding pattern specifies a default value for the property, make the property optional.
56220                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
56221                         if (impliedProp) {
56222                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
56223                         }
56224                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
56225                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
56226                         }
56227                     }
56228                     prop.declarations = member.declarations;
56229                     prop.parent = member.parent;
56230                     if (member.valueDeclaration) {
56231                         prop.valueDeclaration = member.valueDeclaration;
56232                     }
56233                     prop.type = type;
56234                     prop.target = member;
56235                     member = prop;
56236                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
56237                 }
56238                 else if (memberDecl.kind === 283 /* SpreadAssignment */) {
56239                     if (languageVersion < 2 /* ES2015 */) {
56240                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
56241                     }
56242                     if (propertiesArray.length > 0) {
56243                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56244                         propertiesArray = [];
56245                         propertiesTable = ts.createSymbolTable();
56246                         hasComputedStringProperty = false;
56247                         hasComputedNumberProperty = false;
56248                     }
56249                     var type = getReducedType(checkExpression(memberDecl.expression));
56250                     if (!isValidSpreadType(type)) {
56251                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
56252                         return errorType;
56253                     }
56254                     if (allPropertiesTable) {
56255                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
56256                     }
56257                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
56258                     offset = i + 1;
56259                     continue;
56260                 }
56261                 else {
56262                     // TypeScript 1.0 spec (April 2014)
56263                     // A get accessor declaration is processed in the same manner as
56264                     // an ordinary function declaration(section 6.1) with no parameters.
56265                     // A set accessor declaration is processed in the same manner
56266                     // as an ordinary function declaration with a single parameter and a Void return type.
56267                     ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
56268                     checkNodeDeferred(memberDecl);
56269                 }
56270                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
56271                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
56272                         if (isTypeAssignableTo(computedNameType, numberType)) {
56273                             hasComputedNumberProperty = true;
56274                         }
56275                         else {
56276                             hasComputedStringProperty = true;
56277                         }
56278                         if (inDestructuringPattern) {
56279                             patternWithComputedProperties = true;
56280                         }
56281                     }
56282                 }
56283                 else {
56284                     propertiesTable.set(member.escapedName, member);
56285                 }
56286                 propertiesArray.push(member);
56287             }
56288             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
56289             // type with those properties for which the binding pattern specifies a default value.
56290             // If the object literal is spread into another object literal, skip this step and let the top-level object
56291             // literal handle it instead.
56292             if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) {
56293                 for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) {
56294                     var prop = _c[_b];
56295                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
56296                         if (!(prop.flags & 16777216 /* Optional */)) {
56297                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
56298                         }
56299                         propertiesTable.set(prop.escapedName, prop);
56300                         propertiesArray.push(prop);
56301                     }
56302                 }
56303             }
56304             if (spread !== emptyObjectType) {
56305                 if (propertiesArray.length > 0) {
56306                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56307                     propertiesArray = [];
56308                     propertiesTable = ts.createSymbolTable();
56309                     hasComputedStringProperty = false;
56310                     hasComputedNumberProperty = false;
56311                 }
56312                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
56313                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
56314             }
56315             return createObjectLiteralType();
56316             function createObjectLiteralType() {
56317                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
56318                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
56319                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
56320                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56321                 if (isJSObjectLiteral) {
56322                     result.objectFlags |= 16384 /* JSLiteral */;
56323                 }
56324                 if (patternWithComputedProperties) {
56325                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
56326                 }
56327                 if (inDestructuringPattern) {
56328                     result.pattern = node;
56329                 }
56330                 return result;
56331             }
56332         }
56333         function isValidSpreadType(type) {
56334             if (type.flags & 63176704 /* Instantiable */) {
56335                 var constraint = getBaseConstraintOfType(type);
56336                 if (constraint !== undefined) {
56337                     return isValidSpreadType(constraint);
56338                 }
56339             }
56340             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
56341                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
56342                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
56343         }
56344         function checkJsxSelfClosingElementDeferred(node) {
56345             checkJsxOpeningLikeElementOrOpeningFragment(node);
56346             resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
56347         }
56348         function checkJsxSelfClosingElement(node, _checkMode) {
56349             checkNodeDeferred(node);
56350             return getJsxElementTypeAt(node) || anyType;
56351         }
56352         function checkJsxElementDeferred(node) {
56353             // Check attributes
56354             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
56355             // Perform resolution on the closing tag so that rename/go to definition/etc work
56356             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
56357                 getIntrinsicTagSymbol(node.closingElement);
56358             }
56359             else {
56360                 checkExpression(node.closingElement.tagName);
56361             }
56362             checkJsxChildren(node);
56363         }
56364         function checkJsxElement(node, _checkMode) {
56365             checkNodeDeferred(node);
56366             return getJsxElementTypeAt(node) || anyType;
56367         }
56368         function checkJsxFragment(node) {
56369             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
56370             if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
56371                 error(node, compilerOptions.jsxFactory
56372                     ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
56373                     : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
56374             }
56375             checkJsxChildren(node);
56376             return getJsxElementTypeAt(node) || anyType;
56377         }
56378         /**
56379          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
56380          */
56381         function isUnhyphenatedJsxName(name) {
56382             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
56383             return !ts.stringContains(name, "-");
56384         }
56385         /**
56386          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
56387          */
56388         function isJsxIntrinsicIdentifier(tagName) {
56389             return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
56390         }
56391         function checkJsxAttribute(node, checkMode) {
56392             return node.initializer
56393                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
56394                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
56395         }
56396         /**
56397          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
56398          *
56399          * @param openingLikeElement a JSX opening-like element
56400          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
56401          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
56402          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
56403          * which also calls getSpreadType.
56404          */
56405         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
56406             var attributes = openingLikeElement.attributes;
56407             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56408             var attributesTable = ts.createSymbolTable();
56409             var spread = emptyJsxObjectType;
56410             var hasSpreadAnyType = false;
56411             var typeToIntersect;
56412             var explicitlySpecifyChildrenAttribute = false;
56413             var objectFlags = 4096 /* JsxAttributes */;
56414             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
56415             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
56416                 var attributeDecl = _a[_i];
56417                 var member = attributeDecl.symbol;
56418                 if (ts.isJsxAttribute(attributeDecl)) {
56419                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
56420                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
56421                     var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
56422                     attributeSymbol.declarations = member.declarations;
56423                     attributeSymbol.parent = member.parent;
56424                     if (member.valueDeclaration) {
56425                         attributeSymbol.valueDeclaration = member.valueDeclaration;
56426                     }
56427                     attributeSymbol.type = exprType;
56428                     attributeSymbol.target = member;
56429                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56430                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56431                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
56432                         explicitlySpecifyChildrenAttribute = true;
56433                     }
56434                 }
56435                 else {
56436                     ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
56437                     if (attributesTable.size > 0) {
56438                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56439                         attributesTable = ts.createSymbolTable();
56440                     }
56441                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
56442                     if (isTypeAny(exprType)) {
56443                         hasSpreadAnyType = true;
56444                     }
56445                     if (isValidSpreadType(exprType)) {
56446                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
56447                         if (allAttributesTable) {
56448                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
56449                         }
56450                     }
56451                     else {
56452                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
56453                     }
56454                 }
56455             }
56456             if (!hasSpreadAnyType) {
56457                 if (attributesTable.size > 0) {
56458                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56459                 }
56460             }
56461             // Handle children attribute
56462             var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
56463             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
56464             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
56465                 var childrenTypes = checkJsxChildren(parent, checkMode);
56466                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
56467                     // Error if there is a attribute named "children" explicitly specified and children element.
56468                     // This is because children element will overwrite the value from attributes.
56469                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
56470                     if (explicitlySpecifyChildrenAttribute) {
56471                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
56472                     }
56473                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
56474                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
56475                     // 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
56476                     var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
56477                     childrenPropSymbol.type = childrenTypes.length === 1 ?
56478                         childrenTypes[0] :
56479                         (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
56480                     // Fake up a property declaration for the children
56481                     childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
56482                     childrenPropSymbol.valueDeclaration.parent = attributes;
56483                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
56484                     var childPropMap = ts.createSymbolTable();
56485                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
56486                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
56487                 }
56488             }
56489             if (hasSpreadAnyType) {
56490                 return anyType;
56491             }
56492             if (typeToIntersect && spread !== emptyJsxObjectType) {
56493                 return getIntersectionType([typeToIntersect, spread]);
56494             }
56495             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
56496             /**
56497              * Create anonymous type from given attributes symbol table.
56498              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
56499              * @param attributesTable a symbol table of attributes property
56500              */
56501             function createJsxAttributesType() {
56502                 objectFlags |= freshObjectLiteralFlag;
56503                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
56504                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56505                 return result;
56506             }
56507         }
56508         function checkJsxChildren(node, checkMode) {
56509             var childrenTypes = [];
56510             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
56511                 var child = _a[_i];
56512                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
56513                 // because then type of children property will have constituent of string type.
56514                 if (child.kind === 11 /* JsxText */) {
56515                     if (!child.containsOnlyTriviaWhiteSpaces) {
56516                         childrenTypes.push(stringType);
56517                     }
56518                 }
56519                 else {
56520                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
56521                 }
56522             }
56523             return childrenTypes;
56524         }
56525         function checkSpreadPropOverrides(type, props, spread) {
56526             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56527                 var right = _a[_i];
56528                 var left = props.get(right.escapedName);
56529                 var rightType = getTypeOfSymbol(right);
56530                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
56531                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
56532                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
56533                 }
56534             }
56535         }
56536         /**
56537          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
56538          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
56539          * @param node a JSXAttributes to be resolved of its type
56540          */
56541         function checkJsxAttributes(node, checkMode) {
56542             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
56543         }
56544         function getJsxType(name, location) {
56545             var namespace = getJsxNamespaceAt(location);
56546             var exports = namespace && getExportsOfSymbol(namespace);
56547             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
56548             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
56549         }
56550         /**
56551          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
56552          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
56553          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
56554          * May also return unknownSymbol if both of these lookups fail.
56555          */
56556         function getIntrinsicTagSymbol(node) {
56557             var links = getNodeLinks(node);
56558             if (!links.resolvedSymbol) {
56559                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
56560                 if (intrinsicElementsType !== errorType) {
56561                     // Property case
56562                     if (!ts.isIdentifier(node.tagName))
56563                         return ts.Debug.fail();
56564                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
56565                     if (intrinsicProp) {
56566                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
56567                         return links.resolvedSymbol = intrinsicProp;
56568                     }
56569                     // Intrinsic string indexer case
56570                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56571                     if (indexSignatureType) {
56572                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
56573                         return links.resolvedSymbol = intrinsicElementsType.symbol;
56574                     }
56575                     // Wasn't found
56576                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
56577                     return links.resolvedSymbol = unknownSymbol;
56578                 }
56579                 else {
56580                     if (noImplicitAny) {
56581                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
56582                     }
56583                     return links.resolvedSymbol = unknownSymbol;
56584                 }
56585             }
56586             return links.resolvedSymbol;
56587         }
56588         function getJsxNamespaceAt(location) {
56589             var links = location && getNodeLinks(location);
56590             if (links && links.jsxNamespace) {
56591                 return links.jsxNamespace;
56592             }
56593             if (!links || links.jsxNamespace !== false) {
56594                 var namespaceName = getJsxNamespace(location);
56595                 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
56596                 if (resolvedNamespace) {
56597                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
56598                     if (candidate) {
56599                         if (links) {
56600                             links.jsxNamespace = candidate;
56601                         }
56602                         return candidate;
56603                     }
56604                     if (links) {
56605                         links.jsxNamespace = false;
56606                     }
56607                 }
56608             }
56609             // JSX global fallback
56610             return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
56611         }
56612         /**
56613          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
56614          * Get a single property from that container if existed. Report an error if there are more than one property.
56615          *
56616          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
56617          *          if other string is given or the container doesn't exist, return undefined.
56618          */
56619         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
56620             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
56621             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
56622             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
56623             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
56624             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
56625             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
56626             if (propertiesOfJsxElementAttribPropInterface) {
56627                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
56628                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
56629                     return "";
56630                 }
56631                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
56632                 // property of the class instance type
56633                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
56634                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
56635                 }
56636                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
56637                     // More than one property on ElementAttributesProperty is an error
56638                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
56639                 }
56640             }
56641             return undefined;
56642         }
56643         function getJsxLibraryManagedAttributes(jsxNamespace) {
56644             // JSX.LibraryManagedAttributes [symbol]
56645             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
56646         }
56647         /// e.g. "props" for React.d.ts,
56648         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
56649         ///     non-intrinsic elements' attributes type is 'any'),
56650         /// or '' if it has 0 properties (which means every
56651         ///     non-intrinsic elements' attributes type is the element instance type)
56652         function getJsxElementPropertiesName(jsxNamespace) {
56653             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
56654         }
56655         function getJsxElementChildrenPropertyName(jsxNamespace) {
56656             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
56657         }
56658         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
56659             if (elementType.flags & 4 /* String */) {
56660                 return [anySignature];
56661             }
56662             else if (elementType.flags & 128 /* StringLiteral */) {
56663                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
56664                 if (!intrinsicType) {
56665                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
56666                     return ts.emptyArray;
56667                 }
56668                 else {
56669                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
56670                     return [fakeSignature];
56671                 }
56672             }
56673             var apparentElemType = getApparentType(elementType);
56674             // Resolve the signatures, preferring constructor
56675             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
56676             if (signatures.length === 0) {
56677                 // No construct signatures, try call signatures
56678                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
56679             }
56680             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
56681                 // If each member has some combination of new/call signatures; make a union signature list for those
56682                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
56683             }
56684             return signatures;
56685         }
56686         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
56687             // 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
56688             // For example:
56689             //      var CustomTag: "h1" = "h1";
56690             //      <CustomTag> Hello World </CustomTag>
56691             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
56692             if (intrinsicElementsType !== errorType) {
56693                 var stringLiteralTypeName = type.value;
56694                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
56695                 if (intrinsicProp) {
56696                     return getTypeOfSymbol(intrinsicProp);
56697                 }
56698                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56699                 if (indexSignatureType) {
56700                     return indexSignatureType;
56701                 }
56702                 return undefined;
56703             }
56704             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
56705             return anyType;
56706         }
56707         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
56708             if (refKind === 1 /* Function */) {
56709                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56710                 if (sfcReturnConstraint) {
56711                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56712                 }
56713             }
56714             else if (refKind === 0 /* Component */) {
56715                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56716                 if (classConstraint) {
56717                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
56718                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56719                 }
56720             }
56721             else { // Mixed
56722                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56723                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56724                 if (!sfcReturnConstraint || !classConstraint) {
56725                     return;
56726                 }
56727                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
56728                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56729             }
56730             function generateInitialErrorChain() {
56731                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
56732                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
56733             }
56734         }
56735         /**
56736          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
56737          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
56738          * @param node an intrinsic JSX opening-like element
56739          */
56740         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
56741             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
56742             var links = getNodeLinks(node);
56743             if (!links.resolvedJsxElementAttributesType) {
56744                 var symbol = getIntrinsicTagSymbol(node);
56745                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
56746                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
56747                 }
56748                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
56749                     return links.resolvedJsxElementAttributesType =
56750                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
56751                 }
56752                 else {
56753                     return links.resolvedJsxElementAttributesType = errorType;
56754                 }
56755             }
56756             return links.resolvedJsxElementAttributesType;
56757         }
56758         function getJsxElementClassTypeAt(location) {
56759             var type = getJsxType(JsxNames.ElementClass, location);
56760             if (type === errorType)
56761                 return undefined;
56762             return type;
56763         }
56764         function getJsxElementTypeAt(location) {
56765             return getJsxType(JsxNames.Element, location);
56766         }
56767         function getJsxStatelessElementTypeAt(location) {
56768             var jsxElementType = getJsxElementTypeAt(location);
56769             if (jsxElementType) {
56770                 return getUnionType([jsxElementType, nullType]);
56771             }
56772         }
56773         /**
56774          * Returns all the properties of the Jsx.IntrinsicElements interface
56775          */
56776         function getJsxIntrinsicTagNamesAt(location) {
56777             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
56778             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
56779         }
56780         function checkJsxPreconditions(errorNode) {
56781             // Preconditions for using JSX
56782             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
56783                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
56784             }
56785             if (getJsxElementTypeAt(errorNode) === undefined) {
56786                 if (noImplicitAny) {
56787                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
56788                 }
56789             }
56790         }
56791         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
56792             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
56793             if (isNodeOpeningLikeElement) {
56794                 checkGrammarJsxElement(node);
56795             }
56796             checkJsxPreconditions(node);
56797             // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
56798             // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
56799             var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
56800             var reactNamespace = getJsxNamespace(node);
56801             var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
56802             var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
56803             if (reactSym) {
56804                 // Mark local symbol as referenced here because it might not have been marked
56805                 // if jsx emit was not react as there wont be error being emitted
56806                 reactSym.isReferenced = 67108863 /* All */;
56807                 // If react symbol is alias, mark it as refereced
56808                 if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
56809                     markAliasSymbolAsReferenced(reactSym);
56810                 }
56811             }
56812             if (isNodeOpeningLikeElement) {
56813                 var jsxOpeningLikeNode = node;
56814                 var sig = getResolvedSignature(jsxOpeningLikeNode);
56815                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
56816             }
56817         }
56818         /**
56819          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
56820          * is considered known if
56821          * 1. the object type is empty and the check is for assignability, or
56822          * 2. if the object type has index signatures, or
56823          * 3. if the property is actually declared in the object type
56824          *    (this means that 'toString', for example, is not usually a known property).
56825          * 4. In a union or intersection type,
56826          *    a property is considered known if it is known in any constituent type.
56827          * @param targetType a type to search a given name in
56828          * @param name a property name to search
56829          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
56830          */
56831         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
56832             if (targetType.flags & 524288 /* Object */) {
56833                 var resolved = resolveStructuredTypeMembers(targetType);
56834                 if (resolved.stringIndexInfo ||
56835                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
56836                     getPropertyOfObjectType(targetType, name) ||
56837                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
56838                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
56839                     return true;
56840                 }
56841             }
56842             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
56843                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
56844                     var t = _a[_i];
56845                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
56846                         return true;
56847                     }
56848                 }
56849             }
56850             return false;
56851         }
56852         function isExcessPropertyCheckTarget(type) {
56853             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
56854                 type.flags & 67108864 /* NonPrimitive */ ||
56855                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
56856                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
56857         }
56858         function checkJsxExpression(node, checkMode) {
56859             checkGrammarJsxExpression(node);
56860             if (node.expression) {
56861                 var type = checkExpression(node.expression, checkMode);
56862                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
56863                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
56864                 }
56865                 return type;
56866             }
56867             else {
56868                 return errorType;
56869             }
56870         }
56871         function getDeclarationNodeFlagsFromSymbol(s) {
56872             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
56873         }
56874         /**
56875          * Return whether this symbol is a member of a prototype somewhere
56876          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
56877          */
56878         function isPrototypeProperty(symbol) {
56879             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
56880                 return true;
56881             }
56882             if (ts.isInJSFile(symbol.valueDeclaration)) {
56883                 var parent = symbol.valueDeclaration.parent;
56884                 return parent && ts.isBinaryExpression(parent) &&
56885                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
56886             }
56887         }
56888         /**
56889          * Check whether the requested property access is valid.
56890          * Returns true if node is a valid property access, and false otherwise.
56891          * @param node The node to be checked.
56892          * @param isSuper True if the access is from `super.`.
56893          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
56894          * @param prop The symbol for the property being accessed.
56895          */
56896         function checkPropertyAccessibility(node, isSuper, type, prop) {
56897             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
56898             var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
56899             if (isSuper) {
56900                 // TS 1.0 spec (April 2014): 4.8.2
56901                 // - In a constructor, instance member function, instance member accessor, or
56902                 //   instance member variable initializer where this references a derived class instance,
56903                 //   a super property access is permitted and must specify a public instance member function of the base class.
56904                 // - In a static member function or static member accessor
56905                 //   where this references the constructor function object of a derived class,
56906                 //   a super property access is permitted and must specify a public static member function of the base class.
56907                 if (languageVersion < 2 /* ES2015 */) {
56908                     if (symbolHasNonMethodDeclaration(prop)) {
56909                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
56910                         return false;
56911                     }
56912                 }
56913                 if (flags & 128 /* Abstract */) {
56914                     // A method cannot be accessed in a super property access if the method is abstract.
56915                     // This error could mask a private property access error. But, a member
56916                     // cannot simultaneously be private and abstract, so this will trigger an
56917                     // additional error elsewhere.
56918                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56919                     return false;
56920                 }
56921             }
56922             // Referencing abstract properties within their own constructors is not allowed
56923             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
56924                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56925                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
56926                     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
56927                     return false;
56928                 }
56929             }
56930             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
56931                 if (!ts.getContainingClass(node)) {
56932                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56933                     return false;
56934                 }
56935                 return true;
56936             }
56937             // Public properties are otherwise accessible.
56938             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
56939                 return true;
56940             }
56941             // Property is known to be private or protected at this point
56942             // Private property is accessible if the property is within the declaring class
56943             if (flags & 8 /* Private */) {
56944                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56945                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
56946                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56947                     return false;
56948                 }
56949                 return true;
56950             }
56951             // Property is known to be protected at this point
56952             // All protected properties of a supertype are accessible in a super access
56953             if (isSuper) {
56954                 return true;
56955             }
56956             // Find the first enclosing class that has the declaring classes of the protected constituents
56957             // of the property as base classes
56958             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
56959                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
56960                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
56961             });
56962             // A protected property is accessible if the property is within the declaring class or classes derived from it
56963             if (!enclosingClass) {
56964                 // allow PropertyAccessibility if context is in function with this parameter
56965                 // static member access is disallow
56966                 var thisParameter = void 0;
56967                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
56968                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
56969                     return false;
56970                 }
56971                 var thisType = getTypeFromTypeNode(thisParameter.type);
56972                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
56973             }
56974             // No further restrictions for static properties
56975             if (flags & 32 /* Static */) {
56976                 return true;
56977             }
56978             if (type.flags & 262144 /* TypeParameter */) {
56979                 // get the original type -- represented as the type constraint of the 'this' type
56980                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
56981             }
56982             if (!type || !hasBaseType(type, enclosingClass)) {
56983                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
56984                 return false;
56985             }
56986             return true;
56987         }
56988         function getThisParameterFromNodeContext(node) {
56989             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
56990             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
56991         }
56992         function symbolHasNonMethodDeclaration(symbol) {
56993             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
56994         }
56995         function checkNonNullExpression(node) {
56996             return checkNonNullType(checkExpression(node), node);
56997         }
56998         function isNullableType(type) {
56999             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
57000         }
57001         function getNonNullableTypeIfNeeded(type) {
57002             return isNullableType(type) ? getNonNullableType(type) : type;
57003         }
57004         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
57005             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
57006                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
57007                 ts.Diagnostics.Object_is_possibly_undefined :
57008                 ts.Diagnostics.Object_is_possibly_null);
57009         }
57010         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
57011             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
57012                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
57013                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
57014                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
57015         }
57016         function checkNonNullTypeWithReporter(type, node, reportError) {
57017             if (strictNullChecks && type.flags & 2 /* Unknown */) {
57018                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
57019                 return errorType;
57020             }
57021             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
57022             if (kind) {
57023                 reportError(node, kind);
57024                 var t = getNonNullableType(type);
57025                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
57026             }
57027             return type;
57028         }
57029         function checkNonNullType(type, node) {
57030             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
57031         }
57032         function checkNonNullNonVoidType(type, node) {
57033             var nonNullType = checkNonNullType(type, node);
57034             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
57035                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
57036             }
57037             return nonNullType;
57038         }
57039         function checkPropertyAccessExpression(node) {
57040             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
57041                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
57042         }
57043         function checkPropertyAccessChain(node) {
57044             var leftType = checkExpression(node.expression);
57045             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
57046             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
57047         }
57048         function checkQualifiedName(node) {
57049             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
57050         }
57051         function isMethodAccessForCall(node) {
57052             while (node.parent.kind === 200 /* ParenthesizedExpression */) {
57053                 node = node.parent;
57054             }
57055             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
57056         }
57057         // Lookup the private identifier lexically.
57058         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
57059             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
57060                 var symbol = containingClass.symbol;
57061                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
57062                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
57063                 if (prop) {
57064                     return prop;
57065                 }
57066             }
57067         }
57068         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
57069             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
57070         }
57071         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
57072             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
57073             // Find a private identifier with the same description on the type.
57074             var propertyOnType;
57075             var properties = getPropertiesOfType(leftType);
57076             if (properties) {
57077                 ts.forEach(properties, function (symbol) {
57078                     var decl = symbol.valueDeclaration;
57079                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
57080                         propertyOnType = symbol;
57081                         return true;
57082                     }
57083                 });
57084             }
57085             var diagName = diagnosticName(right);
57086             if (propertyOnType) {
57087                 var typeValueDecl = propertyOnType.valueDeclaration;
57088                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
57089                 ts.Debug.assert(!!typeClass_1);
57090                 // We found a private identifier property with the same description.
57091                 // Either:
57092                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
57093                 // - It is an attempt to access the private identifier outside of the class.
57094                 if (lexicallyScopedIdentifier) {
57095                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
57096                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
57097                     ts.Debug.assert(!!lexicalClass);
57098                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
57099                         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));
57100                         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));
57101                         return true;
57102                     }
57103                 }
57104                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
57105                 return true;
57106             }
57107             return false;
57108         }
57109         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
57110             var parentSymbol = getNodeLinks(left).resolvedSymbol;
57111             var assignmentKind = ts.getAssignmentTargetKind(node);
57112             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
57113             if (ts.isPrivateIdentifier(right)) {
57114                 checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
57115             }
57116             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
57117             var prop;
57118             if (ts.isPrivateIdentifier(right)) {
57119                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
57120                 if (isAnyLike) {
57121                     if (lexicallyScopedSymbol) {
57122                         return apparentType;
57123                     }
57124                     if (!ts.getContainingClass(right)) {
57125                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
57126                         return anyType;
57127                     }
57128                 }
57129                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
57130                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
57131                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
57132                     return errorType;
57133                 }
57134             }
57135             else {
57136                 if (isAnyLike) {
57137                     if (ts.isIdentifier(left) && parentSymbol) {
57138                         markAliasReferenced(parentSymbol, node);
57139                     }
57140                     return apparentType;
57141                 }
57142                 prop = getPropertyOfType(apparentType, right.escapedText);
57143             }
57144             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
57145                 markAliasReferenced(parentSymbol, node);
57146             }
57147             var propType;
57148             if (!prop) {
57149                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
57150                 if (!(indexInfo && indexInfo.type)) {
57151                     if (isJSLiteralType(leftType)) {
57152                         return anyType;
57153                     }
57154                     if (leftType.symbol === globalThisSymbol) {
57155                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
57156                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
57157                         }
57158                         else if (noImplicitAny) {
57159                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
57160                         }
57161                         return anyType;
57162                     }
57163                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
57164                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
57165                     }
57166                     return errorType;
57167                 }
57168                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
57169                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
57170                 }
57171                 propType = indexInfo.type;
57172             }
57173             else {
57174                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
57175                 markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
57176                 getNodeLinks(node).resolvedSymbol = prop;
57177                 checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
57178                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
57179                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
57180                     return errorType;
57181                 }
57182                 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
57183             }
57184             return getFlowTypeOfAccessExpression(node, prop, propType, right);
57185         }
57186         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
57187             // Only compute control flow type if this is a property access expression that isn't an
57188             // assignment target, and the referenced property was declared as a variable, property,
57189             // accessor, or optional method.
57190             var assignmentKind = ts.getAssignmentTargetKind(node);
57191             if (!ts.isAccessExpression(node) ||
57192                 assignmentKind === 1 /* Definite */ ||
57193                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
57194                 return propType;
57195             }
57196             // If strict null checks and strict property initialization checks are enabled, if we have
57197             // a this.xxx property access, if the property is an instance property without an initializer,
57198             // and if we are in a constructor of the same class as the property declaration, assume that
57199             // the property is uninitialized at the top of the control flow.
57200             var assumeUninitialized = false;
57201             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
57202                 var declaration = prop && prop.valueDeclaration;
57203                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
57204                     var flowContainer = getControlFlowContainer(node);
57205                     if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
57206                         assumeUninitialized = true;
57207                     }
57208                 }
57209             }
57210             else if (strictNullChecks && prop && prop.valueDeclaration &&
57211                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
57212                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
57213                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
57214                 assumeUninitialized = true;
57215             }
57216             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
57217             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
57218                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
57219                 // Return the declared type to reduce follow-on errors
57220                 return propType;
57221             }
57222             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
57223         }
57224         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
57225             var valueDeclaration = prop.valueDeclaration;
57226             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
57227                 return;
57228             }
57229             var diagnosticMessage;
57230             var declarationName = ts.idText(right);
57231             if (isInPropertyInitializer(node)
57232                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
57233                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
57234                 && !isPropertyDeclaredInAncestorClass(prop)) {
57235                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
57236             }
57237             else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
57238                 node.parent.kind !== 169 /* TypeReference */ &&
57239                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
57240                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
57241                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
57242             }
57243             if (diagnosticMessage) {
57244                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
57245             }
57246         }
57247         function isInPropertyInitializer(node) {
57248             return !!ts.findAncestor(node, function (node) {
57249                 switch (node.kind) {
57250                     case 159 /* PropertyDeclaration */:
57251                         return true;
57252                     case 281 /* PropertyAssignment */:
57253                     case 161 /* MethodDeclaration */:
57254                     case 163 /* GetAccessor */:
57255                     case 164 /* SetAccessor */:
57256                     case 283 /* SpreadAssignment */:
57257                     case 154 /* ComputedPropertyName */:
57258                     case 221 /* TemplateSpan */:
57259                     case 276 /* JsxExpression */:
57260                     case 273 /* JsxAttribute */:
57261                     case 274 /* JsxAttributes */:
57262                     case 275 /* JsxSpreadAttribute */:
57263                     case 268 /* JsxOpeningElement */:
57264                     case 216 /* ExpressionWithTypeArguments */:
57265                     case 279 /* HeritageClause */:
57266                         return false;
57267                     default:
57268                         return ts.isExpressionNode(node) ? false : "quit";
57269                 }
57270             });
57271         }
57272         /**
57273          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
57274          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
57275          */
57276         function isPropertyDeclaredInAncestorClass(prop) {
57277             if (!(prop.parent.flags & 32 /* Class */)) {
57278                 return false;
57279             }
57280             var classType = getTypeOfSymbol(prop.parent);
57281             while (true) {
57282                 classType = classType.symbol && getSuperClass(classType);
57283                 if (!classType) {
57284                     return false;
57285                 }
57286                 var superProperty = getPropertyOfType(classType, prop.escapedName);
57287                 if (superProperty && superProperty.valueDeclaration) {
57288                     return true;
57289                 }
57290             }
57291         }
57292         function getSuperClass(classType) {
57293             var x = getBaseTypes(classType);
57294             if (x.length === 0) {
57295                 return undefined;
57296             }
57297             return getIntersectionType(x);
57298         }
57299         function reportNonexistentProperty(propNode, containingType) {
57300             var errorInfo;
57301             var relatedInfo;
57302             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
57303                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
57304                     var subtype = _a[_i];
57305                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
57306                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
57307                         break;
57308                     }
57309                 }
57310             }
57311             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
57312                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57313             }
57314             else {
57315                 var promisedType = getPromisedTypeOfPromise(containingType);
57316                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
57317                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57318                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
57319                 }
57320                 else {
57321                     var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
57322                     if (suggestion !== undefined) {
57323                         var suggestedName = ts.symbolName(suggestion);
57324                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
57325                         relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
57326                     }
57327                     else {
57328                         errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57329                     }
57330                 }
57331             }
57332             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
57333             if (relatedInfo) {
57334                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
57335             }
57336             diagnostics.add(resultDiagnostic);
57337         }
57338         function typeHasStaticProperty(propName, containingType) {
57339             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
57340             return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
57341         }
57342         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
57343             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
57344         }
57345         function getSuggestionForNonexistentProperty(name, containingType) {
57346             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
57347             return suggestion && ts.symbolName(suggestion);
57348         }
57349         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
57350             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
57351             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
57352                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
57353                 var symbol = getSymbol(symbols, name, meaning);
57354                 // 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
57355                 // So the table *contains* `x` but `x` isn't actually in scope.
57356                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
57357                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
57358             });
57359             return result;
57360         }
57361         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
57362             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
57363             return symbolResult && ts.symbolName(symbolResult);
57364         }
57365         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
57366             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
57367         }
57368         function getSuggestionForNonexistentExport(name, targetModule) {
57369             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
57370             return suggestion && ts.symbolName(suggestion);
57371         }
57372         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
57373             // check if object type has setter or getter
57374             function hasProp(name) {
57375                 var prop = getPropertyOfObjectType(objectType, name);
57376                 if (prop) {
57377                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
57378                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
57379                 }
57380                 return false;
57381             }
57382             ;
57383             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
57384             if (!hasProp(suggestedMethod)) {
57385                 return undefined;
57386             }
57387             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
57388             if (suggestion === undefined) {
57389                 suggestion = suggestedMethod;
57390             }
57391             else {
57392                 suggestion += "." + suggestedMethod;
57393             }
57394             return suggestion;
57395         }
57396         /**
57397          * 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.
57398          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
57399          *
57400          * If there is a candidate that's the same except for case, return that.
57401          * If there is a candidate that's within one edit of the name, return that.
57402          * Otherwise, return the candidate with the smallest Levenshtein distance,
57403          *    except for candidates:
57404          *      * With no name
57405          *      * Whose meaning doesn't match the `meaning` parameter.
57406          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
57407          *      * Whose levenshtein distance is more than 0.4 of the length of the name
57408          *        (0.4 allows 1 substitution/transposition for every 5 characters,
57409          *         and 1 insertion/deletion at 3 characters)
57410          */
57411         function getSpellingSuggestionForName(name, symbols, meaning) {
57412             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
57413             function getCandidateName(candidate) {
57414                 var candidateName = ts.symbolName(candidate);
57415                 if (ts.startsWith(candidateName, "\"")) {
57416                     return undefined;
57417                 }
57418                 if (candidate.flags & meaning) {
57419                     return candidateName;
57420                 }
57421                 if (candidate.flags & 2097152 /* Alias */) {
57422                     var alias = tryResolveAlias(candidate);
57423                     if (alias && alias.flags & meaning) {
57424                         return candidateName;
57425                     }
57426                 }
57427                 return undefined;
57428             }
57429         }
57430         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
57431             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
57432             if (!valueDeclaration) {
57433                 return;
57434             }
57435             var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
57436             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
57437             if (!hasPrivateModifier && !hasPrivateIdentifier) {
57438                 return;
57439             }
57440             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
57441                 return;
57442             }
57443             if (isThisAccess) {
57444                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
57445                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
57446                 if (containingMethod && containingMethod.symbol === prop) {
57447                     return;
57448                 }
57449             }
57450             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
57451         }
57452         function isValidPropertyAccess(node, propertyName) {
57453             switch (node.kind) {
57454                 case 194 /* PropertyAccessExpression */:
57455                     return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
57456                 case 153 /* QualifiedName */:
57457                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
57458                 case 188 /* ImportType */:
57459                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
57460             }
57461         }
57462         function isValidPropertyAccessForCompletions(node, type, property) {
57463             return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
57464             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
57465         }
57466         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
57467             if (type === errorType || isTypeAny(type)) {
57468                 return true;
57469             }
57470             var prop = getPropertyOfType(type, propertyName);
57471             if (prop) {
57472                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
57473                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
57474                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
57475                 }
57476                 return checkPropertyAccessibility(node, isSuper, type, prop);
57477             }
57478             // In js files properties of unions are allowed in completion
57479             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
57480         }
57481         /**
57482          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
57483          */
57484         function getForInVariableSymbol(node) {
57485             var initializer = node.initializer;
57486             if (initializer.kind === 243 /* VariableDeclarationList */) {
57487                 var variable = initializer.declarations[0];
57488                 if (variable && !ts.isBindingPattern(variable.name)) {
57489                     return getSymbolOfNode(variable);
57490                 }
57491             }
57492             else if (initializer.kind === 75 /* Identifier */) {
57493                 return getResolvedSymbol(initializer);
57494             }
57495             return undefined;
57496         }
57497         /**
57498          * Return true if the given type is considered to have numeric property names.
57499          */
57500         function hasNumericPropertyNames(type) {
57501             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
57502         }
57503         /**
57504          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
57505          * that references a for-in variable for an object with numeric property names.
57506          */
57507         function isForInVariableForNumericPropertyNames(expr) {
57508             var e = ts.skipParentheses(expr);
57509             if (e.kind === 75 /* Identifier */) {
57510                 var symbol = getResolvedSymbol(e);
57511                 if (symbol.flags & 3 /* Variable */) {
57512                     var child = expr;
57513                     var node = expr.parent;
57514                     while (node) {
57515                         if (node.kind === 231 /* ForInStatement */ &&
57516                             child === node.statement &&
57517                             getForInVariableSymbol(node) === symbol &&
57518                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
57519                             return true;
57520                         }
57521                         child = node;
57522                         node = node.parent;
57523                     }
57524                 }
57525             }
57526             return false;
57527         }
57528         function checkIndexedAccess(node) {
57529             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
57530                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
57531         }
57532         function checkElementAccessChain(node) {
57533             var exprType = checkExpression(node.expression);
57534             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
57535             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
57536         }
57537         function checkElementAccessExpression(node, exprType) {
57538             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
57539             var indexExpression = node.argumentExpression;
57540             var indexType = checkExpression(indexExpression);
57541             if (objectType === errorType || objectType === silentNeverType) {
57542                 return objectType;
57543             }
57544             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
57545                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
57546                 return errorType;
57547             }
57548             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
57549             var accessFlags = ts.isAssignmentTarget(node) ?
57550                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
57551                 0 /* None */;
57552             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
57553             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
57554         }
57555         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
57556             if (expressionType === errorType) {
57557                 // There is already an error, so no need to report one.
57558                 return false;
57559             }
57560             if (!ts.isWellKnownSymbolSyntactically(expression)) {
57561                 return false;
57562             }
57563             // Make sure the property type is the primitive symbol type
57564             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
57565                 if (reportError) {
57566                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
57567                 }
57568                 return false;
57569             }
57570             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
57571             // global Symbol object
57572             var leftHandSide = expression.expression;
57573             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
57574             if (!leftHandSideSymbol) {
57575                 return false;
57576             }
57577             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
57578             if (!globalESSymbol) {
57579                 // Already errored when we tried to look up the symbol
57580                 return false;
57581             }
57582             if (leftHandSideSymbol !== globalESSymbol) {
57583                 if (reportError) {
57584                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
57585                 }
57586                 return false;
57587             }
57588             return true;
57589         }
57590         function callLikeExpressionMayHaveTypeArguments(node) {
57591             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
57592         }
57593         function resolveUntypedCall(node) {
57594             if (callLikeExpressionMayHaveTypeArguments(node)) {
57595                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
57596                 // This gets us diagnostics for the type arguments and marks them as referenced.
57597                 ts.forEach(node.typeArguments, checkSourceElement);
57598             }
57599             if (node.kind === 198 /* TaggedTemplateExpression */) {
57600                 checkExpression(node.template);
57601             }
57602             else if (ts.isJsxOpeningLikeElement(node)) {
57603                 checkExpression(node.attributes);
57604             }
57605             else if (node.kind !== 157 /* Decorator */) {
57606                 ts.forEach(node.arguments, function (argument) {
57607                     checkExpression(argument);
57608                 });
57609             }
57610             return anySignature;
57611         }
57612         function resolveErrorCall(node) {
57613             resolveUntypedCall(node);
57614             return unknownSignature;
57615         }
57616         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
57617         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
57618         // A nit here is that we reorder only signatures that belong to the same symbol,
57619         // so order how inherited signatures are processed is still preserved.
57620         // interface A { (x: string): void }
57621         // interface B extends A { (x: 'foo'): string }
57622         // const b: B;
57623         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
57624         function reorderCandidates(signatures, result, callChainFlags) {
57625             var lastParent;
57626             var lastSymbol;
57627             var cutoffIndex = 0;
57628             var index;
57629             var specializedIndex = -1;
57630             var spliceIndex;
57631             ts.Debug.assert(!result.length);
57632             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
57633                 var signature = signatures_7[_i];
57634                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
57635                 var parent = signature.declaration && signature.declaration.parent;
57636                 if (!lastSymbol || symbol === lastSymbol) {
57637                     if (lastParent && parent === lastParent) {
57638                         index = index + 1;
57639                     }
57640                     else {
57641                         lastParent = parent;
57642                         index = cutoffIndex;
57643                     }
57644                 }
57645                 else {
57646                     // current declaration belongs to a different symbol
57647                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
57648                     index = cutoffIndex = result.length;
57649                     lastParent = parent;
57650                 }
57651                 lastSymbol = symbol;
57652                 // specialized signatures always need to be placed before non-specialized signatures regardless
57653                 // of the cutoff position; see GH#1133
57654                 if (signatureHasLiteralTypes(signature)) {
57655                     specializedIndex++;
57656                     spliceIndex = specializedIndex;
57657                     // The cutoff index always needs to be greater than or equal to the specialized signature index
57658                     // in order to prevent non-specialized signatures from being added before a specialized
57659                     // signature.
57660                     cutoffIndex++;
57661                 }
57662                 else {
57663                     spliceIndex = index;
57664                 }
57665                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
57666             }
57667         }
57668         function isSpreadArgument(arg) {
57669             return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
57670         }
57671         function getSpreadArgumentIndex(args) {
57672             return ts.findIndex(args, isSpreadArgument);
57673         }
57674         function acceptsVoid(t) {
57675             return !!(t.flags & 16384 /* Void */);
57676         }
57677         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
57678             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
57679             var argCount;
57680             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
57681             var effectiveParameterCount = getParameterCount(signature);
57682             var effectiveMinimumArguments = getMinArgumentCount(signature);
57683             if (node.kind === 198 /* TaggedTemplateExpression */) {
57684                 argCount = args.length;
57685                 if (node.template.kind === 211 /* TemplateExpression */) {
57686                     // If a tagged template expression lacks a tail literal, the call is incomplete.
57687                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
57688                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
57689                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
57690                 }
57691                 else {
57692                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
57693                     // then this might actually turn out to be a TemplateHead in the future;
57694                     // so we consider the call to be incomplete.
57695                     var templateLiteral = node.template;
57696                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
57697                     callIsIncomplete = !!templateLiteral.isUnterminated;
57698                 }
57699             }
57700             else if (node.kind === 157 /* Decorator */) {
57701                 argCount = getDecoratorArgumentCount(node, signature);
57702             }
57703             else if (ts.isJsxOpeningLikeElement(node)) {
57704                 callIsIncomplete = node.attributes.end === node.end;
57705                 if (callIsIncomplete) {
57706                     return true;
57707                 }
57708                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
57709                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
57710                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
57711             }
57712             else {
57713                 if (!node.arguments) {
57714                     // This only happens when we have something of the form: 'new C'
57715                     ts.Debug.assert(node.kind === 197 /* NewExpression */);
57716                     return getMinArgumentCount(signature) === 0;
57717                 }
57718                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
57719                 // If we are missing the close parenthesis, the call is incomplete.
57720                 callIsIncomplete = node.arguments.end === node.end;
57721                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
57722                 var spreadArgIndex = getSpreadArgumentIndex(args);
57723                 if (spreadArgIndex >= 0) {
57724                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
57725                 }
57726             }
57727             // Too many arguments implies incorrect arity.
57728             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
57729                 return false;
57730             }
57731             // If the call is incomplete, we should skip the lower bound check.
57732             // JSX signatures can have extra parameters provided by the library which we don't check
57733             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
57734                 return true;
57735             }
57736             for (var i = argCount; i < effectiveMinimumArguments; i++) {
57737                 var type = getTypeAtPosition(signature, i);
57738                 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
57739                     return false;
57740                 }
57741             }
57742             return true;
57743         }
57744         function hasCorrectTypeArgumentArity(signature, typeArguments) {
57745             // If the user supplied type arguments, but the number of type arguments does not match
57746             // the declared number of type parameters, the call has an incorrect arity.
57747             var numTypeParameters = ts.length(signature.typeParameters);
57748             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
57749             return !ts.some(typeArguments) ||
57750                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
57751         }
57752         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
57753         function getSingleCallSignature(type) {
57754             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
57755         }
57756         function getSingleCallOrConstructSignature(type) {
57757             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
57758                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
57759         }
57760         function getSingleSignature(type, kind, allowMembers) {
57761             if (type.flags & 524288 /* Object */) {
57762                 var resolved = resolveStructuredTypeMembers(type);
57763                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
57764                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
57765                         return resolved.callSignatures[0];
57766                     }
57767                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
57768                         return resolved.constructSignatures[0];
57769                     }
57770                 }
57771             }
57772             return undefined;
57773         }
57774         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
57775         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
57776             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
57777             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
57778             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
57779             // for T but leave it possible to later infer '[any]' back to A.
57780             var restType = getEffectiveRestType(contextualSignature);
57781             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
57782             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
57783             applyToParameterTypes(sourceSignature, signature, function (source, target) {
57784                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
57785                 inferTypes(context.inferences, source, target);
57786             });
57787             if (!inferenceContext) {
57788                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
57789                     inferTypes(context.inferences, source, target, 32 /* ReturnType */);
57790                 });
57791             }
57792             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
57793         }
57794         function inferJsxTypeArguments(node, signature, checkMode, context) {
57795             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57796             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
57797             inferTypes(context.inferences, checkAttrType, paramType);
57798             return getInferredTypes(context);
57799         }
57800         function inferTypeArguments(node, signature, args, checkMode, context) {
57801             if (ts.isJsxOpeningLikeElement(node)) {
57802                 return inferJsxTypeArguments(node, signature, checkMode, context);
57803             }
57804             // If a contextual type is available, infer from that type to the return type of the call expression. For
57805             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
57806             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
57807             // return type of 'wrap'.
57808             if (node.kind !== 157 /* Decorator */) {
57809                 var contextualType = getContextualType(node);
57810                 if (contextualType) {
57811                     // We clone the inference context to avoid disturbing a resolution in progress for an
57812                     // outer call expression. Effectively we just want a snapshot of whatever has been
57813                     // inferred for any outer call expression so far.
57814                     var outerContext = getInferenceContext(node);
57815                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
57816                     var instantiatedType = instantiateType(contextualType, outerMapper);
57817                     // If the contextual type is a generic function type with a single call signature, we
57818                     // instantiate the type with its own type parameters and type arguments. This ensures that
57819                     // the type parameters are not erased to type any during type inference such that they can
57820                     // be inferred as actual types from the contextual type. For example:
57821                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
57822                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
57823                     // Above, the type of the 'value' parameter is inferred to be 'A'.
57824                     var contextualSignature = getSingleCallSignature(instantiatedType);
57825                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
57826                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
57827                         instantiatedType;
57828                     var inferenceTargetType = getReturnTypeOfSignature(signature);
57829                     // Inferences made from return types have lower priority than all other inferences.
57830                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
57831                     // Create a type mapper for instantiating generic contextual types using the inferences made
57832                     // from the return type. We need a separate inference pass here because (a) instantiation of
57833                     // the source type uses the outer context's return mapper (which excludes inferences made from
57834                     // outer arguments), and (b) we don't want any further inferences going into this context.
57835                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
57836                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
57837                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
57838                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
57839                 }
57840             }
57841             var thisType = getThisTypeOfSignature(signature);
57842             if (thisType) {
57843                 var thisArgumentNode = getThisArgumentOfCall(node);
57844                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
57845                 inferTypes(context.inferences, thisArgumentType, thisType);
57846             }
57847             var restType = getNonArrayRestType(signature);
57848             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57849             for (var i = 0; i < argCount; i++) {
57850                 var arg = args[i];
57851                 if (arg.kind !== 215 /* OmittedExpression */) {
57852                     var paramType = getTypeAtPosition(signature, i);
57853                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
57854                     inferTypes(context.inferences, argType, paramType);
57855                 }
57856             }
57857             if (restType) {
57858                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
57859                 inferTypes(context.inferences, spreadType, restType);
57860             }
57861             return getInferredTypes(context);
57862         }
57863         function getArrayifiedType(type) {
57864             return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
57865                 type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
57866                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
57867                         createArrayType(getIndexedAccessType(type, numberType));
57868         }
57869         function getSpreadArgumentType(args, index, argCount, restType, context) {
57870             if (index >= argCount - 1) {
57871                 var arg = args[argCount - 1];
57872                 if (isSpreadArgument(arg)) {
57873                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
57874                     // and the argument are ...x forms.
57875                     return arg.kind === 220 /* SyntheticExpression */ ?
57876                         createArrayType(arg.type) :
57877                         getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
57878                 }
57879             }
57880             var types = [];
57881             var spreadIndex = -1;
57882             for (var i = index; i < argCount; i++) {
57883                 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
57884                 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
57885                 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
57886                     spreadIndex = i - index;
57887                 }
57888                 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
57889                 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
57890             }
57891             return spreadIndex < 0 ?
57892                 createTupleType(types) :
57893                 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
57894         }
57895         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
57896             var isJavascript = ts.isInJSFile(signature.declaration);
57897             var typeParameters = signature.typeParameters;
57898             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
57899             var mapper;
57900             for (var i = 0; i < typeArgumentNodes.length; i++) {
57901                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
57902                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
57903                 if (constraint) {
57904                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
57905                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
57906                     if (!mapper) {
57907                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
57908                     }
57909                     var typeArgument = typeArgumentTypes[i];
57910                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
57911                         return undefined;
57912                     }
57913                 }
57914             }
57915             return typeArgumentTypes;
57916         }
57917         function getJsxReferenceKind(node) {
57918             if (isJsxIntrinsicIdentifier(node.tagName)) {
57919                 return 2 /* Mixed */;
57920             }
57921             var tagType = getApparentType(checkExpression(node.tagName));
57922             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
57923                 return 0 /* Component */;
57924             }
57925             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
57926                 return 1 /* Function */;
57927             }
57928             return 2 /* Mixed */;
57929         }
57930         /**
57931          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
57932          * @param node a JSX opening-like element we are trying to figure its call signature
57933          * @param signature a candidate signature we are trying whether it is a call signature
57934          * @param relation a relationship to check parameter and argument type
57935          */
57936         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
57937             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
57938             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
57939             // can be specified by users through attributes property.
57940             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57941             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
57942             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
57943             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57944             function checkTagNameDoesNotExpectTooManyArguments() {
57945                 var _a;
57946                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
57947                 if (!tagType) {
57948                     return true;
57949                 }
57950                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
57951                 if (!ts.length(tagCallSignatures)) {
57952                     return true;
57953                 }
57954                 var factory = getJsxFactoryEntity(node);
57955                 if (!factory) {
57956                     return true;
57957                 }
57958                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
57959                 if (!factorySymbol) {
57960                     return true;
57961                 }
57962                 var factoryType = getTypeOfSymbol(factorySymbol);
57963                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
57964                 if (!ts.length(callSignatures)) {
57965                     return true;
57966                 }
57967                 var hasFirstParamSignatures = false;
57968                 var maxParamCount = 0;
57969                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
57970                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
57971                     var sig = callSignatures_1[_i];
57972                     var firstparam = getTypeAtPosition(sig, 0);
57973                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
57974                     if (!ts.length(signaturesOfParam))
57975                         continue;
57976                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
57977                         var paramSig = signaturesOfParam_1[_b];
57978                         hasFirstParamSignatures = true;
57979                         if (hasEffectiveRestParameter(paramSig)) {
57980                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
57981                         }
57982                         var paramCount = getParameterCount(paramSig);
57983                         if (paramCount > maxParamCount) {
57984                             maxParamCount = paramCount;
57985                         }
57986                     }
57987                 }
57988                 if (!hasFirstParamSignatures) {
57989                     // Not a single signature had a first parameter which expected a signature - for back compat, and
57990                     // to guard against generic factories which won't have signatures directly, do not error
57991                     return true;
57992                 }
57993                 var absoluteMinArgCount = Infinity;
57994                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
57995                     var tagSig = tagCallSignatures_1[_c];
57996                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
57997                     if (tagRequiredArgCount < absoluteMinArgCount) {
57998                         absoluteMinArgCount = tagRequiredArgCount;
57999                     }
58000                 }
58001                 if (absoluteMinArgCount <= maxParamCount) {
58002                     return true; // some signature accepts the number of arguments the function component provides
58003                 }
58004                 if (reportErrors) {
58005                     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);
58006                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
58007                     if (tagNameDeclaration) {
58008                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
58009                     }
58010                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
58011                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58012                     }
58013                     if (!errorOutputContainer.skipLogging) {
58014                         diagnostics.add(diag);
58015                     }
58016                 }
58017                 return false;
58018             }
58019         }
58020         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
58021             var errorOutputContainer = { errors: undefined, skipLogging: true };
58022             if (ts.isJsxOpeningLikeElement(node)) {
58023                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
58024                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
58025                     return errorOutputContainer.errors || ts.emptyArray;
58026                 }
58027                 return undefined;
58028             }
58029             var thisType = getThisTypeOfSignature(signature);
58030             if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
58031                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
58032                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
58033                 // If the expression is a new expression, then the check is skipped.
58034                 var thisArgumentNode = getThisArgumentOfCall(node);
58035                 var thisArgumentType = void 0;
58036                 if (thisArgumentNode) {
58037                     thisArgumentType = checkExpression(thisArgumentNode);
58038                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
58039                         thisArgumentType = getNonNullableType(thisArgumentType);
58040                     }
58041                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
58042                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
58043                     }
58044                 }
58045                 else {
58046                     thisArgumentType = voidType;
58047                 }
58048                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
58049                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
58050                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
58051                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
58052                     return errorOutputContainer.errors || ts.emptyArray;
58053                 }
58054             }
58055             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
58056             var restType = getNonArrayRestType(signature);
58057             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
58058             for (var i = 0; i < argCount; i++) {
58059                 var arg = args[i];
58060                 if (arg.kind !== 215 /* OmittedExpression */) {
58061                     var paramType = getTypeAtPosition(signature, i);
58062                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
58063                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
58064                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
58065                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
58066                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
58067                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
58068                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
58069                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
58070                         return errorOutputContainer.errors || ts.emptyArray;
58071                     }
58072                 }
58073             }
58074             if (restType) {
58075                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
58076                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
58077                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
58078                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
58079                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
58080                     return errorOutputContainer.errors || ts.emptyArray;
58081                 }
58082             }
58083             return undefined;
58084             function maybeAddMissingAwaitInfo(errorNode, source, target) {
58085                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
58086                     // Bail if target is Promise-like---something else is wrong
58087                     if (getAwaitedTypeOfPromise(target)) {
58088                         return;
58089                     }
58090                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
58091                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
58092                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
58093                     }
58094                 }
58095             }
58096         }
58097         /**
58098          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
58099          */
58100         function getThisArgumentOfCall(node) {
58101             if (node.kind === 196 /* CallExpression */) {
58102                 var callee = ts.skipOuterExpressions(node.expression);
58103                 if (ts.isAccessExpression(callee)) {
58104                     return callee.expression;
58105                 }
58106             }
58107         }
58108         function createSyntheticExpression(parent, type, isSpread) {
58109             var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
58110             result.parent = parent;
58111             result.type = type;
58112             result.isSpread = isSpread || false;
58113             return result;
58114         }
58115         /**
58116          * Returns the effective arguments for an expression that works like a function invocation.
58117          */
58118         function getEffectiveCallArguments(node) {
58119             if (node.kind === 198 /* TaggedTemplateExpression */) {
58120                 var template = node.template;
58121                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
58122                 if (template.kind === 211 /* TemplateExpression */) {
58123                     ts.forEach(template.templateSpans, function (span) {
58124                         args_3.push(span.expression);
58125                     });
58126                 }
58127                 return args_3;
58128             }
58129             if (node.kind === 157 /* Decorator */) {
58130                 return getEffectiveDecoratorArguments(node);
58131             }
58132             if (ts.isJsxOpeningLikeElement(node)) {
58133                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
58134             }
58135             var args = node.arguments || ts.emptyArray;
58136             var length = args.length;
58137             if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
58138                 // We have a spread argument in the last position and no other spread arguments. If the type
58139                 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
58140                 // call checkExpressionCached because spread expressions never have a contextual type.
58141                 var spreadArgument_1 = args[length - 1];
58142                 var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
58143                 if (isTupleType(type)) {
58144                     var typeArguments = getTypeArguments(type);
58145                     var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
58146                     var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
58147                     return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
58148                 }
58149             }
58150             return args;
58151         }
58152         /**
58153          * Returns the synthetic argument list for a decorator invocation.
58154          */
58155         function getEffectiveDecoratorArguments(node) {
58156             var parent = node.parent;
58157             var expr = node.expression;
58158             switch (parent.kind) {
58159                 case 245 /* ClassDeclaration */:
58160                 case 214 /* ClassExpression */:
58161                     // For a class decorator, the `target` is the type of the class (e.g. the
58162                     // "static" or "constructor" side of the class).
58163                     return [
58164                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
58165                     ];
58166                 case 156 /* Parameter */:
58167                     // A parameter declaration decorator will have three arguments (see
58168                     // `ParameterDecorator` in core.d.ts).
58169                     var func = parent.parent;
58170                     return [
58171                         createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
58172                         createSyntheticExpression(expr, anyType),
58173                         createSyntheticExpression(expr, numberType)
58174                     ];
58175                 case 159 /* PropertyDeclaration */:
58176                 case 161 /* MethodDeclaration */:
58177                 case 163 /* GetAccessor */:
58178                 case 164 /* SetAccessor */:
58179                     // A method or accessor declaration decorator will have two or three arguments (see
58180                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
58181                     // for ES3, we will only pass two arguments.
58182                     var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
58183                     return [
58184                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
58185                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
58186                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
58187                     ];
58188             }
58189             return ts.Debug.fail();
58190         }
58191         /**
58192          * Returns the argument count for a decorator node that works like a function invocation.
58193          */
58194         function getDecoratorArgumentCount(node, signature) {
58195             switch (node.parent.kind) {
58196                 case 245 /* ClassDeclaration */:
58197                 case 214 /* ClassExpression */:
58198                     return 1;
58199                 case 159 /* PropertyDeclaration */:
58200                     return 2;
58201                 case 161 /* MethodDeclaration */:
58202                 case 163 /* GetAccessor */:
58203                 case 164 /* SetAccessor */:
58204                     // For ES3 or decorators with only two parameters we supply only two arguments
58205                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
58206                 case 156 /* Parameter */:
58207                     return 3;
58208                 default:
58209                     return ts.Debug.fail();
58210             }
58211         }
58212         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
58213             var start;
58214             var length;
58215             var sourceFile = ts.getSourceFileOfNode(node);
58216             if (ts.isPropertyAccessExpression(node.expression)) {
58217                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
58218                 start = nameSpan.start;
58219                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
58220             }
58221             else {
58222                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
58223                 start = expressionSpan.start;
58224                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
58225             }
58226             return { start: start, length: length, sourceFile: sourceFile };
58227         }
58228         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
58229             if (ts.isCallExpression(node)) {
58230                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
58231                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
58232             }
58233             else {
58234                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
58235             }
58236         }
58237         function getArgumentArityError(node, signatures, args) {
58238             var min = Number.POSITIVE_INFINITY;
58239             var max = Number.NEGATIVE_INFINITY;
58240             var belowArgCount = Number.NEGATIVE_INFINITY;
58241             var aboveArgCount = Number.POSITIVE_INFINITY;
58242             var argCount = args.length;
58243             var closestSignature;
58244             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
58245                 var sig = signatures_8[_i];
58246                 var minCount = getMinArgumentCount(sig);
58247                 var maxCount = getParameterCount(sig);
58248                 if (minCount < argCount && minCount > belowArgCount)
58249                     belowArgCount = minCount;
58250                 if (argCount < maxCount && maxCount < aboveArgCount)
58251                     aboveArgCount = maxCount;
58252                 if (minCount < min) {
58253                     min = minCount;
58254                     closestSignature = sig;
58255                 }
58256                 max = Math.max(max, maxCount);
58257             }
58258             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
58259             var paramRange = hasRestParameter ? min :
58260                 min < max ? min + "-" + max :
58261                     min;
58262             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
58263             if (argCount <= max && hasSpreadArgument) {
58264                 argCount--;
58265             }
58266             var spanArray;
58267             var related;
58268             var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
58269                 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
58270                     ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
58271             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
58272                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
58273                 if (paramDecl) {
58274                     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);
58275                 }
58276             }
58277             if (min < argCount && argCount < max) {
58278                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
58279             }
58280             if (!hasSpreadArgument && argCount < min) {
58281                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
58282                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
58283             }
58284             if (hasRestParameter || hasSpreadArgument) {
58285                 spanArray = ts.createNodeArray(args);
58286                 if (hasSpreadArgument && argCount) {
58287                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
58288                     spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
58289                 }
58290             }
58291             else {
58292                 spanArray = ts.createNodeArray(args.slice(max));
58293             }
58294             spanArray.pos = ts.first(spanArray).pos;
58295             spanArray.end = ts.last(spanArray).end;
58296             if (spanArray.end === spanArray.pos) {
58297                 spanArray.end++;
58298             }
58299             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
58300             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
58301         }
58302         function getTypeArgumentArityError(node, signatures, typeArguments) {
58303             var argCount = typeArguments.length;
58304             // No overloads exist
58305             if (signatures.length === 1) {
58306                 var sig = signatures[0];
58307                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
58308                 var max = ts.length(sig.typeParameters);
58309                 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);
58310             }
58311             // Overloads exist
58312             var belowArgCount = -Infinity;
58313             var aboveArgCount = Infinity;
58314             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
58315                 var sig = signatures_9[_i];
58316                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
58317                 var max = ts.length(sig.typeParameters);
58318                 if (min_2 > argCount) {
58319                     aboveArgCount = Math.min(aboveArgCount, min_2);
58320                 }
58321                 else if (max < argCount) {
58322                     belowArgCount = Math.max(belowArgCount, max);
58323                 }
58324             }
58325             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
58326                 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);
58327             }
58328             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
58329         }
58330         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
58331             var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
58332             var isDecorator = node.kind === 157 /* Decorator */;
58333             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
58334             var reportErrors = !candidatesOutArray;
58335             var typeArguments;
58336             if (!isDecorator) {
58337                 typeArguments = node.typeArguments;
58338                 // We already perform checking on the type arguments on the class declaration itself.
58339                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
58340                     ts.forEach(typeArguments, checkSourceElement);
58341                 }
58342             }
58343             var candidates = candidatesOutArray || [];
58344             // reorderCandidates fills up the candidates array directly
58345             reorderCandidates(signatures, candidates, callChainFlags);
58346             if (!candidates.length) {
58347                 if (reportErrors) {
58348                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
58349                 }
58350                 return resolveErrorCall(node);
58351             }
58352             var args = getEffectiveCallArguments(node);
58353             // The excludeArgument array contains true for each context sensitive argument (an argument
58354             // is context sensitive it is susceptible to a one-time permanent contextual typing).
58355             //
58356             // The idea is that we will perform type argument inference & assignability checking once
58357             // without using the susceptible parameters that are functions, and once more for those
58358             // parameters, contextually typing each as we go along.
58359             //
58360             // For a tagged template, then the first argument be 'undefined' if necessary because it
58361             // represents a TemplateStringsArray.
58362             //
58363             // For a decorator, no arguments are susceptible to contextual typing due to the fact
58364             // decorators are applied to a declaration by the emitter, and not to an expression.
58365             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
58366             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
58367             // The following variables are captured and modified by calls to chooseOverload.
58368             // If overload resolution or type argument inference fails, we want to report the
58369             // best error possible. The best error is one which says that an argument was not
58370             // assignable to a parameter. This implies that everything else about the overload
58371             // was fine. So if there is any overload that is only incorrect because of an
58372             // argument, we will report an error on that one.
58373             //
58374             //     function foo(s: string): void;
58375             //     function foo(n: number): void; // Report argument error on this overload
58376             //     function foo(): void;
58377             //     foo(true);
58378             //
58379             // If none of the overloads even made it that far, there are two possibilities.
58380             // There was a problem with type arguments for some overload, in which case
58381             // report an error on that. Or none of the overloads even had correct arity,
58382             // in which case give an arity error.
58383             //
58384             //     function foo<T extends string>(x: T): void; // Report type argument error
58385             //     function foo(): void;
58386             //     foo<number>(0);
58387             //
58388             var candidatesForArgumentError;
58389             var candidateForArgumentArityError;
58390             var candidateForTypeArgumentError;
58391             var result;
58392             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
58393             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
58394             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
58395             // Section 4.12.1:
58396             // if the candidate list contains one or more signatures for which the type of each argument
58397             // expression is a subtype of each corresponding parameter type, the return type of the first
58398             // of those signatures becomes the return type of the function call.
58399             // Otherwise, the return type of the first signature in the candidate list becomes the return
58400             // type of the function call.
58401             //
58402             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
58403             // is just important for choosing the best signature. So in the case where there is only one
58404             // signature, the subtype pass is useless. So skipping it is an optimization.
58405             if (candidates.length > 1) {
58406                 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
58407             }
58408             if (!result) {
58409                 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
58410             }
58411             if (result) {
58412                 return result;
58413             }
58414             // No signatures were applicable. Now report errors based on the last applicable signature with
58415             // no arguments excluded from assignability checks.
58416             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
58417             // skip the checkApplicableSignature check.
58418             if (reportErrors) {
58419                 if (candidatesForArgumentError) {
58420                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
58421                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
58422                         var chain_1;
58423                         if (candidatesForArgumentError.length > 3) {
58424                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
58425                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
58426                         }
58427                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
58428                         if (diags) {
58429                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
58430                                 var d = diags_1[_i];
58431                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
58432                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
58433                                 }
58434                                 diagnostics.add(d);
58435                             }
58436                         }
58437                         else {
58438                             ts.Debug.fail("No error for last overload signature");
58439                         }
58440                     }
58441                     else {
58442                         var allDiagnostics = [];
58443                         var max = 0;
58444                         var min_3 = Number.MAX_VALUE;
58445                         var minIndex = 0;
58446                         var i_1 = 0;
58447                         var _loop_17 = function (c) {
58448                             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)); };
58449                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
58450                             if (diags_2) {
58451                                 if (diags_2.length <= min_3) {
58452                                     min_3 = diags_2.length;
58453                                     minIndex = i_1;
58454                                 }
58455                                 max = Math.max(max, diags_2.length);
58456                                 allDiagnostics.push(diags_2);
58457                             }
58458                             else {
58459                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
58460                             }
58461                             i_1++;
58462                         };
58463                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
58464                             var c = candidatesForArgumentError_1[_a];
58465                             _loop_17(c);
58466                         }
58467                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
58468                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
58469                         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);
58470                         var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
58471                         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; })) {
58472                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
58473                             diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
58474                         }
58475                         else {
58476                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
58477                         }
58478                     }
58479                 }
58480                 else if (candidateForArgumentArityError) {
58481                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
58482                 }
58483                 else if (candidateForTypeArgumentError) {
58484                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
58485                 }
58486                 else {
58487                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
58488                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
58489                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
58490                     }
58491                     else if (!isDecorator) {
58492                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
58493                     }
58494                     else if (fallbackError) {
58495                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
58496                     }
58497                 }
58498             }
58499             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
58500             function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
58501                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
58502                 candidatesForArgumentError = undefined;
58503                 candidateForArgumentArityError = undefined;
58504                 candidateForTypeArgumentError = undefined;
58505                 if (isSingleNonGenericCandidate) {
58506                     var candidate = candidates[0];
58507                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58508                         return undefined;
58509                     }
58510                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58511                         candidatesForArgumentError = [candidate];
58512                         return undefined;
58513                     }
58514                     return candidate;
58515                 }
58516                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
58517                     var candidate = candidates[candidateIndex];
58518                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58519                         continue;
58520                     }
58521                     var checkCandidate = void 0;
58522                     var inferenceContext = void 0;
58523                     if (candidate.typeParameters) {
58524                         var typeArgumentTypes = void 0;
58525                         if (ts.some(typeArguments)) {
58526                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
58527                             if (!typeArgumentTypes) {
58528                                 candidateForTypeArgumentError = candidate;
58529                                 continue;
58530                             }
58531                         }
58532                         else {
58533                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58534                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
58535                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
58536                         }
58537                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58538                         // If the original signature has a generic rest type, instantiation may produce a
58539                         // signature with different arity and we need to perform another arity check.
58540                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58541                             candidateForArgumentArityError = checkCandidate;
58542                             continue;
58543                         }
58544                     }
58545                     else {
58546                         checkCandidate = candidate;
58547                     }
58548                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58549                         // Give preference to error candidates that have no rest parameters (as they are more specific)
58550                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58551                         continue;
58552                     }
58553                     if (argCheckMode) {
58554                         // If one or more context sensitive arguments were excluded, we start including
58555                         // them now (and keeping do so for any subsequent candidates) and perform a second
58556                         // round of type inference and applicability checking for this particular candidate.
58557                         argCheckMode = 0 /* Normal */;
58558                         if (inferenceContext) {
58559                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
58560                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58561                             // If the original signature has a generic rest type, instantiation may produce a
58562                             // signature with different arity and we need to perform another arity check.
58563                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58564                                 candidateForArgumentArityError = checkCandidate;
58565                                 continue;
58566                             }
58567                         }
58568                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58569                             // Give preference to error candidates that have no rest parameters (as they are more specific)
58570                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58571                             continue;
58572                         }
58573                     }
58574                     candidates[candidateIndex] = checkCandidate;
58575                     return checkCandidate;
58576                 }
58577                 return undefined;
58578             }
58579         }
58580         // No signature was applicable. We have already reported the errors for the invalid signature.
58581         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
58582             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
58583             checkNodeDeferred(node);
58584             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
58585             // Don't do this if there is a `candidatesOutArray`,
58586             // because then we want the chosen best candidate to be one of the overloads, not a combination.
58587             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
58588                 ? pickLongestCandidateSignature(node, candidates, args)
58589                 : createUnionOfSignaturesForOverloadFailure(candidates);
58590         }
58591         function createUnionOfSignaturesForOverloadFailure(candidates) {
58592             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
58593             var thisParameter;
58594             if (thisParameters.length) {
58595                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
58596             }
58597             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
58598             var parameters = [];
58599             var _loop_18 = function (i) {
58600                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
58601                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
58602                     i < s.parameters.length ? s.parameters[i] : undefined; });
58603                 ts.Debug.assert(symbols.length !== 0);
58604                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
58605             };
58606             for (var i = 0; i < maxNonRestParam; i++) {
58607                 _loop_18(i);
58608             }
58609             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
58610             var flags = 0 /* None */;
58611             if (restParameterSymbols.length !== 0) {
58612                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
58613                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
58614                 flags |= 1 /* HasRestParameter */;
58615             }
58616             if (candidates.some(signatureHasLiteralTypes)) {
58617                 flags |= 2 /* HasLiteralTypes */;
58618             }
58619             return createSignature(candidates[0].declaration, 
58620             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
58621             thisParameter, parameters, 
58622             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
58623             /*typePredicate*/ undefined, minArgumentCount, flags);
58624         }
58625         function getNumNonRestParameters(signature) {
58626             var numParams = signature.parameters.length;
58627             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
58628         }
58629         function createCombinedSymbolFromTypes(sources, types) {
58630             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
58631         }
58632         function createCombinedSymbolForOverloadFailure(sources, type) {
58633             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
58634             return createSymbolWithType(ts.first(sources), type);
58635         }
58636         function pickLongestCandidateSignature(node, candidates, args) {
58637             // Pick the longest signature. This way we can get a contextual type for cases like:
58638             //     declare function f(a: { xa: number; xb: number; }, b: number);
58639             //     f({ |
58640             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
58641             //     declare function f<T>(k: keyof T);
58642             //     f<Foo>("
58643             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
58644             var candidate = candidates[bestIndex];
58645             var typeParameters = candidate.typeParameters;
58646             if (!typeParameters) {
58647                 return candidate;
58648             }
58649             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
58650             var instantiated = typeArgumentNodes
58651                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
58652                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
58653             candidates[bestIndex] = instantiated;
58654             return instantiated;
58655         }
58656         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
58657             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
58658             while (typeArguments.length > typeParameters.length) {
58659                 typeArguments.pop();
58660             }
58661             while (typeArguments.length < typeParameters.length) {
58662                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
58663             }
58664             return typeArguments;
58665         }
58666         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
58667             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58668             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
58669             return createSignatureInstantiation(candidate, typeArgumentTypes);
58670         }
58671         function getLongestCandidateIndex(candidates, argsCount) {
58672             var maxParamsIndex = -1;
58673             var maxParams = -1;
58674             for (var i = 0; i < candidates.length; i++) {
58675                 var candidate = candidates[i];
58676                 var paramCount = getParameterCount(candidate);
58677                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
58678                     return i;
58679                 }
58680                 if (paramCount > maxParams) {
58681                     maxParams = paramCount;
58682                     maxParamsIndex = i;
58683                 }
58684             }
58685             return maxParamsIndex;
58686         }
58687         function resolveCallExpression(node, candidatesOutArray, checkMode) {
58688             if (node.expression.kind === 102 /* SuperKeyword */) {
58689                 var superType = checkSuperExpression(node.expression);
58690                 if (isTypeAny(superType)) {
58691                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
58692                         var arg = _a[_i];
58693                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
58694                     }
58695                     return anySignature;
58696                 }
58697                 if (superType !== errorType) {
58698                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
58699                     // with the type arguments specified in the extends clause.
58700                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
58701                     if (baseTypeNode) {
58702                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
58703                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
58704                     }
58705                 }
58706                 return resolveUntypedCall(node);
58707             }
58708             var callChainFlags;
58709             var funcType = checkExpression(node.expression);
58710             if (ts.isCallChain(node)) {
58711                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
58712                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
58713                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
58714                         4 /* IsInnerCallChain */;
58715                 funcType = nonOptionalType;
58716             }
58717             else {
58718                 callChainFlags = 0 /* None */;
58719             }
58720             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
58721             if (funcType === silentNeverType) {
58722                 return silentNeverSignature;
58723             }
58724             var apparentType = getApparentType(funcType);
58725             if (apparentType === errorType) {
58726                 // Another error has already been reported
58727                 return resolveErrorCall(node);
58728             }
58729             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58730             // but we are not including call signatures that may have been added to the Object or
58731             // Function interface, since they have none by default. This is a bit of a leap of faith
58732             // that the user will not add any.
58733             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58734             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58735             // TS 1.0 Spec: 4.12
58736             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
58737             // types are provided for the argument expressions, and the result is always of type Any.
58738             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58739                 // The unknownType indicates that an error already occurred (and was reported).  No
58740                 // need to report another error in this case.
58741                 if (funcType !== errorType && node.typeArguments) {
58742                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58743                 }
58744                 return resolveUntypedCall(node);
58745             }
58746             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
58747             // TypeScript employs overload resolution in typed function calls in order to support functions
58748             // with multiple call signatures.
58749             if (!callSignatures.length) {
58750                 if (numConstructSignatures) {
58751                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58752                 }
58753                 else {
58754                     var relatedInformation = void 0;
58755                     if (node.arguments.length === 1) {
58756                         var text = ts.getSourceFileOfNode(node).text;
58757                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
58758                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
58759                         }
58760                     }
58761                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
58762                 }
58763                 return resolveErrorCall(node);
58764             }
58765             // When a call to a generic function is an argument to an outer call to a generic function for which
58766             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
58767             // its contextual type to its return type, deferring the inner call processing allows the best possible
58768             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
58769             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
58770             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
58771             // If no type arguments are specified in the inner call and at least one call signature is generic and
58772             // returns a function type, we choose to defer processing. This narrowly permits function composition
58773             // operators to flow inferences through return types, but otherwise processes calls right away. We
58774             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
58775             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
58776             // from which we never make inferences).
58777             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
58778                 skippedGenericFunction(node, checkMode);
58779                 return resolvingSignature;
58780             }
58781             // If the function is explicitly marked with `@class`, then it must be constructed.
58782             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
58783                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58784                 return resolveErrorCall(node);
58785             }
58786             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
58787         }
58788         function isGenericFunctionReturningFunction(signature) {
58789             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
58790         }
58791         /**
58792          * TS 1.0 spec: 4.12
58793          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
58794          * but is a subtype of the Function interface, the call is an untyped function call.
58795          */
58796         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
58797             // We exclude union types because we may have a union of function types that happen to have no common signatures.
58798             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
58799                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
58800         }
58801         function resolveNewExpression(node, candidatesOutArray, checkMode) {
58802             if (node.arguments && languageVersion < 1 /* ES5 */) {
58803                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
58804                 if (spreadIndex >= 0) {
58805                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
58806                 }
58807             }
58808             var expressionType = checkNonNullExpression(node.expression);
58809             if (expressionType === silentNeverType) {
58810                 return silentNeverSignature;
58811             }
58812             // If expressionType's apparent type(section 3.8.1) is an object type with one or
58813             // more construct signatures, the expression is processed in the same manner as a
58814             // function call, but using the construct signatures as the initial set of candidate
58815             // signatures for overload resolution. The result type of the function call becomes
58816             // the result type of the operation.
58817             expressionType = getApparentType(expressionType);
58818             if (expressionType === errorType) {
58819                 // Another error has already been reported
58820                 return resolveErrorCall(node);
58821             }
58822             // TS 1.0 spec: 4.11
58823             // If expressionType is of type Any, Args can be any argument
58824             // list and the result of the operation is of type Any.
58825             if (isTypeAny(expressionType)) {
58826                 if (node.typeArguments) {
58827                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58828                 }
58829                 return resolveUntypedCall(node);
58830             }
58831             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58832             // but we are not including construct signatures that may have been added to the Object or
58833             // Function interface, since they have none by default. This is a bit of a leap of faith
58834             // that the user will not add any.
58835             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
58836             if (constructSignatures.length) {
58837                 if (!isConstructorAccessible(node, constructSignatures[0])) {
58838                     return resolveErrorCall(node);
58839                 }
58840                 // If the expression is a class of abstract type, then it cannot be instantiated.
58841                 // Note, only class declarations can be declared abstract.
58842                 // In the case of a merged class-module or class-interface declaration,
58843                 // only the class declaration node will have the Abstract flag set.
58844                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
58845                 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
58846                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
58847                     return resolveErrorCall(node);
58848                 }
58849                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
58850             }
58851             // If expressionType's apparent type is an object type with no construct signatures but
58852             // one or more call signatures, the expression is processed as a function call. A compile-time
58853             // error occurs if the result of the function call is not Void. The type of the result of the
58854             // operation is Any. It is an error to have a Void this type.
58855             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
58856             if (callSignatures.length) {
58857                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58858                 if (!noImplicitAny) {
58859                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
58860                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
58861                     }
58862                     if (getThisTypeOfSignature(signature) === voidType) {
58863                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
58864                     }
58865                 }
58866                 return signature;
58867             }
58868             invocationError(node.expression, expressionType, 1 /* Construct */);
58869             return resolveErrorCall(node);
58870         }
58871         function typeHasProtectedAccessibleBase(target, type) {
58872             var baseTypes = getBaseTypes(type);
58873             if (!ts.length(baseTypes)) {
58874                 return false;
58875             }
58876             var firstBase = baseTypes[0];
58877             if (firstBase.flags & 2097152 /* Intersection */) {
58878                 var types = firstBase.types;
58879                 var mixinFlags = findMixins(types);
58880                 var i = 0;
58881                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
58882                     var intersectionMember = _a[_i];
58883                     // We want to ignore mixin ctors
58884                     if (!mixinFlags[i]) {
58885                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
58886                             if (intersectionMember.symbol === target) {
58887                                 return true;
58888                             }
58889                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
58890                                 return true;
58891                             }
58892                         }
58893                     }
58894                     i++;
58895                 }
58896                 return false;
58897             }
58898             if (firstBase.symbol === target) {
58899                 return true;
58900             }
58901             return typeHasProtectedAccessibleBase(target, firstBase);
58902         }
58903         function isConstructorAccessible(node, signature) {
58904             if (!signature || !signature.declaration) {
58905                 return true;
58906             }
58907             var declaration = signature.declaration;
58908             var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
58909             // (1) Public constructors and (2) constructor functions are always accessible.
58910             if (!modifiers || declaration.kind !== 162 /* Constructor */) {
58911                 return true;
58912             }
58913             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
58914             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
58915             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
58916             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
58917                 var containingClass = ts.getContainingClass(node);
58918                 if (containingClass && modifiers & 16 /* Protected */) {
58919                     var containingType = getTypeOfNode(containingClass);
58920                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
58921                         return true;
58922                     }
58923                 }
58924                 if (modifiers & 8 /* Private */) {
58925                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58926                 }
58927                 if (modifiers & 16 /* Protected */) {
58928                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58929                 }
58930                 return false;
58931             }
58932             return true;
58933         }
58934         function invocationErrorDetails(apparentType, kind) {
58935             var errorInfo;
58936             var isCall = kind === 0 /* Call */;
58937             var awaitedType = getAwaitedType(apparentType);
58938             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
58939             if (apparentType.flags & 1048576 /* Union */) {
58940                 var types = apparentType.types;
58941                 var hasSignatures = false;
58942                 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
58943                     var constituent = types_18[_i];
58944                     var signatures = getSignaturesOfType(constituent, kind);
58945                     if (signatures.length !== 0) {
58946                         hasSignatures = true;
58947                         if (errorInfo) {
58948                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
58949                             break;
58950                         }
58951                     }
58952                     else {
58953                         // Error on the first non callable constituent only
58954                         if (!errorInfo) {
58955                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58956                                 ts.Diagnostics.Type_0_has_no_call_signatures :
58957                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
58958                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58959                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
58960                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
58961                         }
58962                         if (hasSignatures) {
58963                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
58964                             break;
58965                         }
58966                     }
58967                 }
58968                 if (!hasSignatures) {
58969                     errorInfo = ts.chainDiagnosticMessages(
58970                     /* detials */ undefined, isCall ?
58971                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
58972                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
58973                 }
58974                 if (!errorInfo) {
58975                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58976                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
58977                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
58978                 }
58979             }
58980             else {
58981                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58982                     ts.Diagnostics.Type_0_has_no_call_signatures :
58983                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
58984             }
58985             return {
58986                 messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
58987                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
58988             };
58989         }
58990         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
58991             var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
58992             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
58993             if (relatedInfo) {
58994                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
58995             }
58996             if (ts.isCallExpression(errorTarget.parent)) {
58997                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
58998                 diagnostic.start = start;
58999                 diagnostic.length = length_7;
59000             }
59001             diagnostics.add(diagnostic);
59002             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
59003         }
59004         function invocationErrorRecovery(apparentType, kind, diagnostic) {
59005             if (!apparentType.symbol) {
59006                 return;
59007             }
59008             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
59009             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
59010             //  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
59011             if (importNode && !ts.isImportCall(importNode)) {
59012                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
59013                 if (!sigs || !sigs.length)
59014                     return;
59015                 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));
59016             }
59017         }
59018         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
59019             var tagType = checkExpression(node.tag);
59020             var apparentType = getApparentType(tagType);
59021             if (apparentType === errorType) {
59022                 // Another error has already been reported
59023                 return resolveErrorCall(node);
59024             }
59025             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
59026             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
59027             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
59028                 return resolveUntypedCall(node);
59029             }
59030             if (!callSignatures.length) {
59031                 invocationError(node.tag, apparentType, 0 /* Call */);
59032                 return resolveErrorCall(node);
59033             }
59034             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
59035         }
59036         /**
59037          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
59038          */
59039         function getDiagnosticHeadMessageForDecoratorResolution(node) {
59040             switch (node.parent.kind) {
59041                 case 245 /* ClassDeclaration */:
59042                 case 214 /* ClassExpression */:
59043                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
59044                 case 156 /* Parameter */:
59045                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
59046                 case 159 /* PropertyDeclaration */:
59047                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
59048                 case 161 /* MethodDeclaration */:
59049                 case 163 /* GetAccessor */:
59050                 case 164 /* SetAccessor */:
59051                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
59052                 default:
59053                     return ts.Debug.fail();
59054             }
59055         }
59056         /**
59057          * Resolves a decorator as if it were a call expression.
59058          */
59059         function resolveDecorator(node, candidatesOutArray, checkMode) {
59060             var funcType = checkExpression(node.expression);
59061             var apparentType = getApparentType(funcType);
59062             if (apparentType === errorType) {
59063                 return resolveErrorCall(node);
59064             }
59065             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
59066             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
59067             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
59068                 return resolveUntypedCall(node);
59069             }
59070             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
59071                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
59072                 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);
59073                 return resolveErrorCall(node);
59074             }
59075             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
59076             if (!callSignatures.length) {
59077                 var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
59078                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
59079                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
59080                 if (errorDetails.relatedMessage) {
59081                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
59082                 }
59083                 diagnostics.add(diag);
59084                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
59085                 return resolveErrorCall(node);
59086             }
59087             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
59088         }
59089         function createSignatureForJSXIntrinsic(node, result) {
59090             var namespace = getJsxNamespaceAt(node);
59091             var exports = namespace && getExportsOfSymbol(namespace);
59092             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
59093             // file would probably be preferable.
59094             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
59095             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
59096             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 */));
59097             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
59098             parameterSymbol.type = result;
59099             return createSignature(declaration, 
59100             /*typeParameters*/ undefined, 
59101             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
59102             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
59103         }
59104         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
59105             if (isJsxIntrinsicIdentifier(node.tagName)) {
59106                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
59107                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
59108                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
59109                 return fakeSignature;
59110             }
59111             var exprTypes = checkExpression(node.tagName);
59112             var apparentType = getApparentType(exprTypes);
59113             if (apparentType === errorType) {
59114                 return resolveErrorCall(node);
59115             }
59116             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
59117             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
59118                 return resolveUntypedCall(node);
59119             }
59120             if (signatures.length === 0) {
59121                 // We found no signatures at all, which is an error
59122                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
59123                 return resolveErrorCall(node);
59124             }
59125             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
59126         }
59127         /**
59128          * Sometimes, we have a decorator that could accept zero arguments,
59129          * but is receiving too many arguments as part of the decorator invocation.
59130          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
59131          */
59132         function isPotentiallyUncalledDecorator(decorator, signatures) {
59133             return signatures.length && ts.every(signatures, function (signature) {
59134                 return signature.minArgumentCount === 0 &&
59135                     !signatureHasRestParameter(signature) &&
59136                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
59137             });
59138         }
59139         function resolveSignature(node, candidatesOutArray, checkMode) {
59140             switch (node.kind) {
59141                 case 196 /* CallExpression */:
59142                     return resolveCallExpression(node, candidatesOutArray, checkMode);
59143                 case 197 /* NewExpression */:
59144                     return resolveNewExpression(node, candidatesOutArray, checkMode);
59145                 case 198 /* TaggedTemplateExpression */:
59146                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
59147                 case 157 /* Decorator */:
59148                     return resolveDecorator(node, candidatesOutArray, checkMode);
59149                 case 268 /* JsxOpeningElement */:
59150                 case 267 /* JsxSelfClosingElement */:
59151                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
59152             }
59153             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
59154         }
59155         /**
59156          * Resolve a signature of a given call-like expression.
59157          * @param node a call-like expression to try resolve a signature for
59158          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
59159          *                           the function will fill it up with appropriate candidate signatures
59160          * @return a signature of the call-like expression or undefined if one can't be found
59161          */
59162         function getResolvedSignature(node, candidatesOutArray, checkMode) {
59163             var links = getNodeLinks(node);
59164             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
59165             // However, it is possible that either candidatesOutArray was not passed in the first time,
59166             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
59167             // to correctly fill the candidatesOutArray.
59168             var cached = links.resolvedSignature;
59169             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
59170                 return cached;
59171             }
59172             links.resolvedSignature = resolvingSignature;
59173             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
59174             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
59175             // resolution should be deferred.
59176             if (result !== resolvingSignature) {
59177                 // If signature resolution originated in control flow type analysis (for example to compute the
59178                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
59179                 // types from the control flow analysis.
59180                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
59181             }
59182             return result;
59183         }
59184         /**
59185          * Indicates whether a declaration can be treated as a constructor in a JavaScript
59186          * file.
59187          */
59188         function isJSConstructor(node) {
59189             if (!node || !ts.isInJSFile(node)) {
59190                 return false;
59191             }
59192             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
59193                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
59194                     undefined;
59195             if (func) {
59196                 // If the node has a @class tag, treat it like a constructor.
59197                 if (ts.getJSDocClassTag(node))
59198                     return true;
59199                 // If the symbol of the node has members, treat it like a constructor.
59200                 var symbol = getSymbolOfNode(func);
59201                 return !!symbol && ts.hasEntries(symbol.members);
59202             }
59203             return false;
59204         }
59205         function mergeJSSymbols(target, source) {
59206             if (source) {
59207                 var links = getSymbolLinks(source);
59208                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
59209                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
59210                     inferred.exports = inferred.exports || ts.createSymbolTable();
59211                     inferred.members = inferred.members || ts.createSymbolTable();
59212                     inferred.flags |= source.flags & 32 /* Class */;
59213                     if (ts.hasEntries(source.exports)) {
59214                         mergeSymbolTable(inferred.exports, source.exports);
59215                     }
59216                     if (ts.hasEntries(source.members)) {
59217                         mergeSymbolTable(inferred.members, source.members);
59218                     }
59219                     (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
59220                     return inferred;
59221                 }
59222                 return links.inferredClassSymbol.get("" + getSymbolId(target));
59223             }
59224         }
59225         function getAssignedClassSymbol(decl) {
59226             var assignmentSymbol = decl && decl.parent &&
59227                 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
59228                     ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
59229                     ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
59230             var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
59231             var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
59232             return init ? getSymbolOfNode(init) : undefined;
59233         }
59234         function getAssignedJSPrototype(node) {
59235             if (!node.parent) {
59236                 return false;
59237             }
59238             var parent = node.parent;
59239             while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
59240                 parent = parent.parent;
59241             }
59242             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
59243                 var right = ts.getInitializerOfBinaryExpression(parent);
59244                 return ts.isObjectLiteralExpression(right) && right;
59245             }
59246         }
59247         /**
59248          * Syntactically and semantically checks a call or new expression.
59249          * @param node The call/new expression to be checked.
59250          * @returns On success, the expression's signature's return type. On failure, anyType.
59251          */
59252         function checkCallExpression(node, checkMode) {
59253             if (!checkGrammarTypeArguments(node, node.typeArguments))
59254                 checkGrammarArguments(node.arguments);
59255             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
59256             if (signature === resolvingSignature) {
59257                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
59258                 // returns a function type. We defer checking and return nonInferrableType.
59259                 return nonInferrableType;
59260             }
59261             if (node.expression.kind === 102 /* SuperKeyword */) {
59262                 return voidType;
59263             }
59264             if (node.kind === 197 /* NewExpression */) {
59265                 var declaration = signature.declaration;
59266                 if (declaration &&
59267                     declaration.kind !== 162 /* Constructor */ &&
59268                     declaration.kind !== 166 /* ConstructSignature */ &&
59269                     declaration.kind !== 171 /* ConstructorType */ &&
59270                     !ts.isJSDocConstructSignature(declaration) &&
59271                     !isJSConstructor(declaration)) {
59272                     // When resolved signature is a call signature (and not a construct signature) the result type is any
59273                     if (noImplicitAny) {
59274                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
59275                     }
59276                     return anyType;
59277                 }
59278             }
59279             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
59280             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
59281                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
59282             }
59283             var returnType = getReturnTypeOfSignature(signature);
59284             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
59285             // as a fresh unique symbol literal type.
59286             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
59287                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
59288             }
59289             if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
59290                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
59291                 if (!ts.isDottedName(node.expression)) {
59292                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
59293                 }
59294                 else if (!getEffectsSignature(node)) {
59295                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
59296                     getTypeOfDottedName(node.expression, diagnostic);
59297                 }
59298             }
59299             if (ts.isInJSFile(node)) {
59300                 var decl = ts.getDeclarationOfExpando(node);
59301                 if (decl) {
59302                     var jsSymbol = getSymbolOfNode(decl);
59303                     if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
59304                         var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
59305                         jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
59306                         return getIntersectionType([returnType, jsAssignmentType]);
59307                     }
59308                 }
59309             }
59310             return returnType;
59311         }
59312         function isSymbolOrSymbolForCall(node) {
59313             if (!ts.isCallExpression(node))
59314                 return false;
59315             var left = node.expression;
59316             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
59317                 left = left.expression;
59318             }
59319             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
59320                 return false;
59321             }
59322             // make sure `Symbol` is the global symbol
59323             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
59324             if (!globalESSymbol) {
59325                 return false;
59326             }
59327             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
59328         }
59329         function checkImportCallExpression(node) {
59330             // Check grammar of dynamic import
59331             if (!checkGrammarArguments(node.arguments))
59332                 checkGrammarImportCallExpression(node);
59333             if (node.arguments.length === 0) {
59334                 return createPromiseReturnType(node, anyType);
59335             }
59336             var specifier = node.arguments[0];
59337             var specifierType = checkExpressionCached(specifier);
59338             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
59339             for (var i = 1; i < node.arguments.length; ++i) {
59340                 checkExpressionCached(node.arguments[i]);
59341             }
59342             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
59343                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
59344             }
59345             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
59346             var moduleSymbol = resolveExternalModuleName(node, specifier);
59347             if (moduleSymbol) {
59348                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
59349                 if (esModuleSymbol) {
59350                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
59351                 }
59352             }
59353             return createPromiseReturnType(node, anyType);
59354         }
59355         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
59356             if (allowSyntheticDefaultImports && type && type !== errorType) {
59357                 var synthType = type;
59358                 if (!synthType.syntheticType) {
59359                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
59360                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
59361                     if (hasSyntheticDefault) {
59362                         var memberTable = ts.createSymbolTable();
59363                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
59364                         newSymbol.nameType = getLiteralType("default");
59365                         newSymbol.target = resolveSymbol(symbol);
59366                         memberTable.set("default" /* Default */, newSymbol);
59367                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
59368                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
59369                         anonymousSymbol.type = defaultContainingObject;
59370                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
59371                     }
59372                     else {
59373                         synthType.syntheticType = type;
59374                     }
59375                 }
59376                 return synthType.syntheticType;
59377             }
59378             return type;
59379         }
59380         function isCommonJsRequire(node) {
59381             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
59382                 return false;
59383             }
59384             // Make sure require is not a local function
59385             if (!ts.isIdentifier(node.expression))
59386                 return ts.Debug.fail();
59387             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
59388             if (resolvedRequire === requireSymbol) {
59389                 return true;
59390             }
59391             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
59392             if (resolvedRequire.flags & 2097152 /* Alias */) {
59393                 return false;
59394             }
59395             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
59396                 ? 244 /* FunctionDeclaration */
59397                 : resolvedRequire.flags & 3 /* Variable */
59398                     ? 242 /* VariableDeclaration */
59399                     : 0 /* Unknown */;
59400             if (targetDeclarationKind !== 0 /* Unknown */) {
59401                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
59402                 // function/variable declaration should be ambient
59403                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
59404             }
59405             return false;
59406         }
59407         function checkTaggedTemplateExpression(node) {
59408             if (!checkGrammarTaggedTemplateChain(node))
59409                 checkGrammarTypeArguments(node, node.typeArguments);
59410             if (languageVersion < 2 /* ES2015 */) {
59411                 checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
59412             }
59413             return getReturnTypeOfSignature(getResolvedSignature(node));
59414         }
59415         function checkAssertion(node) {
59416             return checkAssertionWorker(node, node.type, node.expression);
59417         }
59418         function isValidConstAssertionArgument(node) {
59419             switch (node.kind) {
59420                 case 10 /* StringLiteral */:
59421                 case 14 /* NoSubstitutionTemplateLiteral */:
59422                 case 8 /* NumericLiteral */:
59423                 case 9 /* BigIntLiteral */:
59424                 case 106 /* TrueKeyword */:
59425                 case 91 /* FalseKeyword */:
59426                 case 192 /* ArrayLiteralExpression */:
59427                 case 193 /* ObjectLiteralExpression */:
59428                     return true;
59429                 case 200 /* ParenthesizedExpression */:
59430                     return isValidConstAssertionArgument(node.expression);
59431                 case 207 /* PrefixUnaryExpression */:
59432                     var op = node.operator;
59433                     var arg = node.operand;
59434                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
59435                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
59436                 case 194 /* PropertyAccessExpression */:
59437                 case 195 /* ElementAccessExpression */:
59438                     var expr = node.expression;
59439                     if (ts.isIdentifier(expr)) {
59440                         var symbol = getSymbolAtLocation(expr);
59441                         if (symbol && symbol.flags & 2097152 /* Alias */) {
59442                             symbol = resolveAlias(symbol);
59443                         }
59444                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
59445                     }
59446             }
59447             return false;
59448         }
59449         function checkAssertionWorker(errNode, type, expression, checkMode) {
59450             var exprType = checkExpression(expression, checkMode);
59451             if (ts.isConstTypeReference(type)) {
59452                 if (!isValidConstAssertionArgument(expression)) {
59453                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
59454                 }
59455                 return getRegularTypeOfLiteralType(exprType);
59456             }
59457             checkSourceElement(type);
59458             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
59459             var targetType = getTypeFromTypeNode(type);
59460             if (produceDiagnostics && targetType !== errorType) {
59461                 var widenedType = getWidenedType(exprType);
59462                 if (!isTypeComparableTo(targetType, widenedType)) {
59463                     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);
59464                 }
59465             }
59466             return targetType;
59467         }
59468         function checkNonNullChain(node) {
59469             var leftType = checkExpression(node.expression);
59470             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
59471             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
59472         }
59473         function checkNonNullAssertion(node) {
59474             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
59475                 getNonNullableType(checkExpression(node.expression));
59476         }
59477         function checkMetaProperty(node) {
59478             checkGrammarMetaProperty(node);
59479             if (node.keywordToken === 99 /* NewKeyword */) {
59480                 return checkNewTargetMetaProperty(node);
59481             }
59482             if (node.keywordToken === 96 /* ImportKeyword */) {
59483                 return checkImportMetaProperty(node);
59484             }
59485             return ts.Debug.assertNever(node.keywordToken);
59486         }
59487         function checkNewTargetMetaProperty(node) {
59488             var container = ts.getNewTargetContainer(node);
59489             if (!container) {
59490                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
59491                 return errorType;
59492             }
59493             else if (container.kind === 162 /* Constructor */) {
59494                 var symbol = getSymbolOfNode(container.parent);
59495                 return getTypeOfSymbol(symbol);
59496             }
59497             else {
59498                 var symbol = getSymbolOfNode(container);
59499                 return getTypeOfSymbol(symbol);
59500             }
59501         }
59502         function checkImportMetaProperty(node) {
59503             if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
59504                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
59505             }
59506             var file = ts.getSourceFileOfNode(node);
59507             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
59508             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
59509             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
59510         }
59511         function getTypeOfParameter(symbol) {
59512             var type = getTypeOfSymbol(symbol);
59513             if (strictNullChecks) {
59514                 var declaration = symbol.valueDeclaration;
59515                 if (declaration && ts.hasInitializer(declaration)) {
59516                     return getOptionalType(type);
59517                 }
59518             }
59519             return type;
59520         }
59521         function getParameterNameAtPosition(signature, pos) {
59522             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59523             if (pos < paramCount) {
59524                 return signature.parameters[pos].escapedName;
59525             }
59526             var restParameter = signature.parameters[paramCount] || unknownSymbol;
59527             var restType = getTypeOfSymbol(restParameter);
59528             if (isTupleType(restType)) {
59529                 var associatedNames = restType.target.associatedNames;
59530                 var index = pos - paramCount;
59531                 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
59532             }
59533             return restParameter.escapedName;
59534         }
59535         function getTypeAtPosition(signature, pos) {
59536             return tryGetTypeAtPosition(signature, pos) || anyType;
59537         }
59538         function tryGetTypeAtPosition(signature, pos) {
59539             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59540             if (pos < paramCount) {
59541                 return getTypeOfParameter(signature.parameters[pos]);
59542             }
59543             if (signatureHasRestParameter(signature)) {
59544                 // We want to return the value undefined for an out of bounds parameter position,
59545                 // so we need to check bounds here before calling getIndexedAccessType (which
59546                 // otherwise would return the type 'undefined').
59547                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
59548                 var index = pos - paramCount;
59549                 if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
59550                     return getIndexedAccessType(restType, getLiteralType(index));
59551                 }
59552             }
59553             return undefined;
59554         }
59555         function getRestTypeAtPosition(source, pos) {
59556             var paramCount = getParameterCount(source);
59557             var restType = getEffectiveRestType(source);
59558             var nonRestCount = paramCount - (restType ? 1 : 0);
59559             if (restType && pos === nonRestCount) {
59560                 return restType;
59561             }
59562             var types = [];
59563             var names = [];
59564             for (var i = pos; i < nonRestCount; i++) {
59565                 types.push(getTypeAtPosition(source, i));
59566                 names.push(getParameterNameAtPosition(source, i));
59567             }
59568             if (restType) {
59569                 types.push(getIndexedAccessType(restType, numberType));
59570                 names.push(getParameterNameAtPosition(source, nonRestCount));
59571             }
59572             var minArgumentCount = getMinArgumentCount(source);
59573             var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
59574             return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
59575         }
59576         function getParameterCount(signature) {
59577             var length = signature.parameters.length;
59578             if (signatureHasRestParameter(signature)) {
59579                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
59580                 if (isTupleType(restType)) {
59581                     return length + getTypeArguments(restType).length - 1;
59582                 }
59583             }
59584             return length;
59585         }
59586         function getMinArgumentCount(signature, strongArityForUntypedJS) {
59587             if (signatureHasRestParameter(signature)) {
59588                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59589                 if (isTupleType(restType)) {
59590                     var minLength = restType.target.minLength;
59591                     if (minLength > 0) {
59592                         return signature.parameters.length - 1 + minLength;
59593                     }
59594                 }
59595             }
59596             if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
59597                 return 0;
59598             }
59599             return signature.minArgumentCount;
59600         }
59601         function hasEffectiveRestParameter(signature) {
59602             if (signatureHasRestParameter(signature)) {
59603                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59604                 return !isTupleType(restType) || restType.target.hasRestElement;
59605             }
59606             return false;
59607         }
59608         function getEffectiveRestType(signature) {
59609             if (signatureHasRestParameter(signature)) {
59610                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59611                 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
59612             }
59613             return undefined;
59614         }
59615         function getNonArrayRestType(signature) {
59616             var restType = getEffectiveRestType(signature);
59617             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
59618         }
59619         function getTypeOfFirstParameterOfSignature(signature) {
59620             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
59621         }
59622         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
59623             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
59624         }
59625         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
59626             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59627             for (var i = 0; i < len; i++) {
59628                 var declaration = signature.parameters[i].valueDeclaration;
59629                 if (declaration.type) {
59630                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
59631                     if (typeNode) {
59632                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
59633                     }
59634                 }
59635             }
59636             var restType = getEffectiveRestType(context);
59637             if (restType && restType.flags & 262144 /* TypeParameter */) {
59638                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
59639                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
59640                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
59641                 assignContextualParameterTypes(signature, instantiatedContext);
59642                 // We then infer from a tuple type representing the parameters that correspond to the contextual
59643                 // rest parameter.
59644                 var restPos = getParameterCount(context) - 1;
59645                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
59646             }
59647         }
59648         function assignContextualParameterTypes(signature, context) {
59649             signature.typeParameters = context.typeParameters;
59650             if (context.thisParameter) {
59651                 var parameter = signature.thisParameter;
59652                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
59653                     if (!parameter) {
59654                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
59655                     }
59656                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
59657                 }
59658             }
59659             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59660             for (var i = 0; i < len; i++) {
59661                 var parameter = signature.parameters[i];
59662                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59663                     var contextualParameterType = tryGetTypeAtPosition(context, i);
59664                     assignParameterType(parameter, contextualParameterType);
59665                 }
59666             }
59667             if (signatureHasRestParameter(signature)) {
59668                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
59669                 var parameter = ts.last(signature.parameters);
59670                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59671                     var contextualParameterType = getRestTypeAtPosition(context, len);
59672                     assignParameterType(parameter, contextualParameterType);
59673                 }
59674             }
59675         }
59676         function assignNonContextualParameterTypes(signature) {
59677             if (signature.thisParameter) {
59678                 assignParameterType(signature.thisParameter);
59679             }
59680             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
59681                 var parameter = _a[_i];
59682                 assignParameterType(parameter);
59683             }
59684         }
59685         function assignParameterType(parameter, type) {
59686             var links = getSymbolLinks(parameter);
59687             if (!links.type) {
59688                 var declaration = parameter.valueDeclaration;
59689                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
59690                 if (declaration.name.kind !== 75 /* Identifier */) {
59691                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
59692                     if (links.type === unknownType) {
59693                         links.type = getTypeFromBindingPattern(declaration.name);
59694                     }
59695                     assignBindingElementTypes(declaration.name);
59696                 }
59697             }
59698         }
59699         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
59700         // the destructured type into the contained binding elements.
59701         function assignBindingElementTypes(pattern) {
59702             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
59703                 var element = _a[_i];
59704                 if (!ts.isOmittedExpression(element)) {
59705                     if (element.name.kind === 75 /* Identifier */) {
59706                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
59707                     }
59708                     else {
59709                         assignBindingElementTypes(element.name);
59710                     }
59711                 }
59712             }
59713         }
59714         function createPromiseType(promisedType) {
59715             // creates a `Promise<T>` type where `T` is the promisedType argument
59716             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
59717             if (globalPromiseType !== emptyGenericType) {
59718                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59719                 promisedType = getAwaitedType(promisedType) || unknownType;
59720                 return createTypeReference(globalPromiseType, [promisedType]);
59721             }
59722             return unknownType;
59723         }
59724         function createPromiseLikeType(promisedType) {
59725             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
59726             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
59727             if (globalPromiseLikeType !== emptyGenericType) {
59728                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59729                 promisedType = getAwaitedType(promisedType) || unknownType;
59730                 return createTypeReference(globalPromiseLikeType, [promisedType]);
59731             }
59732             return unknownType;
59733         }
59734         function createPromiseReturnType(func, promisedType) {
59735             var promiseType = createPromiseType(promisedType);
59736             if (promiseType === unknownType) {
59737                 error(func, ts.isImportCall(func) ?
59738                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
59739                     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);
59740                 return errorType;
59741             }
59742             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
59743                 error(func, ts.isImportCall(func) ?
59744                     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 :
59745                     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);
59746             }
59747             return promiseType;
59748         }
59749         function getReturnTypeFromBody(func, checkMode) {
59750             if (!func.body) {
59751                 return errorType;
59752             }
59753             var functionFlags = ts.getFunctionFlags(func);
59754             var isAsync = (functionFlags & 2 /* Async */) !== 0;
59755             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
59756             var returnType;
59757             var yieldType;
59758             var nextType;
59759             var fallbackReturnType = voidType;
59760             if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
59761                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59762                 if (isAsync) {
59763                     // From within an async function you can return either a non-promise value or a promise. Any
59764                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59765                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
59766                     // the native Promise<T> type later in this function.
59767                     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);
59768                 }
59769             }
59770             else if (isGenerator) { // Generator or AsyncGenerator function
59771                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
59772                 if (!returnTypes) {
59773                     fallbackReturnType = neverType;
59774                 }
59775                 else if (returnTypes.length > 0) {
59776                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
59777                 }
59778                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
59779                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
59780                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
59781             }
59782             else { // Async or normal function
59783                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
59784                 if (!types) {
59785                     // For an async function, the return type will not be never, but rather a Promise for never.
59786                     return functionFlags & 2 /* Async */
59787                         ? createPromiseReturnType(func, neverType) // Async function
59788                         : neverType; // Normal function
59789                 }
59790                 if (types.length === 0) {
59791                     // For an async function, the return type will not be void, but rather a Promise for void.
59792                     return functionFlags & 2 /* Async */
59793                         ? createPromiseReturnType(func, voidType) // Async function
59794                         : voidType; // Normal function
59795                 }
59796                 // Return a union of the return expression types.
59797                 returnType = getUnionType(types, 2 /* Subtype */);
59798             }
59799             if (returnType || yieldType || nextType) {
59800                 if (yieldType)
59801                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
59802                 if (returnType)
59803                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
59804                 if (nextType)
59805                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
59806                 if (returnType && isUnitType(returnType) ||
59807                     yieldType && isUnitType(yieldType) ||
59808                     nextType && isUnitType(nextType)) {
59809                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
59810                     var contextualType = !contextualSignature ? undefined :
59811                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
59812                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
59813                     if (isGenerator) {
59814                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
59815                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
59816                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
59817                     }
59818                     else {
59819                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
59820                     }
59821                 }
59822                 if (yieldType)
59823                     yieldType = getWidenedType(yieldType);
59824                 if (returnType)
59825                     returnType = getWidenedType(returnType);
59826                 if (nextType)
59827                     nextType = getWidenedType(nextType);
59828             }
59829             if (isGenerator) {
59830                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
59831             }
59832             else {
59833                 // From within an async function you can return either a non-promise value or a promise. Any
59834                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59835                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
59836                 return isAsync
59837                     ? createPromiseType(returnType || fallbackReturnType)
59838                     : returnType || fallbackReturnType;
59839             }
59840         }
59841         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
59842             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
59843             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
59844             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
59845             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
59846             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
59847             if (globalGeneratorType === emptyGenericType) {
59848                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
59849                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
59850                 // nextType.
59851                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
59852                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
59853                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
59854                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
59855                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
59856                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
59857                     if (globalType !== emptyGenericType) {
59858                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
59859                     }
59860                     // The global IterableIterator type doesn't exist, so report an error
59861                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
59862                     return emptyObjectType;
59863                 }
59864                 // The global Generator type doesn't exist, so report an error
59865                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
59866                 return emptyObjectType;
59867             }
59868             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
59869         }
59870         function checkAndAggregateYieldOperandTypes(func, checkMode) {
59871             var yieldTypes = [];
59872             var nextTypes = [];
59873             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
59874             ts.forEachYieldExpression(func.body, function (yieldExpression) {
59875                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
59876                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
59877                 var nextType;
59878                 if (yieldExpression.asteriskToken) {
59879                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
59880                     nextType = iterationTypes && iterationTypes.nextType;
59881                 }
59882                 else {
59883                     nextType = getContextualType(yieldExpression);
59884                 }
59885                 if (nextType)
59886                     ts.pushIfUnique(nextTypes, nextType);
59887             });
59888             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
59889         }
59890         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
59891             var errorNode = node.expression || node;
59892             // A `yield*` expression effectively yields everything that its operand yields
59893             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
59894             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
59895                 ? 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
59896                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59897         }
59898         /**
59899          * Collect the TypeFacts learned from a typeof switch with
59900          * total clauses `witnesses`, and the active clause ranging
59901          * from `start` to `end`. Parameter `hasDefault` denotes
59902          * whether the active clause contains a default clause.
59903          */
59904         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
59905             var facts = 0 /* None */;
59906             // When in the default we only collect inequality facts
59907             // because default is 'in theory' a set of infinite
59908             // equalities.
59909             if (hasDefault) {
59910                 // Value is not equal to any types after the active clause.
59911                 for (var i = end; i < witnesses.length; i++) {
59912                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59913                 }
59914                 // Remove inequalities for types that appear in the
59915                 // active clause because they appear before other
59916                 // types collected so far.
59917                 for (var i = start; i < end; i++) {
59918                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
59919                 }
59920                 // Add inequalities for types before the active clause unconditionally.
59921                 for (var i = 0; i < start; i++) {
59922                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59923                 }
59924             }
59925             // When in an active clause without default the set of
59926             // equalities is finite.
59927             else {
59928                 // Add equalities for all types in the active clause.
59929                 for (var i = start; i < end; i++) {
59930                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
59931                 }
59932                 // Remove equalities for types that appear before the
59933                 // active clause.
59934                 for (var i = 0; i < start; i++) {
59935                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
59936                 }
59937             }
59938             return facts;
59939         }
59940         function isExhaustiveSwitchStatement(node) {
59941             var links = getNodeLinks(node);
59942             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
59943         }
59944         function computeExhaustiveSwitchStatement(node) {
59945             if (node.expression.kind === 204 /* TypeOfExpression */) {
59946                 var operandType = getTypeOfExpression(node.expression.expression);
59947                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
59948                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
59949                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
59950                 var type_3 = getBaseConstraintOfType(operandType) || operandType;
59951                 return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
59952             }
59953             var type = getTypeOfExpression(node.expression);
59954             if (!isLiteralType(type)) {
59955                 return false;
59956             }
59957             var switchTypes = getSwitchClauseTypes(node);
59958             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
59959                 return false;
59960             }
59961             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
59962         }
59963         function functionHasImplicitReturn(func) {
59964             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
59965         }
59966         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
59967         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
59968             var functionFlags = ts.getFunctionFlags(func);
59969             var aggregatedTypes = [];
59970             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
59971             var hasReturnOfTypeNever = false;
59972             ts.forEachReturnStatement(func.body, function (returnStatement) {
59973                 var expr = returnStatement.expression;
59974                 if (expr) {
59975                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59976                     if (functionFlags & 2 /* Async */) {
59977                         // From within an async function you can return either a non-promise value or a promise. Any
59978                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59979                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
59980                         // the native Promise<T> type by the caller.
59981                         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);
59982                     }
59983                     if (type.flags & 131072 /* Never */) {
59984                         hasReturnOfTypeNever = true;
59985                     }
59986                     ts.pushIfUnique(aggregatedTypes, type);
59987                 }
59988                 else {
59989                     hasReturnWithNoExpression = true;
59990                 }
59991             });
59992             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
59993                 return undefined;
59994             }
59995             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
59996                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
59997                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
59998                 ts.pushIfUnique(aggregatedTypes, undefinedType);
59999             }
60000             return aggregatedTypes;
60001         }
60002         function mayReturnNever(func) {
60003             switch (func.kind) {
60004                 case 201 /* FunctionExpression */:
60005                 case 202 /* ArrowFunction */:
60006                     return true;
60007                 case 161 /* MethodDeclaration */:
60008                     return func.parent.kind === 193 /* ObjectLiteralExpression */;
60009                 default:
60010                     return false;
60011             }
60012         }
60013         /**
60014          * TypeScript Specification 1.0 (6.3) - July 2014
60015          *   An explicitly typed function whose return type isn't the Void type,
60016          *   the Any type, or a union type containing the Void or Any type as a constituent
60017          *   must have at least one return statement somewhere in its body.
60018          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
60019          *
60020          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
60021          */
60022         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
60023             if (!produceDiagnostics) {
60024                 return;
60025             }
60026             var functionFlags = ts.getFunctionFlags(func);
60027             var type = returnType && unwrapReturnType(returnType, functionFlags);
60028             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
60029             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
60030                 return;
60031             }
60032             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
60033             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
60034             if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
60035                 return;
60036             }
60037             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
60038             if (type && type.flags & 131072 /* Never */) {
60039                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
60040             }
60041             else if (type && !hasExplicitReturn) {
60042                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
60043                 // this function does not conform to the specification.
60044                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
60045                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
60046             }
60047             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
60048                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
60049             }
60050             else if (compilerOptions.noImplicitReturns) {
60051                 if (!type) {
60052                     // If return type annotation is omitted check if function has any explicit return statements.
60053                     // If it does not have any - its inferred return type is void - don't do any checks.
60054                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
60055                     if (!hasExplicitReturn) {
60056                         return;
60057                     }
60058                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
60059                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
60060                         return;
60061                     }
60062                 }
60063                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
60064             }
60065         }
60066         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
60067             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
60068             checkNodeDeferred(node);
60069             // The identityMapper object is used to indicate that function expressions are wildcards
60070             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
60071                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
60072                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
60073                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
60074                     var contextualSignature = getContextualSignature(node);
60075                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
60076                         var links = getNodeLinks(node);
60077                         if (links.contextFreeType) {
60078                             return links.contextFreeType;
60079                         }
60080                         var returnType = getReturnTypeFromBody(node, checkMode);
60081                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
60082                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
60083                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
60084                         return links.contextFreeType = returnOnlyType;
60085                     }
60086                 }
60087                 return anyFunctionType;
60088             }
60089             // Grammar checking
60090             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
60091             if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
60092                 checkGrammarForGenerator(node);
60093             }
60094             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
60095             return getTypeOfSymbol(getSymbolOfNode(node));
60096         }
60097         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
60098             var links = getNodeLinks(node);
60099             // Check if function expression is contextually typed and assign parameter types if so.
60100             if (!(links.flags & 1024 /* ContextChecked */)) {
60101                 var contextualSignature = getContextualSignature(node);
60102                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
60103                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
60104                 // already assigned contextual types.
60105                 if (!(links.flags & 1024 /* ContextChecked */)) {
60106                     links.flags |= 1024 /* ContextChecked */;
60107                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
60108                     if (!signature) {
60109                         return;
60110                     }
60111                     if (isContextSensitive(node)) {
60112                         if (contextualSignature) {
60113                             var inferenceContext = getInferenceContext(node);
60114                             if (checkMode && checkMode & 2 /* Inferential */) {
60115                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
60116                             }
60117                             var instantiatedContextualSignature = inferenceContext ?
60118                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
60119                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
60120                         }
60121                         else {
60122                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
60123                             assignNonContextualParameterTypes(signature);
60124                         }
60125                     }
60126                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
60127                         var returnType = getReturnTypeFromBody(node, checkMode);
60128                         if (!signature.resolvedReturnType) {
60129                             signature.resolvedReturnType = returnType;
60130                         }
60131                     }
60132                     checkSignatureDeclaration(node);
60133                 }
60134             }
60135         }
60136         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
60137             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
60138             var functionFlags = ts.getFunctionFlags(node);
60139             var returnType = getReturnTypeFromAnnotation(node);
60140             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
60141             if (node.body) {
60142                 if (!ts.getEffectiveReturnTypeNode(node)) {
60143                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
60144                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
60145                     // of a function. Because checking of function expression bodies is deferred, there was never an
60146                     // appropriate time to do this during the main walk of the file (see the comment at the top of
60147                     // checkFunctionExpressionBodies). So it must be done now.
60148                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
60149                 }
60150                 if (node.body.kind === 223 /* Block */) {
60151                     checkSourceElement(node.body);
60152                 }
60153                 else {
60154                     // From within an async function you can return either a non-promise value or a promise. Any
60155                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
60156                     // should not be checking assignability of a promise to the return type. Instead, we need to
60157                     // check assignability of the awaited type of the expression body against the promised type of
60158                     // its return type annotation.
60159                     var exprType = checkExpression(node.body);
60160                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
60161                     if (returnOrPromisedType) {
60162                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
60163                             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);
60164                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
60165                         }
60166                         else { // Normal function
60167                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
60168                         }
60169                     }
60170                 }
60171             }
60172         }
60173         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
60174             if (isAwaitValid === void 0) { isAwaitValid = false; }
60175             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
60176                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
60177                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
60178                 return false;
60179             }
60180             return true;
60181         }
60182         function isReadonlyAssignmentDeclaration(d) {
60183             if (!ts.isCallExpression(d)) {
60184                 return false;
60185             }
60186             if (!ts.isBindableObjectDefinePropertyCall(d)) {
60187                 return false;
60188             }
60189             var objectLitType = checkExpressionCached(d.arguments[2]);
60190             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
60191             if (valueType) {
60192                 var writableProp = getPropertyOfType(objectLitType, "writable");
60193                 var writableType = writableProp && getTypeOfSymbol(writableProp);
60194                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
60195                     return true;
60196                 }
60197                 // We include this definition whereupon we walk back and check the type at the declaration because
60198                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
60199                 // argument types, should the type be contextualized by the call itself.
60200                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
60201                     var initializer = writableProp.valueDeclaration.initializer;
60202                     var rawOriginalType = checkExpression(initializer);
60203                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
60204                         return true;
60205                     }
60206                 }
60207                 return false;
60208             }
60209             var setProp = getPropertyOfType(objectLitType, "set");
60210             return !setProp;
60211         }
60212         function isReadonlySymbol(symbol) {
60213             // The following symbols are considered read-only:
60214             // Properties with a 'readonly' modifier
60215             // Variables declared with 'const'
60216             // Get accessors without matching set accessors
60217             // Enum members
60218             // Object.defineProperty assignments with writable false or no setter
60219             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
60220             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
60221                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
60222                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
60223                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
60224                 symbol.flags & 8 /* EnumMember */ ||
60225                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
60226         }
60227         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
60228             var _a, _b;
60229             if (assignmentKind === 0 /* None */) {
60230                 // no assigment means it doesn't matter whether the entity is readonly
60231                 return false;
60232             }
60233             if (isReadonlySymbol(symbol)) {
60234                 // Allow assignments to readonly properties within constructors of the same class declaration.
60235                 if (symbol.flags & 4 /* Property */ &&
60236                     ts.isAccessExpression(expr) &&
60237                     expr.expression.kind === 104 /* ThisKeyword */) {
60238                     // Look for if this is the constructor for the class that `symbol` is a property of.
60239                     var ctor = ts.getContainingFunction(expr);
60240                     if (!(ctor && ctor.kind === 162 /* Constructor */)) {
60241                         return true;
60242                     }
60243                     if (symbol.valueDeclaration) {
60244                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
60245                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
60246                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
60247                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
60248                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
60249                         var isWriteableSymbol = isLocalPropertyDeclaration
60250                             || isLocalParameterProperty
60251                             || isLocalThisPropertyAssignment
60252                             || isLocalThisPropertyAssignmentConstructorFunction;
60253                         return !isWriteableSymbol;
60254                     }
60255                 }
60256                 return true;
60257             }
60258             if (ts.isAccessExpression(expr)) {
60259                 // references through namespace import should be readonly
60260                 var node = ts.skipParentheses(expr.expression);
60261                 if (node.kind === 75 /* Identifier */) {
60262                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
60263                     if (symbol_2.flags & 2097152 /* Alias */) {
60264                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
60265                         return !!declaration && declaration.kind === 256 /* NamespaceImport */;
60266                     }
60267                 }
60268             }
60269             return false;
60270         }
60271         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
60272             // References are combinations of identifiers, parentheses, and property accesses.
60273             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
60274             if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
60275                 error(expr, invalidReferenceMessage);
60276                 return false;
60277             }
60278             if (node.flags & 32 /* OptionalChain */) {
60279                 error(expr, invalidOptionalChainMessage);
60280                 return false;
60281             }
60282             return true;
60283         }
60284         function checkDeleteExpression(node) {
60285             checkExpression(node.expression);
60286             var expr = ts.skipParentheses(node.expression);
60287             if (!ts.isAccessExpression(expr)) {
60288                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
60289                 return booleanType;
60290             }
60291             // eslint-disable-next-line
60292             if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
60293                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
60294             }
60295             var links = getNodeLinks(expr);
60296             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
60297             if (symbol && isReadonlySymbol(symbol)) {
60298                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
60299             }
60300             return booleanType;
60301         }
60302         function checkTypeOfExpression(node) {
60303             checkExpression(node.expression);
60304             return typeofType;
60305         }
60306         function checkVoidExpression(node) {
60307             checkExpression(node.expression);
60308             return undefinedWideningType;
60309         }
60310         function isTopLevelAwait(node) {
60311             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
60312             return ts.isSourceFile(container);
60313         }
60314         function checkAwaitExpression(node) {
60315             // Grammar checking
60316             if (produceDiagnostics) {
60317                 if (!(node.flags & 32768 /* AwaitContext */)) {
60318                     if (isTopLevelAwait(node)) {
60319                         var sourceFile = ts.getSourceFileOfNode(node);
60320                         if (!hasParseDiagnostics(sourceFile)) {
60321                             var span = void 0;
60322                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
60323                                 if (!span)
60324                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60325                                 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);
60326                                 diagnostics.add(diagnostic);
60327                             }
60328                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
60329                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60330                                 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);
60331                                 diagnostics.add(diagnostic);
60332                             }
60333                         }
60334                     }
60335                     else {
60336                         // use of 'await' in non-async function
60337                         var sourceFile = ts.getSourceFileOfNode(node);
60338                         if (!hasParseDiagnostics(sourceFile)) {
60339                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60340                             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);
60341                             var func = ts.getContainingFunction(node);
60342                             if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
60343                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
60344                                 ts.addRelatedInfo(diagnostic, relatedInfo);
60345                             }
60346                             diagnostics.add(diagnostic);
60347                         }
60348                     }
60349                 }
60350                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60351                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
60352                 }
60353             }
60354             var operandType = checkExpression(node.expression);
60355             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);
60356             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
60357                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
60358             }
60359             return awaitedType;
60360         }
60361         function checkPrefixUnaryExpression(node) {
60362             var operandType = checkExpression(node.operand);
60363             if (operandType === silentNeverType) {
60364                 return silentNeverType;
60365             }
60366             switch (node.operand.kind) {
60367                 case 8 /* NumericLiteral */:
60368                     switch (node.operator) {
60369                         case 40 /* MinusToken */:
60370                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
60371                         case 39 /* PlusToken */:
60372                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
60373                     }
60374                     break;
60375                 case 9 /* BigIntLiteral */:
60376                     if (node.operator === 40 /* MinusToken */) {
60377                         return getFreshTypeOfLiteralType(getLiteralType({
60378                             negative: true,
60379                             base10Value: ts.parsePseudoBigInt(node.operand.text)
60380                         }));
60381                     }
60382             }
60383             switch (node.operator) {
60384                 case 39 /* PlusToken */:
60385                 case 40 /* MinusToken */:
60386                 case 54 /* TildeToken */:
60387                     checkNonNullType(operandType, node.operand);
60388                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
60389                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
60390                     }
60391                     if (node.operator === 39 /* PlusToken */) {
60392                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60393                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
60394                         }
60395                         return numberType;
60396                     }
60397                     return getUnaryResultType(operandType);
60398                 case 53 /* ExclamationToken */:
60399                     checkTruthinessExpression(node.operand);
60400                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
60401                     return facts === 4194304 /* Truthy */ ? falseType :
60402                         facts === 8388608 /* Falsy */ ? trueType :
60403                             booleanType;
60404                 case 45 /* PlusPlusToken */:
60405                 case 46 /* MinusMinusToken */:
60406                     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);
60407                     if (ok) {
60408                         // run check only if former checks succeeded to avoid reporting cascading errors
60409                         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);
60410                     }
60411                     return getUnaryResultType(operandType);
60412             }
60413             return errorType;
60414         }
60415         function checkPostfixUnaryExpression(node) {
60416             var operandType = checkExpression(node.operand);
60417             if (operandType === silentNeverType) {
60418                 return silentNeverType;
60419             }
60420             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);
60421             if (ok) {
60422                 // run check only if former checks succeeded to avoid reporting cascading errors
60423                 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);
60424             }
60425             return getUnaryResultType(operandType);
60426         }
60427         function getUnaryResultType(operandType) {
60428             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60429                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
60430                     ? numberOrBigIntType
60431                     : bigintType;
60432             }
60433             // If it's not a bigint type, implicit coercion will result in a number
60434             return numberType;
60435         }
60436         // Return true if type might be of the given kind. A union or intersection type might be of a given
60437         // kind if at least one constituent type is of the given kind.
60438         function maybeTypeOfKind(type, kind) {
60439             if (type.flags & kind) {
60440                 return true;
60441             }
60442             if (type.flags & 3145728 /* UnionOrIntersection */) {
60443                 var types = type.types;
60444                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
60445                     var t = types_19[_i];
60446                     if (maybeTypeOfKind(t, kind)) {
60447                         return true;
60448                     }
60449                 }
60450             }
60451             return false;
60452         }
60453         function isTypeAssignableToKind(source, kind, strict) {
60454             if (source.flags & kind) {
60455                 return true;
60456             }
60457             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
60458                 return false;
60459             }
60460             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
60461                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
60462                 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
60463                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
60464                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
60465                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
60466                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
60467                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
60468                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
60469                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
60470         }
60471         function allTypesAssignableToKind(source, kind, strict) {
60472             return source.flags & 1048576 /* Union */ ?
60473                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
60474                 isTypeAssignableToKind(source, kind, strict);
60475         }
60476         function isConstEnumObjectType(type) {
60477             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
60478         }
60479         function isConstEnumSymbol(symbol) {
60480             return (symbol.flags & 128 /* ConstEnum */) !== 0;
60481         }
60482         function checkInstanceOfExpression(left, right, leftType, rightType) {
60483             if (leftType === silentNeverType || rightType === silentNeverType) {
60484                 return silentNeverType;
60485             }
60486             // TypeScript 1.0 spec (April 2014): 4.15.4
60487             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
60488             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
60489             // The result is always of the Boolean primitive type.
60490             // NOTE: do not raise error if leftType is unknown as related error was already reported
60491             if (!isTypeAny(leftType) &&
60492                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
60493                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60494             }
60495             // NOTE: do not raise error if right is unknown as related error was already reported
60496             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
60497                 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);
60498             }
60499             return booleanType;
60500         }
60501         function checkInExpression(left, right, leftType, rightType) {
60502             if (leftType === silentNeverType || rightType === silentNeverType) {
60503                 return silentNeverType;
60504             }
60505             leftType = checkNonNullType(leftType, left);
60506             rightType = checkNonNullType(rightType, right);
60507             // TypeScript 1.0 spec (April 2014): 4.15.5
60508             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
60509             // and the right operand to be of type Any, an object type, or a type parameter type.
60510             // The result is always of the Boolean primitive type.
60511             if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
60512                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
60513             }
60514             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
60515                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60516             }
60517             return booleanType;
60518         }
60519         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
60520             var properties = node.properties;
60521             if (strictNullChecks && properties.length === 0) {
60522                 return checkNonNullType(sourceType, node);
60523             }
60524             for (var i = 0; i < properties.length; i++) {
60525                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
60526             }
60527             return sourceType;
60528         }
60529         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
60530         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
60531             if (rightIsThis === void 0) { rightIsThis = false; }
60532             var properties = node.properties;
60533             var property = properties[propertyIndex];
60534             if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
60535                 var name = property.name;
60536                 var exprType = getLiteralTypeFromPropertyName(name);
60537                 if (isTypeUsableAsPropertyName(exprType)) {
60538                     var text = getPropertyNameFromType(exprType);
60539                     var prop = getPropertyOfType(objectLiteralType, text);
60540                     if (prop) {
60541                         markPropertyAsReferenced(prop, property, rightIsThis);
60542                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
60543                     }
60544                 }
60545                 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
60546                 var type = getFlowTypeOfDestructuring(property, elementType);
60547                 return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
60548             }
60549             else if (property.kind === 283 /* SpreadAssignment */) {
60550                 if (propertyIndex < properties.length - 1) {
60551                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60552                 }
60553                 else {
60554                     if (languageVersion < 99 /* ESNext */) {
60555                         checkExternalEmitHelpers(property, 4 /* Rest */);
60556                     }
60557                     var nonRestNames = [];
60558                     if (allProperties) {
60559                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
60560                             var otherProperty = allProperties_1[_i];
60561                             if (!ts.isSpreadAssignment(otherProperty)) {
60562                                 nonRestNames.push(otherProperty.name);
60563                             }
60564                         }
60565                     }
60566                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
60567                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60568                     return checkDestructuringAssignment(property.expression, type);
60569                 }
60570             }
60571             else {
60572                 error(property, ts.Diagnostics.Property_assignment_expected);
60573             }
60574         }
60575         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
60576             var elements = node.elements;
60577             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
60578                 checkExternalEmitHelpers(node, 512 /* Read */);
60579             }
60580             // This elementType will be used if the specific property corresponding to this index is not
60581             // present (aka the tuple element property). This call also checks that the parentType is in
60582             // fact an iterable or array (depending on target language).
60583             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
60584             for (var i = 0; i < elements.length; i++) {
60585                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
60586             }
60587             return sourceType;
60588         }
60589         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
60590             var elements = node.elements;
60591             var element = elements[elementIndex];
60592             if (element.kind !== 215 /* OmittedExpression */) {
60593                 if (element.kind !== 213 /* SpreadElement */) {
60594                     var indexType = getLiteralType(elementIndex);
60595                     if (isArrayLikeType(sourceType)) {
60596                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
60597                         // when the element is a SyntaxKind.ElementAccessExpression.
60598                         var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
60599                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
60600                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
60601                         var type = getFlowTypeOfDestructuring(element, assignedType);
60602                         return checkDestructuringAssignment(element, type, checkMode);
60603                     }
60604                     return checkDestructuringAssignment(element, elementType, checkMode);
60605                 }
60606                 if (elementIndex < elements.length - 1) {
60607                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60608                 }
60609                 else {
60610                     var restExpression = element.expression;
60611                     if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
60612                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
60613                     }
60614                     else {
60615                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60616                         var type = everyType(sourceType, isTupleType) ?
60617                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
60618                             createArrayType(elementType);
60619                         return checkDestructuringAssignment(restExpression, type, checkMode);
60620                     }
60621                 }
60622             }
60623             return undefined;
60624         }
60625         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
60626             var target;
60627             if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
60628                 var prop = exprOrAssignment;
60629                 if (prop.objectAssignmentInitializer) {
60630                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
60631                     // undefined from the final type.
60632                     if (strictNullChecks &&
60633                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
60634                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
60635                     }
60636                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
60637                 }
60638                 target = exprOrAssignment.name;
60639             }
60640             else {
60641                 target = exprOrAssignment;
60642             }
60643             if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
60644                 checkBinaryExpression(target, checkMode);
60645                 target = target.left;
60646             }
60647             if (target.kind === 193 /* ObjectLiteralExpression */) {
60648                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
60649             }
60650             if (target.kind === 192 /* ArrayLiteralExpression */) {
60651                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
60652             }
60653             return checkReferenceAssignment(target, sourceType, checkMode);
60654         }
60655         function checkReferenceAssignment(target, sourceType, checkMode) {
60656             var targetType = checkExpression(target, checkMode);
60657             var error = target.parent.kind === 283 /* SpreadAssignment */ ?
60658                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
60659                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
60660             var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
60661                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
60662                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
60663             if (checkReferenceExpression(target, error, optionalError)) {
60664                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
60665             }
60666             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
60667                 checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
60668             }
60669             return sourceType;
60670         }
60671         /**
60672          * This is a *shallow* check: An expression is side-effect-free if the
60673          * evaluation of the expression *itself* cannot produce side effects.
60674          * For example, x++ / 3 is side-effect free because the / operator
60675          * does not have side effects.
60676          * The intent is to "smell test" an expression for correctness in positions where
60677          * its value is discarded (e.g. the left side of the comma operator).
60678          */
60679         function isSideEffectFree(node) {
60680             node = ts.skipParentheses(node);
60681             switch (node.kind) {
60682                 case 75 /* Identifier */:
60683                 case 10 /* StringLiteral */:
60684                 case 13 /* RegularExpressionLiteral */:
60685                 case 198 /* TaggedTemplateExpression */:
60686                 case 211 /* TemplateExpression */:
60687                 case 14 /* NoSubstitutionTemplateLiteral */:
60688                 case 8 /* NumericLiteral */:
60689                 case 9 /* BigIntLiteral */:
60690                 case 106 /* TrueKeyword */:
60691                 case 91 /* FalseKeyword */:
60692                 case 100 /* NullKeyword */:
60693                 case 146 /* UndefinedKeyword */:
60694                 case 201 /* FunctionExpression */:
60695                 case 214 /* ClassExpression */:
60696                 case 202 /* ArrowFunction */:
60697                 case 192 /* ArrayLiteralExpression */:
60698                 case 193 /* ObjectLiteralExpression */:
60699                 case 204 /* TypeOfExpression */:
60700                 case 218 /* NonNullExpression */:
60701                 case 267 /* JsxSelfClosingElement */:
60702                 case 266 /* JsxElement */:
60703                     return true;
60704                 case 210 /* ConditionalExpression */:
60705                     return isSideEffectFree(node.whenTrue) &&
60706                         isSideEffectFree(node.whenFalse);
60707                 case 209 /* BinaryExpression */:
60708                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
60709                         return false;
60710                     }
60711                     return isSideEffectFree(node.left) &&
60712                         isSideEffectFree(node.right);
60713                 case 207 /* PrefixUnaryExpression */:
60714                 case 208 /* PostfixUnaryExpression */:
60715                     // Unary operators ~, !, +, and - have no side effects.
60716                     // The rest do.
60717                     switch (node.operator) {
60718                         case 53 /* ExclamationToken */:
60719                         case 39 /* PlusToken */:
60720                         case 40 /* MinusToken */:
60721                         case 54 /* TildeToken */:
60722                             return true;
60723                     }
60724                     return false;
60725                 // Some forms listed here for clarity
60726                 case 205 /* VoidExpression */: // Explicit opt-out
60727                 case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
60728                 case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
60729                 default:
60730                     return false;
60731             }
60732         }
60733         function isTypeEqualityComparableTo(source, target) {
60734             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
60735         }
60736         var CheckBinaryExpressionState;
60737         (function (CheckBinaryExpressionState) {
60738             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
60739             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
60740             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
60741         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
60742         function checkBinaryExpression(node, checkMode) {
60743             var workStacks = {
60744                 expr: [node],
60745                 state: [0 /* MaybeCheckLeft */],
60746                 leftType: [undefined]
60747             };
60748             var stackIndex = 0;
60749             var lastResult;
60750             while (stackIndex >= 0) {
60751                 node = workStacks.expr[stackIndex];
60752                 switch (workStacks.state[stackIndex]) {
60753                     case 0 /* MaybeCheckLeft */: {
60754                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
60755                             finishInvocation(checkExpression(node.right, checkMode));
60756                             break;
60757                         }
60758                         checkGrammarNullishCoalesceWithLogicalExpression(node);
60759                         var operator = node.operatorToken.kind;
60760                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
60761                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
60762                             break;
60763                         }
60764                         advanceState(1 /* CheckRight */);
60765                         maybeCheckExpression(node.left);
60766                         break;
60767                     }
60768                     case 1 /* CheckRight */: {
60769                         var leftType = lastResult;
60770                         workStacks.leftType[stackIndex] = leftType;
60771                         var operator = node.operatorToken.kind;
60772                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60773                             checkTruthinessOfType(leftType, node.left);
60774                         }
60775                         advanceState(2 /* FinishCheck */);
60776                         maybeCheckExpression(node.right);
60777                         break;
60778                     }
60779                     case 2 /* FinishCheck */: {
60780                         var leftType = workStacks.leftType[stackIndex];
60781                         var rightType = lastResult;
60782                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
60783                         break;
60784                     }
60785                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
60786                 }
60787             }
60788             return lastResult;
60789             function finishInvocation(result) {
60790                 lastResult = result;
60791                 stackIndex--;
60792             }
60793             /**
60794              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
60795              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
60796              */
60797             function advanceState(nextState) {
60798                 workStacks.state[stackIndex] = nextState;
60799             }
60800             function maybeCheckExpression(node) {
60801                 if (ts.isBinaryExpression(node)) {
60802                     stackIndex++;
60803                     workStacks.expr[stackIndex] = node;
60804                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
60805                     workStacks.leftType[stackIndex] = undefined;
60806                 }
60807                 else {
60808                     lastResult = checkExpression(node, checkMode);
60809                 }
60810             }
60811         }
60812         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
60813             var left = node.left, operatorToken = node.operatorToken, right = node.right;
60814             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
60815                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60816                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60817                 }
60818                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60819                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60820                 }
60821             }
60822         }
60823         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
60824         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
60825         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
60826             var operator = operatorToken.kind;
60827             if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
60828                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
60829             }
60830             var leftType;
60831             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60832                 leftType = checkTruthinessExpression(left, checkMode);
60833             }
60834             else {
60835                 leftType = checkExpression(left, checkMode);
60836             }
60837             var rightType = checkExpression(right, checkMode);
60838             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
60839         }
60840         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
60841             var operator = operatorToken.kind;
60842             switch (operator) {
60843                 case 41 /* AsteriskToken */:
60844                 case 42 /* AsteriskAsteriskToken */:
60845                 case 65 /* AsteriskEqualsToken */:
60846                 case 66 /* AsteriskAsteriskEqualsToken */:
60847                 case 43 /* SlashToken */:
60848                 case 67 /* SlashEqualsToken */:
60849                 case 44 /* PercentToken */:
60850                 case 68 /* PercentEqualsToken */:
60851                 case 40 /* MinusToken */:
60852                 case 64 /* MinusEqualsToken */:
60853                 case 47 /* LessThanLessThanToken */:
60854                 case 69 /* LessThanLessThanEqualsToken */:
60855                 case 48 /* GreaterThanGreaterThanToken */:
60856                 case 70 /* GreaterThanGreaterThanEqualsToken */:
60857                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60858                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60859                 case 51 /* BarToken */:
60860                 case 73 /* BarEqualsToken */:
60861                 case 52 /* CaretToken */:
60862                 case 74 /* CaretEqualsToken */:
60863                 case 50 /* AmpersandToken */:
60864                 case 72 /* AmpersandEqualsToken */:
60865                     if (leftType === silentNeverType || rightType === silentNeverType) {
60866                         return silentNeverType;
60867                     }
60868                     leftType = checkNonNullType(leftType, left);
60869                     rightType = checkNonNullType(rightType, right);
60870                     var suggestedOperator = void 0;
60871                     // if a user tries to apply a bitwise operator to 2 boolean operands
60872                     // try and return them a helpful suggestion
60873                     if ((leftType.flags & 528 /* BooleanLike */) &&
60874                         (rightType.flags & 528 /* BooleanLike */) &&
60875                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
60876                         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));
60877                         return numberType;
60878                     }
60879                     else {
60880                         // otherwise just check each operand separately and report errors as normal
60881                         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);
60882                         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);
60883                         var resultType_1;
60884                         // If both are any or unknown, allow operation; assume it will resolve to number
60885                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
60886                             // Or, if neither could be bigint, implicit coercion results in a number result
60887                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
60888                             resultType_1 = numberType;
60889                         }
60890                         // At least one is assignable to bigint, so check that both are
60891                         else if (bothAreBigIntLike(leftType, rightType)) {
60892                             switch (operator) {
60893                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60894                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60895                                     reportOperatorError();
60896                             }
60897                             resultType_1 = bigintType;
60898                         }
60899                         // Exactly one of leftType/rightType is assignable to bigint
60900                         else {
60901                             reportOperatorError(bothAreBigIntLike);
60902                             resultType_1 = errorType;
60903                         }
60904                         if (leftOk && rightOk) {
60905                             checkAssignmentOperator(resultType_1);
60906                         }
60907                         return resultType_1;
60908                     }
60909                 case 39 /* PlusToken */:
60910                 case 63 /* PlusEqualsToken */:
60911                     if (leftType === silentNeverType || rightType === silentNeverType) {
60912                         return silentNeverType;
60913                     }
60914                     if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
60915                         leftType = checkNonNullType(leftType, left);
60916                         rightType = checkNonNullType(rightType, right);
60917                     }
60918                     var resultType = void 0;
60919                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
60920                         // Operands of an enum type are treated as having the primitive type Number.
60921                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
60922                         resultType = numberType;
60923                     }
60924                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
60925                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
60926                         resultType = bigintType;
60927                     }
60928                     else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
60929                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
60930                         resultType = stringType;
60931                     }
60932                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
60933                         // Otherwise, the result is of type Any.
60934                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
60935                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
60936                     }
60937                     // Symbols are not allowed at all in arithmetic expressions
60938                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
60939                         return resultType;
60940                     }
60941                     if (!resultType) {
60942                         // Types that have a reasonably good chance of being a valid operand type.
60943                         // If both types have an awaited type of one of these, we'll assume the user
60944                         // might be missing an await without doing an exhaustive check that inserting
60945                         // await(s) will actually be a completely valid binary expression.
60946                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
60947                         reportOperatorError(function (left, right) {
60948                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
60949                                 isTypeAssignableToKind(right, closeEnoughKind_1);
60950                         });
60951                         return anyType;
60952                     }
60953                     if (operator === 63 /* PlusEqualsToken */) {
60954                         checkAssignmentOperator(resultType);
60955                     }
60956                     return resultType;
60957                 case 29 /* LessThanToken */:
60958                 case 31 /* GreaterThanToken */:
60959                 case 32 /* LessThanEqualsToken */:
60960                 case 33 /* GreaterThanEqualsToken */:
60961                     if (checkForDisallowedESSymbolOperand(operator)) {
60962                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
60963                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
60964                         reportOperatorErrorUnless(function (left, right) {
60965                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
60966                         });
60967                     }
60968                     return booleanType;
60969                 case 34 /* EqualsEqualsToken */:
60970                 case 35 /* ExclamationEqualsToken */:
60971                 case 36 /* EqualsEqualsEqualsToken */:
60972                 case 37 /* ExclamationEqualsEqualsToken */:
60973                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
60974                     return booleanType;
60975                 case 98 /* InstanceOfKeyword */:
60976                     return checkInstanceOfExpression(left, right, leftType, rightType);
60977                 case 97 /* InKeyword */:
60978                     return checkInExpression(left, right, leftType, rightType);
60979                 case 55 /* AmpersandAmpersandToken */:
60980                     return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
60981                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
60982                         leftType;
60983                 case 56 /* BarBarToken */:
60984                     return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
60985                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
60986                         leftType;
60987                 case 60 /* QuestionQuestionToken */:
60988                     return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
60989                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
60990                         leftType;
60991                 case 62 /* EqualsToken */:
60992                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
60993                     checkAssignmentDeclaration(declKind, rightType);
60994                     if (isAssignmentDeclaration(declKind)) {
60995                         if (!(rightType.flags & 524288 /* Object */) ||
60996                             declKind !== 2 /* ModuleExports */ &&
60997                                 declKind !== 6 /* Prototype */ &&
60998                                 !isEmptyObjectType(rightType) &&
60999                                 !isFunctionObjectType(rightType) &&
61000                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
61001                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
61002                             checkAssignmentOperator(rightType);
61003                         }
61004                         return leftType;
61005                     }
61006                     else {
61007                         checkAssignmentOperator(rightType);
61008                         return getRegularTypeOfObjectLiteral(rightType);
61009                     }
61010                 case 27 /* CommaToken */:
61011                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
61012                         error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
61013                     }
61014                     return rightType;
61015                 default:
61016                     return ts.Debug.fail();
61017             }
61018             function bothAreBigIntLike(left, right) {
61019                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
61020             }
61021             function checkAssignmentDeclaration(kind, rightType) {
61022                 if (kind === 2 /* ModuleExports */) {
61023                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
61024                         var prop = _a[_i];
61025                         var propType = getTypeOfSymbol(prop);
61026                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
61027                             var name = prop.escapedName;
61028                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
61029                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
61030                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
61031                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
61032                             }
61033                         }
61034                     }
61035                 }
61036             }
61037             function isEvalNode(node) {
61038                 return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
61039             }
61040             // Return true if there was no error, false if there was an error.
61041             function checkForDisallowedESSymbolOperand(operator) {
61042                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
61043                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
61044                         undefined;
61045                 if (offendingSymbolOperand) {
61046                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
61047                     return false;
61048                 }
61049                 return true;
61050             }
61051             function getSuggestedBooleanOperator(operator) {
61052                 switch (operator) {
61053                     case 51 /* BarToken */:
61054                     case 73 /* BarEqualsToken */:
61055                         return 56 /* BarBarToken */;
61056                     case 52 /* CaretToken */:
61057                     case 74 /* CaretEqualsToken */:
61058                         return 37 /* ExclamationEqualsEqualsToken */;
61059                     case 50 /* AmpersandToken */:
61060                     case 72 /* AmpersandEqualsToken */:
61061                         return 55 /* AmpersandAmpersandToken */;
61062                     default:
61063                         return undefined;
61064                 }
61065             }
61066             function checkAssignmentOperator(valueType) {
61067                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
61068                     // TypeScript 1.0 spec (April 2014): 4.17
61069                     // An assignment of the form
61070                     //    VarExpr = ValueExpr
61071                     // requires VarExpr to be classified as a reference
61072                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
61073                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
61074                     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)
61075                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
61076                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
61077                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
61078                     }
61079                 }
61080             }
61081             function isAssignmentDeclaration(kind) {
61082                 switch (kind) {
61083                     case 2 /* ModuleExports */:
61084                         return true;
61085                     case 1 /* ExportsProperty */:
61086                     case 5 /* Property */:
61087                     case 6 /* Prototype */:
61088                     case 3 /* PrototypeProperty */:
61089                     case 4 /* ThisProperty */:
61090                         var symbol = getSymbolOfNode(left);
61091                         var init = ts.getAssignedExpandoInitializer(right);
61092                         return init && ts.isObjectLiteralExpression(init) &&
61093                             symbol && ts.hasEntries(symbol.exports);
61094                     default:
61095                         return false;
61096                 }
61097             }
61098             /**
61099              * Returns true if an error is reported
61100              */
61101             function reportOperatorErrorUnless(typesAreCompatible) {
61102                 if (!typesAreCompatible(leftType, rightType)) {
61103                     reportOperatorError(typesAreCompatible);
61104                     return true;
61105                 }
61106                 return false;
61107             }
61108             function reportOperatorError(isRelated) {
61109                 var _a;
61110                 var wouldWorkWithAwait = false;
61111                 var errNode = errorNode || operatorToken;
61112                 if (isRelated) {
61113                     var awaitedLeftType = getAwaitedType(leftType);
61114                     var awaitedRightType = getAwaitedType(rightType);
61115                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
61116                         && !!(awaitedLeftType && awaitedRightType)
61117                         && isRelated(awaitedLeftType, awaitedRightType);
61118                 }
61119                 var effectiveLeft = leftType;
61120                 var effectiveRight = rightType;
61121                 if (!wouldWorkWithAwait && isRelated) {
61122                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
61123                 }
61124                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
61125                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
61126                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
61127                 }
61128             }
61129             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
61130                 var typeName;
61131                 switch (operatorToken.kind) {
61132                     case 36 /* EqualsEqualsEqualsToken */:
61133                     case 34 /* EqualsEqualsToken */:
61134                         typeName = "false";
61135                         break;
61136                     case 37 /* ExclamationEqualsEqualsToken */:
61137                     case 35 /* ExclamationEqualsToken */:
61138                         typeName = "true";
61139                 }
61140                 if (typeName) {
61141                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
61142                 }
61143                 return undefined;
61144             }
61145         }
61146         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
61147             var effectiveLeft = leftType;
61148             var effectiveRight = rightType;
61149             var leftBase = getBaseTypeOfLiteralType(leftType);
61150             var rightBase = getBaseTypeOfLiteralType(rightType);
61151             if (!isRelated(leftBase, rightBase)) {
61152                 effectiveLeft = leftBase;
61153                 effectiveRight = rightBase;
61154             }
61155             return [effectiveLeft, effectiveRight];
61156         }
61157         function checkYieldExpression(node) {
61158             // Grammar checking
61159             if (produceDiagnostics) {
61160                 if (!(node.flags & 8192 /* YieldContext */)) {
61161                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
61162                 }
61163                 if (isInParameterInitializerBeforeContainingFunction(node)) {
61164                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
61165                 }
61166             }
61167             var func = ts.getContainingFunction(node);
61168             if (!func)
61169                 return anyType;
61170             var functionFlags = ts.getFunctionFlags(func);
61171             if (!(functionFlags & 1 /* Generator */)) {
61172                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
61173                 return anyType;
61174             }
61175             var isAsync = (functionFlags & 2 /* Async */) !== 0;
61176             if (node.asteriskToken) {
61177                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
61178                 // and __asyncValues helpers
61179                 if (isAsync && languageVersion < 99 /* ESNext */) {
61180                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
61181                 }
61182                 // Generator functions prior to ES2015 require the __values helper
61183                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
61184                     checkExternalEmitHelpers(node, 256 /* Values */);
61185                 }
61186             }
61187             // There is no point in doing an assignability check if the function
61188             // has no explicit return type because the return type is directly computed
61189             // from the yield expressions.
61190             var returnType = getReturnTypeFromAnnotation(func);
61191             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
61192             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
61193             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
61194             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
61195             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
61196             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
61197             if (returnType && yieldedType) {
61198                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
61199             }
61200             if (node.asteriskToken) {
61201                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
61202                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
61203                     || anyType;
61204             }
61205             else if (returnType) {
61206                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
61207                     || anyType;
61208             }
61209             return getContextualIterationType(2 /* Next */, func) || anyType;
61210         }
61211         function checkConditionalExpression(node, checkMode) {
61212             var type = checkTruthinessExpression(node.condition);
61213             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
61214             var type1 = checkExpression(node.whenTrue, checkMode);
61215             var type2 = checkExpression(node.whenFalse, checkMode);
61216             return getUnionType([type1, type2], 2 /* Subtype */);
61217         }
61218         function checkTemplateExpression(node) {
61219             // We just want to check each expressions, but we are unconcerned with
61220             // the type of each expression, as any value may be coerced into a string.
61221             // It is worth asking whether this is what we really want though.
61222             // A place where we actually *are* concerned with the expressions' types are
61223             // in tagged templates.
61224             ts.forEach(node.templateSpans, function (templateSpan) {
61225                 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
61226                     error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
61227                 }
61228             });
61229             return stringType;
61230         }
61231         function getContextNode(node) {
61232             if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
61233                 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)
61234             }
61235             return node;
61236         }
61237         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
61238             var context = getContextNode(node);
61239             var saveContextualType = context.contextualType;
61240             var saveInferenceContext = context.inferenceContext;
61241             try {
61242                 context.contextualType = contextualType;
61243                 context.inferenceContext = inferenceContext;
61244                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
61245                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
61246                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
61247                 // here would be to not mark contextually typed literals as fresh in the first place.
61248                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
61249                     getRegularTypeOfLiteralType(type) : type;
61250                 return result;
61251             }
61252             finally {
61253                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61254                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61255                 // may hold onto the checker that created it.
61256                 context.contextualType = saveContextualType;
61257                 context.inferenceContext = saveInferenceContext;
61258             }
61259         }
61260         function checkExpressionCached(node, checkMode) {
61261             var links = getNodeLinks(node);
61262             if (!links.resolvedType) {
61263                 if (checkMode && checkMode !== 0 /* Normal */) {
61264                     return checkExpression(node, checkMode);
61265                 }
61266                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
61267                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
61268                 // to the top of the stack ensures all transient types are computed from a known point.
61269                 var saveFlowLoopStart = flowLoopStart;
61270                 var saveFlowTypeCache = flowTypeCache;
61271                 flowLoopStart = flowLoopCount;
61272                 flowTypeCache = undefined;
61273                 links.resolvedType = checkExpression(node, checkMode);
61274                 flowTypeCache = saveFlowTypeCache;
61275                 flowLoopStart = saveFlowLoopStart;
61276             }
61277             return links.resolvedType;
61278         }
61279         function isTypeAssertion(node) {
61280             node = ts.skipParentheses(node);
61281             return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
61282         }
61283         function checkDeclarationInitializer(declaration, contextualType) {
61284             var initializer = ts.getEffectiveInitializer(declaration);
61285             var type = getQuickTypeOfExpression(initializer) ||
61286                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
61287             return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
61288                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
61289                 padTupleType(type, declaration.name) : type;
61290         }
61291         function padTupleType(type, pattern) {
61292             var patternElements = pattern.elements;
61293             var arity = getTypeReferenceArity(type);
61294             var elementTypes = arity ? getTypeArguments(type).slice() : [];
61295             for (var i = arity; i < patternElements.length; i++) {
61296                 var e = patternElements[i];
61297                 if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
61298                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
61299                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
61300                         reportImplicitAny(e, anyType);
61301                     }
61302                 }
61303             }
61304             return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
61305         }
61306         function widenTypeInferredFromInitializer(declaration, type) {
61307             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
61308             if (ts.isInJSFile(declaration)) {
61309                 if (widened.flags & 98304 /* Nullable */) {
61310                     reportImplicitAny(declaration, anyType);
61311                     return anyType;
61312                 }
61313                 else if (isEmptyArrayLiteralType(widened)) {
61314                     reportImplicitAny(declaration, anyArrayType);
61315                     return anyArrayType;
61316                 }
61317             }
61318             return widened;
61319         }
61320         function isLiteralOfContextualType(candidateType, contextualType) {
61321             if (contextualType) {
61322                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
61323                     var types = contextualType.types;
61324                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
61325                 }
61326                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
61327                     // If the contextual type is a type variable constrained to a primitive type, consider
61328                     // this a literal context for literals of that primitive type. For example, given a
61329                     // type parameter 'T extends string', infer string literal types for T.
61330                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
61331                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61332                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61333                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61334                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
61335                         isLiteralOfContextualType(candidateType, constraint);
61336                 }
61337                 // If the contextual type is a literal of a particular primitive type, we consider this a
61338                 // literal context for all literals of that primitive type.
61339                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61340                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61341                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61342                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
61343                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
61344             }
61345             return false;
61346         }
61347         function isConstContext(node) {
61348             var parent = node.parent;
61349             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
61350                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
61351                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
61352         }
61353         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
61354             var type = checkExpression(node, checkMode, forceTuple);
61355             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
61356                 isTypeAssertion(node) ? type :
61357                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
61358         }
61359         function checkPropertyAssignment(node, checkMode) {
61360             // Do not use hasDynamicName here, because that returns false for well known symbols.
61361             // We want to perform checkComputedPropertyName for all computed properties, including
61362             // well known symbols.
61363             if (node.name.kind === 154 /* ComputedPropertyName */) {
61364                 checkComputedPropertyName(node.name);
61365             }
61366             return checkExpressionForMutableLocation(node.initializer, checkMode);
61367         }
61368         function checkObjectLiteralMethod(node, checkMode) {
61369             // Grammar checking
61370             checkGrammarMethod(node);
61371             // Do not use hasDynamicName here, because that returns false for well known symbols.
61372             // We want to perform checkComputedPropertyName for all computed properties, including
61373             // well known symbols.
61374             if (node.name.kind === 154 /* ComputedPropertyName */) {
61375                 checkComputedPropertyName(node.name);
61376             }
61377             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61378             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61379         }
61380         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
61381             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
61382                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
61383                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
61384                 var signature = callSignature || constructSignature;
61385                 if (signature && signature.typeParameters) {
61386                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
61387                     if (contextualType) {
61388                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
61389                         if (contextualSignature && !contextualSignature.typeParameters) {
61390                             if (checkMode & 8 /* SkipGenericFunctions */) {
61391                                 skippedGenericFunction(node, checkMode);
61392                                 return anyFunctionType;
61393                             }
61394                             var context = getInferenceContext(node);
61395                             // We have an expression that is an argument of a generic function for which we are performing
61396                             // type argument inference. The expression is of a function type with a single generic call
61397                             // signature and a contextual function type with a single non-generic call signature. Now check
61398                             // if the outer function returns a function type with a single non-generic call signature and
61399                             // if some of the outer function type parameters have no inferences so far. If so, we can
61400                             // potentially add inferred type parameters to the outer function return type.
61401                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
61402                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
61403                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
61404                                 // Instantiate the signature with its own type parameters as type arguments, possibly
61405                                 // renaming the type parameters to ensure they have unique names.
61406                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
61407                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
61408                                 // Infer from the parameters of the instantiated signature to the parameters of the
61409                                 // contextual signature starting with an empty set of inference candidates.
61410                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
61411                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
61412                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
61413                                 });
61414                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
61415                                     // We have inference candidates, indicating that one or more type parameters are referenced
61416                                     // in the parameter types of the contextual signature. Now also infer from the return type.
61417                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
61418                                         inferTypes(inferences_3, source, target);
61419                                     });
61420                                     // If the type parameters for which we produced candidates do not have any inferences yet,
61421                                     // we adopt the new inference candidates and add the type parameters of the expression type
61422                                     // to the set of inferred type parameters for the outer function return type.
61423                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
61424                                         mergeInferences(context.inferences, inferences_3);
61425                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
61426                                         return getOrCreateTypeFromSignature(instantiatedSignature);
61427                                     }
61428                                 }
61429                             }
61430                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
61431                         }
61432                     }
61433                 }
61434             }
61435             return type;
61436         }
61437         function skippedGenericFunction(node, checkMode) {
61438             if (checkMode & 2 /* Inferential */) {
61439                 // We have skipped a generic function during inferential typing. Obtain the inference context and
61440                 // indicate this has occurred such that we know a second pass of inference is be needed.
61441                 var context = getInferenceContext(node);
61442                 context.flags |= 4 /* SkippedGenericFunction */;
61443             }
61444         }
61445         function hasInferenceCandidates(info) {
61446             return !!(info.candidates || info.contraCandidates);
61447         }
61448         function hasOverlappingInferences(a, b) {
61449             for (var i = 0; i < a.length; i++) {
61450                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
61451                     return true;
61452                 }
61453             }
61454             return false;
61455         }
61456         function mergeInferences(target, source) {
61457             for (var i = 0; i < target.length; i++) {
61458                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
61459                     target[i] = source[i];
61460                 }
61461             }
61462         }
61463         function getUniqueTypeParameters(context, typeParameters) {
61464             var result = [];
61465             var oldTypeParameters;
61466             var newTypeParameters;
61467             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
61468                 var tp = typeParameters_2[_i];
61469                 var name = tp.symbol.escapedName;
61470                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
61471                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
61472                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
61473                     var newTypeParameter = createTypeParameter(symbol);
61474                     newTypeParameter.target = tp;
61475                     oldTypeParameters = ts.append(oldTypeParameters, tp);
61476                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
61477                     result.push(newTypeParameter);
61478                 }
61479                 else {
61480                     result.push(tp);
61481                 }
61482             }
61483             if (newTypeParameters) {
61484                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
61485                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
61486                     var tp = newTypeParameters_1[_a];
61487                     tp.mapper = mapper;
61488                 }
61489             }
61490             return result;
61491         }
61492         function hasTypeParameterByName(typeParameters, name) {
61493             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
61494         }
61495         function getUniqueTypeParameterName(typeParameters, baseName) {
61496             var len = baseName.length;
61497             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
61498                 len--;
61499             var s = baseName.slice(0, len);
61500             for (var index = 1; true; index++) {
61501                 var augmentedName = (s + index);
61502                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
61503                     return augmentedName;
61504                 }
61505             }
61506         }
61507         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
61508             var signature = getSingleCallSignature(funcType);
61509             if (signature && !signature.typeParameters) {
61510                 return getReturnTypeOfSignature(signature);
61511             }
61512         }
61513         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
61514             var funcType = checkExpression(expr.expression);
61515             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
61516             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
61517             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
61518         }
61519         /**
61520          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61521          * with computing the type and may not fully check all contained sub-expressions for errors.
61522          */
61523         function getTypeOfExpression(node) {
61524             // Don't bother caching types that require no flow analysis and are quick to compute.
61525             var quickType = getQuickTypeOfExpression(node);
61526             if (quickType) {
61527                 return quickType;
61528             }
61529             // If a type has been cached for the node, return it.
61530             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
61531                 var cachedType = flowTypeCache[getNodeId(node)];
61532                 if (cachedType) {
61533                     return cachedType;
61534                 }
61535             }
61536             var startInvocationCount = flowInvocationCount;
61537             var type = checkExpression(node);
61538             // If control flow analysis was required to determine the type, it is worth caching.
61539             if (flowInvocationCount !== startInvocationCount) {
61540                 var cache = flowTypeCache || (flowTypeCache = []);
61541                 cache[getNodeId(node)] = type;
61542                 node.flags |= 67108864 /* TypeCached */;
61543             }
61544             return type;
61545         }
61546         function getQuickTypeOfExpression(node) {
61547             var expr = ts.skipParentheses(node);
61548             // Optimize for the common case of a call to a function with a single non-generic call
61549             // signature where we can just fetch the return type without checking the arguments.
61550             if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
61551                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
61552                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
61553                 if (type) {
61554                     return type;
61555                 }
61556             }
61557             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
61558                 return getTypeFromTypeNode(expr.type);
61559             }
61560             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
61561                 node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
61562                 return checkExpression(node);
61563             }
61564             return undefined;
61565         }
61566         /**
61567          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61568          * with computing the type and may not fully check all contained sub-expressions for errors.
61569          * It is intended for uses where you know there is no contextual type,
61570          * and requesting the contextual type might cause a circularity or other bad behaviour.
61571          * It sets the contextual type of the node to any before calling getTypeOfExpression.
61572          */
61573         function getContextFreeTypeOfExpression(node) {
61574             var links = getNodeLinks(node);
61575             if (links.contextFreeType) {
61576                 return links.contextFreeType;
61577             }
61578             var saveContextualType = node.contextualType;
61579             node.contextualType = anyType;
61580             try {
61581                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
61582                 return type;
61583             }
61584             finally {
61585                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61586                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61587                 // may hold onto the checker that created it.
61588                 node.contextualType = saveContextualType;
61589             }
61590         }
61591         function checkExpression(node, checkMode, forceTuple) {
61592             var saveCurrentNode = currentNode;
61593             currentNode = node;
61594             instantiationCount = 0;
61595             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
61596             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61597             if (isConstEnumObjectType(type)) {
61598                 checkConstEnumAccess(node, type);
61599             }
61600             currentNode = saveCurrentNode;
61601             return type;
61602         }
61603         function checkConstEnumAccess(node, type) {
61604             // enum object type for const enums are only permitted in:
61605             // - 'left' in property access
61606             // - 'object' in indexed access
61607             // - target in rhs of import statement
61608             var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
61609                 (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
61610                 ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
61611                     (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
61612                 (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
61613             if (!ok) {
61614                 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);
61615             }
61616             if (compilerOptions.isolatedModules) {
61617                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
61618                 var constEnumDeclaration = type.symbol.valueDeclaration;
61619                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
61620                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
61621                 }
61622             }
61623         }
61624         function checkParenthesizedExpression(node, checkMode) {
61625             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
61626             if (tag) {
61627                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
61628             }
61629             return checkExpression(node.expression, checkMode);
61630         }
61631         function checkExpressionWorker(node, checkMode, forceTuple) {
61632             var kind = node.kind;
61633             if (cancellationToken) {
61634                 // Only bother checking on a few construct kinds.  We don't want to be excessively
61635                 // hitting the cancellation token on every node we check.
61636                 switch (kind) {
61637                     case 214 /* ClassExpression */:
61638                     case 201 /* FunctionExpression */:
61639                     case 202 /* ArrowFunction */:
61640                         cancellationToken.throwIfCancellationRequested();
61641                 }
61642             }
61643             switch (kind) {
61644                 case 75 /* Identifier */:
61645                     return checkIdentifier(node);
61646                 case 104 /* ThisKeyword */:
61647                     return checkThisExpression(node);
61648                 case 102 /* SuperKeyword */:
61649                     return checkSuperExpression(node);
61650                 case 100 /* NullKeyword */:
61651                     return nullWideningType;
61652                 case 14 /* NoSubstitutionTemplateLiteral */:
61653                 case 10 /* StringLiteral */:
61654                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
61655                 case 8 /* NumericLiteral */:
61656                     checkGrammarNumericLiteral(node);
61657                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
61658                 case 9 /* BigIntLiteral */:
61659                     checkGrammarBigIntLiteral(node);
61660                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
61661                 case 106 /* TrueKeyword */:
61662                     return trueType;
61663                 case 91 /* FalseKeyword */:
61664                     return falseType;
61665                 case 211 /* TemplateExpression */:
61666                     return checkTemplateExpression(node);
61667                 case 13 /* RegularExpressionLiteral */:
61668                     return globalRegExpType;
61669                 case 192 /* ArrayLiteralExpression */:
61670                     return checkArrayLiteral(node, checkMode, forceTuple);
61671                 case 193 /* ObjectLiteralExpression */:
61672                     return checkObjectLiteral(node, checkMode);
61673                 case 194 /* PropertyAccessExpression */:
61674                     return checkPropertyAccessExpression(node);
61675                 case 153 /* QualifiedName */:
61676                     return checkQualifiedName(node);
61677                 case 195 /* ElementAccessExpression */:
61678                     return checkIndexedAccess(node);
61679                 case 196 /* CallExpression */:
61680                     if (node.expression.kind === 96 /* ImportKeyword */) {
61681                         return checkImportCallExpression(node);
61682                     }
61683                 // falls through
61684                 case 197 /* NewExpression */:
61685                     return checkCallExpression(node, checkMode);
61686                 case 198 /* TaggedTemplateExpression */:
61687                     return checkTaggedTemplateExpression(node);
61688                 case 200 /* ParenthesizedExpression */:
61689                     return checkParenthesizedExpression(node, checkMode);
61690                 case 214 /* ClassExpression */:
61691                     return checkClassExpression(node);
61692                 case 201 /* FunctionExpression */:
61693                 case 202 /* ArrowFunction */:
61694                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61695                 case 204 /* TypeOfExpression */:
61696                     return checkTypeOfExpression(node);
61697                 case 199 /* TypeAssertionExpression */:
61698                 case 217 /* AsExpression */:
61699                     return checkAssertion(node);
61700                 case 218 /* NonNullExpression */:
61701                     return checkNonNullAssertion(node);
61702                 case 219 /* MetaProperty */:
61703                     return checkMetaProperty(node);
61704                 case 203 /* DeleteExpression */:
61705                     return checkDeleteExpression(node);
61706                 case 205 /* VoidExpression */:
61707                     return checkVoidExpression(node);
61708                 case 206 /* AwaitExpression */:
61709                     return checkAwaitExpression(node);
61710                 case 207 /* PrefixUnaryExpression */:
61711                     return checkPrefixUnaryExpression(node);
61712                 case 208 /* PostfixUnaryExpression */:
61713                     return checkPostfixUnaryExpression(node);
61714                 case 209 /* BinaryExpression */:
61715                     return checkBinaryExpression(node, checkMode);
61716                 case 210 /* ConditionalExpression */:
61717                     return checkConditionalExpression(node, checkMode);
61718                 case 213 /* SpreadElement */:
61719                     return checkSpreadExpression(node, checkMode);
61720                 case 215 /* OmittedExpression */:
61721                     return undefinedWideningType;
61722                 case 212 /* YieldExpression */:
61723                     return checkYieldExpression(node);
61724                 case 220 /* SyntheticExpression */:
61725                     return node.type;
61726                 case 276 /* JsxExpression */:
61727                     return checkJsxExpression(node, checkMode);
61728                 case 266 /* JsxElement */:
61729                     return checkJsxElement(node, checkMode);
61730                 case 267 /* JsxSelfClosingElement */:
61731                     return checkJsxSelfClosingElement(node, checkMode);
61732                 case 270 /* JsxFragment */:
61733                     return checkJsxFragment(node);
61734                 case 274 /* JsxAttributes */:
61735                     return checkJsxAttributes(node, checkMode);
61736                 case 268 /* JsxOpeningElement */:
61737                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
61738             }
61739             return errorType;
61740         }
61741         // DECLARATION AND STATEMENT TYPE CHECKING
61742         function checkTypeParameter(node) {
61743             // Grammar Checking
61744             if (node.expression) {
61745                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
61746             }
61747             checkSourceElement(node.constraint);
61748             checkSourceElement(node.default);
61749             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
61750             // Resolve base constraint to reveal circularity errors
61751             getBaseConstraintOfType(typeParameter);
61752             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
61753                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
61754             }
61755             var constraintType = getConstraintOfTypeParameter(typeParameter);
61756             var defaultType = getDefaultFromTypeParameter(typeParameter);
61757             if (constraintType && defaultType) {
61758                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
61759             }
61760             if (produceDiagnostics) {
61761                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
61762             }
61763         }
61764         function checkParameter(node) {
61765             // Grammar checking
61766             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
61767             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
61768             // or if its FunctionBody is strict code(11.1.5).
61769             checkGrammarDecoratorsAndModifiers(node);
61770             checkVariableLikeDeclaration(node);
61771             var func = ts.getContainingFunction(node);
61772             if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
61773                 if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
61774                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
61775                 }
61776                 if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
61777                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
61778                 }
61779             }
61780             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
61781                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
61782             }
61783             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
61784                 if (func.parameters.indexOf(node) !== 0) {
61785                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
61786                 }
61787                 if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
61788                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
61789                 }
61790                 if (func.kind === 202 /* ArrowFunction */) {
61791                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
61792                 }
61793                 if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) {
61794                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
61795                 }
61796             }
61797             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
61798             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
61799             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
61800                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
61801             }
61802         }
61803         function checkTypePredicate(node) {
61804             var parent = getTypePredicateParent(node);
61805             if (!parent) {
61806                 // The parent must not be valid.
61807                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
61808                 return;
61809             }
61810             var signature = getSignatureFromDeclaration(parent);
61811             var typePredicate = getTypePredicateOfSignature(signature);
61812             if (!typePredicate) {
61813                 return;
61814             }
61815             checkSourceElement(node.type);
61816             var parameterName = node.parameterName;
61817             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
61818                 getTypeFromThisTypeNode(parameterName);
61819             }
61820             else {
61821                 if (typePredicate.parameterIndex >= 0) {
61822                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
61823                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
61824                     }
61825                     else {
61826                         if (typePredicate.type) {
61827                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
61828                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
61829                             /*headMessage*/ undefined, leadingError);
61830                         }
61831                     }
61832                 }
61833                 else if (parameterName) {
61834                     var hasReportedError = false;
61835                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
61836                         var name = _a[_i].name;
61837                         if (ts.isBindingPattern(name) &&
61838                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
61839                             hasReportedError = true;
61840                             break;
61841                         }
61842                     }
61843                     if (!hasReportedError) {
61844                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
61845                     }
61846                 }
61847             }
61848         }
61849         function getTypePredicateParent(node) {
61850             switch (node.parent.kind) {
61851                 case 202 /* ArrowFunction */:
61852                 case 165 /* CallSignature */:
61853                 case 244 /* FunctionDeclaration */:
61854                 case 201 /* FunctionExpression */:
61855                 case 170 /* FunctionType */:
61856                 case 161 /* MethodDeclaration */:
61857                 case 160 /* MethodSignature */:
61858                     var parent = node.parent;
61859                     if (node === parent.type) {
61860                         return parent;
61861                     }
61862             }
61863         }
61864         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
61865             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
61866                 var element = _a[_i];
61867                 if (ts.isOmittedExpression(element)) {
61868                     continue;
61869                 }
61870                 var name = element.name;
61871                 if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
61872                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
61873                     return true;
61874                 }
61875                 else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
61876                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
61877                         return true;
61878                     }
61879                 }
61880             }
61881         }
61882         function checkSignatureDeclaration(node) {
61883             // Grammar checking
61884             if (node.kind === 167 /* IndexSignature */) {
61885                 checkGrammarIndexSignature(node);
61886             }
61887             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
61888             else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
61889                 node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
61890                 node.kind === 166 /* ConstructSignature */) {
61891                 checkGrammarFunctionLikeDeclaration(node);
61892             }
61893             var functionFlags = ts.getFunctionFlags(node);
61894             if (!(functionFlags & 4 /* Invalid */)) {
61895                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
61896                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
61897                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
61898                 }
61899                 // Async functions prior to ES2017 require the __awaiter helper
61900                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
61901                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
61902                 }
61903                 // Generator functions, Async functions, and Async Generator functions prior to
61904                 // ES2015 require the __generator helper
61905                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
61906                     checkExternalEmitHelpers(node, 128 /* Generator */);
61907                 }
61908             }
61909             checkTypeParameters(node.typeParameters);
61910             ts.forEach(node.parameters, checkParameter);
61911             // TODO(rbuckton): Should we start checking JSDoc types?
61912             if (node.type) {
61913                 checkSourceElement(node.type);
61914             }
61915             if (produceDiagnostics) {
61916                 checkCollisionWithArgumentsInGeneratedCode(node);
61917                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
61918                 if (noImplicitAny && !returnTypeNode) {
61919                     switch (node.kind) {
61920                         case 166 /* ConstructSignature */:
61921                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61922                             break;
61923                         case 165 /* CallSignature */:
61924                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61925                             break;
61926                     }
61927                 }
61928                 if (returnTypeNode) {
61929                     var functionFlags_1 = ts.getFunctionFlags(node);
61930                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
61931                         var returnType = getTypeFromTypeNode(returnTypeNode);
61932                         if (returnType === voidType) {
61933                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
61934                         }
61935                         else {
61936                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
61937                             // However, that would not catch the error in the following case.
61938                             //
61939                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
61940                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
61941                             //
61942                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
61943                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
61944                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
61945                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
61946                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
61947                         }
61948                     }
61949                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
61950                         checkAsyncFunctionReturnType(node, returnTypeNode);
61951                     }
61952                 }
61953                 if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
61954                     registerForUnusedIdentifiersCheck(node);
61955                 }
61956             }
61957         }
61958         function checkClassForDuplicateDeclarations(node) {
61959             var instanceNames = ts.createUnderscoreEscapedMap();
61960             var staticNames = ts.createUnderscoreEscapedMap();
61961             // instance and static private identifiers share the same scope
61962             var privateIdentifiers = ts.createUnderscoreEscapedMap();
61963             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61964                 var member = _a[_i];
61965                 if (member.kind === 162 /* Constructor */) {
61966                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
61967                         var param = _c[_b];
61968                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
61969                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
61970                         }
61971                     }
61972                 }
61973                 else {
61974                     var isStatic = ts.hasModifier(member, 32 /* Static */);
61975                     var name = member.name;
61976                     if (!name) {
61977                         return;
61978                     }
61979                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
61980                         isStatic ? staticNames :
61981                             instanceNames;
61982                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
61983                     if (memberName) {
61984                         switch (member.kind) {
61985                             case 163 /* GetAccessor */:
61986                                 addName(names, name, memberName, 1 /* GetAccessor */);
61987                                 break;
61988                             case 164 /* SetAccessor */:
61989                                 addName(names, name, memberName, 2 /* SetAccessor */);
61990                                 break;
61991                             case 159 /* PropertyDeclaration */:
61992                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
61993                                 break;
61994                             case 161 /* MethodDeclaration */:
61995                                 addName(names, name, memberName, 8 /* Method */);
61996                                 break;
61997                         }
61998                     }
61999                 }
62000             }
62001             function addName(names, location, name, meaning) {
62002                 var prev = names.get(name);
62003                 if (prev) {
62004                     if (prev & 8 /* Method */) {
62005                         if (meaning !== 8 /* Method */) {
62006                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
62007                         }
62008                     }
62009                     else if (prev & meaning) {
62010                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
62011                     }
62012                     else {
62013                         names.set(name, prev | meaning);
62014                     }
62015                 }
62016                 else {
62017                     names.set(name, meaning);
62018                 }
62019             }
62020         }
62021         /**
62022          * Static members being set on a constructor function may conflict with built-in properties
62023          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
62024          * built-in properties. This check issues a transpile error when a class has a static
62025          * member with the same name as a non-writable built-in property.
62026          *
62027          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
62028          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
62029          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
62030          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
62031          */
62032         function checkClassForStaticPropertyNameConflicts(node) {
62033             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
62034                 var member = _a[_i];
62035                 var memberNameNode = member.name;
62036                 var isStatic = ts.hasModifier(member, 32 /* Static */);
62037                 if (isStatic && memberNameNode) {
62038                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
62039                     switch (memberName) {
62040                         case "name":
62041                         case "length":
62042                         case "caller":
62043                         case "arguments":
62044                         case "prototype":
62045                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
62046                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
62047                             error(memberNameNode, message, memberName, className);
62048                             break;
62049                     }
62050                 }
62051             }
62052         }
62053         function checkObjectTypeForDuplicateDeclarations(node) {
62054             var names = ts.createMap();
62055             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
62056                 var member = _a[_i];
62057                 if (member.kind === 158 /* PropertySignature */) {
62058                     var memberName = void 0;
62059                     var name = member.name;
62060                     switch (name.kind) {
62061                         case 10 /* StringLiteral */:
62062                         case 8 /* NumericLiteral */:
62063                             memberName = name.text;
62064                             break;
62065                         case 75 /* Identifier */:
62066                             memberName = ts.idText(name);
62067                             break;
62068                         default:
62069                             continue;
62070                     }
62071                     if (names.get(memberName)) {
62072                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
62073                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
62074                     }
62075                     else {
62076                         names.set(memberName, true);
62077                     }
62078                 }
62079             }
62080         }
62081         function checkTypeForDuplicateIndexSignatures(node) {
62082             if (node.kind === 246 /* InterfaceDeclaration */) {
62083                 var nodeSymbol = getSymbolOfNode(node);
62084                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
62085                 // to prevent this run check only for the first declaration of a given kind
62086                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
62087                     return;
62088                 }
62089             }
62090             // TypeScript 1.0 spec (April 2014)
62091             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
62092             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
62093             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
62094             if (indexSymbol) {
62095                 var seenNumericIndexer = false;
62096                 var seenStringIndexer = false;
62097                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
62098                     var decl = _a[_i];
62099                     var declaration = decl;
62100                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
62101                         switch (declaration.parameters[0].type.kind) {
62102                             case 143 /* StringKeyword */:
62103                                 if (!seenStringIndexer) {
62104                                     seenStringIndexer = true;
62105                                 }
62106                                 else {
62107                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
62108                                 }
62109                                 break;
62110                             case 140 /* NumberKeyword */:
62111                                 if (!seenNumericIndexer) {
62112                                     seenNumericIndexer = true;
62113                                 }
62114                                 else {
62115                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
62116                                 }
62117                                 break;
62118                         }
62119                     }
62120                 }
62121             }
62122         }
62123         function checkPropertyDeclaration(node) {
62124             // Grammar checking
62125             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
62126                 checkGrammarComputedPropertyName(node.name);
62127             checkVariableLikeDeclaration(node);
62128             // Private class fields transformation relies on WeakMaps.
62129             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
62130                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
62131                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
62132                 }
62133             }
62134         }
62135         function checkPropertySignature(node) {
62136             if (ts.isPrivateIdentifier(node.name)) {
62137                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
62138             }
62139             return checkPropertyDeclaration(node);
62140         }
62141         function checkMethodDeclaration(node) {
62142             // Grammar checking
62143             if (!checkGrammarMethod(node))
62144                 checkGrammarComputedPropertyName(node.name);
62145             if (ts.isPrivateIdentifier(node.name)) {
62146                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
62147             }
62148             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
62149             checkFunctionOrMethodDeclaration(node);
62150             // Abstract methods cannot have an implementation.
62151             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
62152             if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
62153                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
62154             }
62155         }
62156         function checkConstructorDeclaration(node) {
62157             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
62158             checkSignatureDeclaration(node);
62159             // Grammar check for checking only related to constructorDeclaration
62160             if (!checkGrammarConstructorTypeParameters(node))
62161                 checkGrammarConstructorTypeAnnotation(node);
62162             checkSourceElement(node.body);
62163             var symbol = getSymbolOfNode(node);
62164             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
62165             // Only type check the symbol once
62166             if (node === firstDeclaration) {
62167                 checkFunctionOrConstructorSymbol(symbol);
62168             }
62169             // exit early in the case of signature - super checks are not relevant to them
62170             if (ts.nodeIsMissing(node.body)) {
62171                 return;
62172             }
62173             if (!produceDiagnostics) {
62174                 return;
62175             }
62176             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
62177                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
62178                     return true;
62179                 }
62180                 return n.kind === 159 /* PropertyDeclaration */ &&
62181                     !ts.hasModifier(n, 32 /* Static */) &&
62182                     !!n.initializer;
62183             }
62184             // TS 1.0 spec (April 2014): 8.3.2
62185             // Constructors of classes with no extends clause may not contain super calls, whereas
62186             // constructors of derived classes must contain at least one super call somewhere in their function body.
62187             var containingClassDecl = node.parent;
62188             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
62189                 captureLexicalThis(node.parent, containingClassDecl);
62190                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
62191                 var superCall = getSuperCallInConstructor(node);
62192                 if (superCall) {
62193                     if (classExtendsNull) {
62194                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
62195                     }
62196                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
62197                     // if both of the following are true:
62198                     // - The containing class is a derived class.
62199                     // - The constructor declares parameter properties
62200                     //   or the containing class declares instance member variables with initializers.
62201                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
62202                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
62203                             ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }));
62204                     // Skip past any prologue directives to find the first statement
62205                     // to ensure that it was a super call.
62206                     if (superCallShouldBeFirst) {
62207                         var statements = node.body.statements;
62208                         var superCallStatement = void 0;
62209                         for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
62210                             var statement = statements_3[_i];
62211                             if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
62212                                 superCallStatement = statement;
62213                                 break;
62214                             }
62215                             if (!ts.isPrologueDirective(statement)) {
62216                                 break;
62217                             }
62218                         }
62219                         if (!superCallStatement) {
62220                             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);
62221                         }
62222                     }
62223                 }
62224                 else if (!classExtendsNull) {
62225                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
62226                 }
62227             }
62228         }
62229         function checkAccessorDeclaration(node) {
62230             if (produceDiagnostics) {
62231                 // Grammar checking accessors
62232                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
62233                     checkGrammarComputedPropertyName(node.name);
62234                 checkDecorators(node);
62235                 checkSignatureDeclaration(node);
62236                 if (node.kind === 163 /* GetAccessor */) {
62237                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
62238                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
62239                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
62240                         }
62241                     }
62242                 }
62243                 // Do not use hasDynamicName here, because that returns false for well known symbols.
62244                 // We want to perform checkComputedPropertyName for all computed properties, including
62245                 // well known symbols.
62246                 if (node.name.kind === 154 /* ComputedPropertyName */) {
62247                     checkComputedPropertyName(node.name);
62248                 }
62249                 if (ts.isPrivateIdentifier(node.name)) {
62250                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
62251                 }
62252                 if (!hasNonBindableDynamicName(node)) {
62253                     // TypeScript 1.0 spec (April 2014): 8.4.3
62254                     // Accessors for the same member name must specify the same accessibility.
62255                     var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
62256                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
62257                     if (otherAccessor) {
62258                         var nodeFlags = ts.getModifierFlags(node);
62259                         var otherFlags = ts.getModifierFlags(otherAccessor);
62260                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
62261                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
62262                         }
62263                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
62264                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
62265                         }
62266                         // TypeScript 1.0 spec (April 2014): 4.5
62267                         // If both accessors include type annotations, the specified types must be identical.
62268                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
62269                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
62270                     }
62271                 }
62272                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
62273                 if (node.kind === 163 /* GetAccessor */) {
62274                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
62275                 }
62276             }
62277             checkSourceElement(node.body);
62278         }
62279         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
62280             var firstType = getAnnotatedType(first);
62281             var secondType = getAnnotatedType(second);
62282             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
62283                 error(first, message);
62284             }
62285         }
62286         function checkMissingDeclaration(node) {
62287             checkDecorators(node);
62288         }
62289         function getEffectiveTypeArguments(node, typeParameters) {
62290             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
62291         }
62292         function checkTypeArgumentConstraints(node, typeParameters) {
62293             var typeArguments;
62294             var mapper;
62295             var result = true;
62296             for (var i = 0; i < typeParameters.length; i++) {
62297                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
62298                 if (constraint) {
62299                     if (!typeArguments) {
62300                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
62301                         mapper = createTypeMapper(typeParameters, typeArguments);
62302                     }
62303                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
62304                 }
62305             }
62306             return result;
62307         }
62308         function getTypeParametersForTypeReference(node) {
62309             var type = getTypeFromTypeReference(node);
62310             if (type !== errorType) {
62311                 var symbol = getNodeLinks(node).resolvedSymbol;
62312                 if (symbol) {
62313                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
62314                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
62315                 }
62316             }
62317             return undefined;
62318         }
62319         function checkTypeReferenceNode(node) {
62320             checkGrammarTypeArguments(node, node.typeArguments);
62321             if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
62322                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
62323             }
62324             ts.forEach(node.typeArguments, checkSourceElement);
62325             var type = getTypeFromTypeReference(node);
62326             if (type !== errorType) {
62327                 if (node.typeArguments && produceDiagnostics) {
62328                     var typeParameters = getTypeParametersForTypeReference(node);
62329                     if (typeParameters) {
62330                         checkTypeArgumentConstraints(node, typeParameters);
62331                     }
62332                 }
62333                 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
62334                     error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
62335                 }
62336             }
62337         }
62338         function getTypeArgumentConstraint(node) {
62339             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
62340             if (!typeReferenceNode)
62341                 return undefined;
62342             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
62343             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
62344             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
62345         }
62346         function checkTypeQuery(node) {
62347             getTypeFromTypeQueryNode(node);
62348         }
62349         function checkTypeLiteral(node) {
62350             ts.forEach(node.members, checkSourceElement);
62351             if (produceDiagnostics) {
62352                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
62353                 checkIndexConstraints(type);
62354                 checkTypeForDuplicateIndexSignatures(node);
62355                 checkObjectTypeForDuplicateDeclarations(node);
62356             }
62357         }
62358         function checkArrayType(node) {
62359             checkSourceElement(node.elementType);
62360         }
62361         function checkTupleType(node) {
62362             var elementTypes = node.elementTypes;
62363             var seenOptionalElement = false;
62364             for (var i = 0; i < elementTypes.length; i++) {
62365                 var e = elementTypes[i];
62366                 if (e.kind === 177 /* RestType */) {
62367                     if (i !== elementTypes.length - 1) {
62368                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
62369                         break;
62370                     }
62371                     if (!isArrayType(getTypeFromTypeNode(e.type))) {
62372                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
62373                     }
62374                 }
62375                 else if (e.kind === 176 /* OptionalType */) {
62376                     seenOptionalElement = true;
62377                 }
62378                 else if (seenOptionalElement) {
62379                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
62380                     break;
62381                 }
62382             }
62383             ts.forEach(node.elementTypes, checkSourceElement);
62384         }
62385         function checkUnionOrIntersectionType(node) {
62386             ts.forEach(node.types, checkSourceElement);
62387         }
62388         function checkIndexedAccessIndexType(type, accessNode) {
62389             if (!(type.flags & 8388608 /* IndexedAccess */)) {
62390                 return type;
62391             }
62392             // Check if the index type is assignable to 'keyof T' for the object type.
62393             var objectType = type.objectType;
62394             var indexType = type.indexType;
62395             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
62396                 if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
62397                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
62398                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
62399                 }
62400                 return type;
62401             }
62402             // Check if we're indexing with a numeric type and if either object or index types
62403             // is a generic type with a constraint that has a numeric index signature.
62404             var apparentObjectType = getApparentType(objectType);
62405             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
62406                 return type;
62407             }
62408             if (isGenericObjectType(objectType)) {
62409                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
62410                 if (propertyName_1) {
62411                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
62412                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
62413                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
62414                         return errorType;
62415                     }
62416                 }
62417             }
62418             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
62419             return errorType;
62420         }
62421         function checkIndexedAccessType(node) {
62422             checkSourceElement(node.objectType);
62423             checkSourceElement(node.indexType);
62424             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
62425         }
62426         function checkMappedType(node) {
62427             checkSourceElement(node.typeParameter);
62428             checkSourceElement(node.type);
62429             if (!node.type) {
62430                 reportImplicitAny(node, anyType);
62431             }
62432             var type = getTypeFromMappedTypeNode(node);
62433             var constraintType = getConstraintTypeFromMappedType(type);
62434             checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
62435         }
62436         function checkThisType(node) {
62437             getTypeFromThisTypeNode(node);
62438         }
62439         function checkTypeOperator(node) {
62440             checkGrammarTypeOperatorNode(node);
62441             checkSourceElement(node.type);
62442         }
62443         function checkConditionalType(node) {
62444             ts.forEachChild(node, checkSourceElement);
62445         }
62446         function checkInferType(node) {
62447             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
62448                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
62449             }
62450             checkSourceElement(node.typeParameter);
62451             registerForUnusedIdentifiersCheck(node);
62452         }
62453         function checkImportType(node) {
62454             checkSourceElement(node.argument);
62455             getTypeFromTypeNode(node);
62456         }
62457         function isPrivateWithinAmbient(node) {
62458             return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
62459         }
62460         function getEffectiveDeclarationFlags(n, flagsToCheck) {
62461             var flags = ts.getCombinedModifierFlags(n);
62462             // children of classes (even ambient classes) should not be marked as ambient or export
62463             // because those flags have no useful semantics there.
62464             if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
62465                 n.parent.kind !== 245 /* ClassDeclaration */ &&
62466                 n.parent.kind !== 214 /* ClassExpression */ &&
62467                 n.flags & 8388608 /* Ambient */) {
62468                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
62469                     // It is nested in an ambient context, which means it is automatically exported
62470                     flags |= 1 /* Export */;
62471                 }
62472                 flags |= 2 /* Ambient */;
62473             }
62474             return flags & flagsToCheck;
62475         }
62476         function checkFunctionOrConstructorSymbol(symbol) {
62477             if (!produceDiagnostics) {
62478                 return;
62479             }
62480             function getCanonicalOverload(overloads, implementation) {
62481                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
62482                 // Error on all deviations from this canonical set of flags
62483                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
62484                 // report the errors on those. To achieve this, we will say that the implementation is
62485                 // the canonical signature only if it is in the same container as the first overload
62486                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
62487                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
62488             }
62489             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
62490                 // Error if some overloads have a flag that is not shared by all overloads. To find the
62491                 // deviations, we XOR someOverloadFlags with allOverloadFlags
62492                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
62493                 if (someButNotAllOverloadFlags !== 0) {
62494                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
62495                     ts.forEach(overloads, function (o) {
62496                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
62497                         if (deviation & 1 /* Export */) {
62498                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
62499                         }
62500                         else if (deviation & 2 /* Ambient */) {
62501                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
62502                         }
62503                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
62504                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
62505                         }
62506                         else if (deviation & 128 /* Abstract */) {
62507                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
62508                         }
62509                     });
62510                 }
62511             }
62512             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
62513                 if (someHaveQuestionToken !== allHaveQuestionToken) {
62514                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
62515                     ts.forEach(overloads, function (o) {
62516                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
62517                         if (deviation) {
62518                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
62519                         }
62520                     });
62521                 }
62522             }
62523             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
62524             var someNodeFlags = 0 /* None */;
62525             var allNodeFlags = flagsToCheck;
62526             var someHaveQuestionToken = false;
62527             var allHaveQuestionToken = true;
62528             var hasOverloads = false;
62529             var bodyDeclaration;
62530             var lastSeenNonAmbientDeclaration;
62531             var previousDeclaration;
62532             var declarations = symbol.declarations;
62533             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
62534             function reportImplementationExpectedError(node) {
62535                 if (node.name && ts.nodeIsMissing(node.name)) {
62536                     return;
62537                 }
62538                 var seen = false;
62539                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
62540                     if (seen) {
62541                         return c;
62542                     }
62543                     else {
62544                         seen = c === node;
62545                     }
62546                 });
62547                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
62548                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
62549                 if (subsequentNode && subsequentNode.pos === node.end) {
62550                     if (subsequentNode.kind === node.kind) {
62551                         var errorNode_1 = subsequentNode.name || subsequentNode;
62552                         var subsequentName = subsequentNode.name;
62553                         if (node.name && subsequentName && (
62554                         // both are private identifiers
62555                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
62556                             // Both are computed property names
62557                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
62558                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
62559                             // Both are literal property names that are the same.
62560                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
62561                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
62562                             var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
62563                                 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
62564                             // we can get here in two cases
62565                             // 1. mixed static and instance class members
62566                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
62567                             // here we'll report error only for the first case since for second we should already report error in binder
62568                             if (reportError) {
62569                                 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
62570                                 error(errorNode_1, diagnostic);
62571                             }
62572                             return;
62573                         }
62574                         if (ts.nodeIsPresent(subsequentNode.body)) {
62575                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
62576                             return;
62577                         }
62578                     }
62579                 }
62580                 var errorNode = node.name || node;
62581                 if (isConstructor) {
62582                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
62583                 }
62584                 else {
62585                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
62586                     // the node in question is abstract.
62587                     if (ts.hasModifier(node, 128 /* Abstract */)) {
62588                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
62589                     }
62590                     else {
62591                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
62592                     }
62593                 }
62594             }
62595             var duplicateFunctionDeclaration = false;
62596             var multipleConstructorImplementation = false;
62597             var hasNonAmbientClass = false;
62598             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
62599                 var current = declarations_4[_i];
62600                 var node = current;
62601                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
62602                 var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
62603                 if (inAmbientContextOrInterface) {
62604                     // check if declarations are consecutive only if they are non-ambient
62605                     // 1. ambient declarations can be interleaved
62606                     // i.e. this is legal
62607                     //     declare function foo();
62608                     //     declare function bar();
62609                     //     declare function foo();
62610                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
62611                     previousDeclaration = undefined;
62612                 }
62613                 if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
62614                     hasNonAmbientClass = true;
62615                 }
62616                 if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
62617                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
62618                     someNodeFlags |= currentNodeFlags;
62619                     allNodeFlags &= currentNodeFlags;
62620                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
62621                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
62622                     if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
62623                         if (isConstructor) {
62624                             multipleConstructorImplementation = true;
62625                         }
62626                         else {
62627                             duplicateFunctionDeclaration = true;
62628                         }
62629                     }
62630                     else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
62631                         reportImplementationExpectedError(previousDeclaration);
62632                     }
62633                     if (ts.nodeIsPresent(node.body)) {
62634                         if (!bodyDeclaration) {
62635                             bodyDeclaration = node;
62636                         }
62637                     }
62638                     else {
62639                         hasOverloads = true;
62640                     }
62641                     previousDeclaration = node;
62642                     if (!inAmbientContextOrInterface) {
62643                         lastSeenNonAmbientDeclaration = node;
62644                     }
62645                 }
62646             }
62647             if (multipleConstructorImplementation) {
62648                 ts.forEach(declarations, function (declaration) {
62649                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
62650                 });
62651             }
62652             if (duplicateFunctionDeclaration) {
62653                 ts.forEach(declarations, function (declaration) {
62654                     error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
62655                 });
62656             }
62657             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
62658                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
62659                 // TODO: The below just replicates our older error from when classes and functions were
62660                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
62661                 // might be warranted. :shrug:
62662                 ts.forEach(declarations, function (declaration) {
62663                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
62664                 });
62665             }
62666             // Abstract methods can't have an implementation -- in particular, they don't need one.
62667             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
62668                 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
62669                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
62670             }
62671             if (hasOverloads) {
62672                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
62673                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
62674                 if (bodyDeclaration) {
62675                     var signatures = getSignaturesOfSymbol(symbol);
62676                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
62677                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
62678                         var signature = signatures_10[_a];
62679                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
62680                             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));
62681                             break;
62682                         }
62683                     }
62684                 }
62685             }
62686         }
62687         function checkExportsOnMergedDeclarations(node) {
62688             if (!produceDiagnostics) {
62689                 return;
62690             }
62691             // if localSymbol is defined on node then node itself is exported - check is required
62692             var symbol = node.localSymbol;
62693             if (!symbol) {
62694                 // local symbol is undefined => this declaration is non-exported.
62695                 // however symbol might contain other declarations that are exported
62696                 symbol = getSymbolOfNode(node);
62697                 if (!symbol.exportSymbol) {
62698                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
62699                     return;
62700                 }
62701             }
62702             // run the check only for the first declaration in the list
62703             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
62704                 return;
62705             }
62706             var exportedDeclarationSpaces = 0 /* None */;
62707             var nonExportedDeclarationSpaces = 0 /* None */;
62708             var defaultExportedDeclarationSpaces = 0 /* None */;
62709             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
62710                 var d = _a[_i];
62711                 var declarationSpaces = getDeclarationSpaces(d);
62712                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
62713                 if (effectiveDeclarationFlags & 1 /* Export */) {
62714                     if (effectiveDeclarationFlags & 512 /* Default */) {
62715                         defaultExportedDeclarationSpaces |= declarationSpaces;
62716                     }
62717                     else {
62718                         exportedDeclarationSpaces |= declarationSpaces;
62719                     }
62720                 }
62721                 else {
62722                     nonExportedDeclarationSpaces |= declarationSpaces;
62723                 }
62724             }
62725             // Spaces for anything not declared a 'default export'.
62726             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
62727             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
62728             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
62729             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
62730                 // declaration spaces for exported and non-exported declarations intersect
62731                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
62732                     var d = _c[_b];
62733                     var declarationSpaces = getDeclarationSpaces(d);
62734                     var name = ts.getNameOfDeclaration(d);
62735                     // Only error on the declarations that contributed to the intersecting spaces.
62736                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
62737                         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));
62738                     }
62739                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
62740                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
62741                     }
62742                 }
62743             }
62744             function getDeclarationSpaces(decl) {
62745                 var d = decl;
62746                 switch (d.kind) {
62747                     case 246 /* InterfaceDeclaration */:
62748                     case 247 /* TypeAliasDeclaration */:
62749                     // A jsdoc typedef and callback are, by definition, type aliases.
62750                     // falls through
62751                     case 322 /* JSDocTypedefTag */:
62752                     case 315 /* JSDocCallbackTag */:
62753                     case 316 /* JSDocEnumTag */:
62754                         return 2 /* ExportType */;
62755                     case 249 /* ModuleDeclaration */:
62756                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
62757                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
62758                             : 4 /* ExportNamespace */;
62759                     case 245 /* ClassDeclaration */:
62760                     case 248 /* EnumDeclaration */:
62761                     case 284 /* EnumMember */:
62762                         return 2 /* ExportType */ | 1 /* ExportValue */;
62763                     case 290 /* SourceFile */:
62764                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
62765                     case 259 /* ExportAssignment */:
62766                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
62767                         if (!ts.isEntityNameExpression(d.expression)) {
62768                             return 1 /* ExportValue */;
62769                         }
62770                         d = d.expression;
62771                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
62772                     // falls through
62773                     case 253 /* ImportEqualsDeclaration */:
62774                     case 256 /* NamespaceImport */:
62775                     case 255 /* ImportClause */:
62776                         var result_10 = 0 /* None */;
62777                         var target = resolveAlias(getSymbolOfNode(d));
62778                         ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); });
62779                         return result_10;
62780                     case 242 /* VariableDeclaration */:
62781                     case 191 /* BindingElement */:
62782                     case 244 /* FunctionDeclaration */:
62783                     case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
62784                     case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
62785                         // Identifiers are used as declarations of assignment declarations whose parents may be
62786                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
62787                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
62788                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
62789                         // all of which are pretty much always values, or at least imply a value meaning.
62790                         // It may be apprpriate to treat these as aliases in the future.
62791                         return 1 /* ExportValue */;
62792                     default:
62793                         return ts.Debug.failBadSyntaxKind(d);
62794                 }
62795             }
62796         }
62797         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
62798             var promisedType = getPromisedTypeOfPromise(type, errorNode);
62799             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62800         }
62801         /**
62802          * Gets the "promised type" of a promise.
62803          * @param type The type of the promise.
62804          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
62805          */
62806         function getPromisedTypeOfPromise(type, errorNode) {
62807             //
62808             //  { // type
62809             //      then( // thenFunction
62810             //          onfulfilled: ( // onfulfilledParameterType
62811             //              value: T // valueParameterType
62812             //          ) => any
62813             //      ): any;
62814             //  }
62815             //
62816             if (isTypeAny(type)) {
62817                 return undefined;
62818             }
62819             var typeAsPromise = type;
62820             if (typeAsPromise.promisedTypeOfPromise) {
62821                 return typeAsPromise.promisedTypeOfPromise;
62822             }
62823             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
62824                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
62825             }
62826             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
62827             if (isTypeAny(thenFunction)) {
62828                 return undefined;
62829             }
62830             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
62831             if (thenSignatures.length === 0) {
62832                 if (errorNode) {
62833                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
62834                 }
62835                 return undefined;
62836             }
62837             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
62838             if (isTypeAny(onfulfilledParameterType)) {
62839                 return undefined;
62840             }
62841             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
62842             if (onfulfilledParameterSignatures.length === 0) {
62843                 if (errorNode) {
62844                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
62845                 }
62846                 return undefined;
62847             }
62848             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
62849         }
62850         /**
62851          * Gets the "awaited type" of a type.
62852          * @param type The type to await.
62853          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
62854          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
62855          * The runtime behavior of the `await` keyword.
62856          */
62857         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62858             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
62859             return awaitedType || errorType;
62860         }
62861         /**
62862          * Determines whether a type has a callable `then` member.
62863          */
62864         function isThenableType(type) {
62865             var thenFunction = getTypeOfPropertyOfType(type, "then");
62866             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
62867         }
62868         /**
62869          * Gets the "awaited type" of a type.
62870          *
62871          * The "awaited type" of an expression is its "promised type" if the expression is a
62872          * Promise-like type; otherwise, it is the type of the expression. If the "promised
62873          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
62874          * non-promise type is found.
62875          *
62876          * This is used to reflect the runtime behavior of the `await` keyword.
62877          */
62878         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62879             if (isTypeAny(type)) {
62880                 return type;
62881             }
62882             var typeAsAwaitable = type;
62883             if (typeAsAwaitable.awaitedTypeOfType) {
62884                 return typeAsAwaitable.awaitedTypeOfType;
62885             }
62886             // For a union, get a union of the awaited types of each constituent.
62887             //
62888             return typeAsAwaitable.awaitedTypeOfType =
62889                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
62890         }
62891         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
62892             var typeAsAwaitable = type;
62893             if (typeAsAwaitable.awaitedTypeOfType) {
62894                 return typeAsAwaitable.awaitedTypeOfType;
62895             }
62896             var promisedType = getPromisedTypeOfPromise(type);
62897             if (promisedType) {
62898                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
62899                     // Verify that we don't have a bad actor in the form of a promise whose
62900                     // promised type is the same as the promise type, or a mutually recursive
62901                     // promise. If so, we return undefined as we cannot guess the shape. If this
62902                     // were the actual case in the JavaScript, this Promise would never resolve.
62903                     //
62904                     // An example of a bad actor with a singly-recursive promise type might
62905                     // be:
62906                     //
62907                     //  interface BadPromise {
62908                     //      then(
62909                     //          onfulfilled: (value: BadPromise) => any,
62910                     //          onrejected: (error: any) => any): BadPromise;
62911                     //  }
62912                     //
62913                     // The above interface will pass the PromiseLike check, and return a
62914                     // promised type of `BadPromise`. Since this is a self reference, we
62915                     // don't want to keep recursing ad infinitum.
62916                     //
62917                     // An example of a bad actor in the form of a mutually-recursive
62918                     // promise type might be:
62919                     //
62920                     //  interface BadPromiseA {
62921                     //      then(
62922                     //          onfulfilled: (value: BadPromiseB) => any,
62923                     //          onrejected: (error: any) => any): BadPromiseB;
62924                     //  }
62925                     //
62926                     //  interface BadPromiseB {
62927                     //      then(
62928                     //          onfulfilled: (value: BadPromiseA) => any,
62929                     //          onrejected: (error: any) => any): BadPromiseA;
62930                     //  }
62931                     //
62932                     if (errorNode) {
62933                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
62934                     }
62935                     return undefined;
62936                 }
62937                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
62938                 // See the comments above for more information.
62939                 awaitedTypeStack.push(type.id);
62940                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62941                 awaitedTypeStack.pop();
62942                 if (!awaitedType) {
62943                     return undefined;
62944                 }
62945                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
62946             }
62947             // The type was not a promise, so it could not be unwrapped any further.
62948             // As long as the type does not have a callable "then" property, it is
62949             // safe to return the type; otherwise, an error is reported and we return
62950             // undefined.
62951             //
62952             // An example of a non-promise "thenable" might be:
62953             //
62954             //  await { then(): void {} }
62955             //
62956             // The "thenable" does not match the minimal definition for a promise. When
62957             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
62958             // will never settle. We treat this as an error to help flag an early indicator
62959             // of a runtime problem. If the user wants to return this value from an async
62960             // function, they would need to wrap it in some other value. If they want it to
62961             // be treated as a promise, they can cast to <any>.
62962             if (isThenableType(type)) {
62963                 if (errorNode) {
62964                     if (!diagnosticMessage)
62965                         return ts.Debug.fail();
62966                     error(errorNode, diagnosticMessage, arg0);
62967                 }
62968                 return undefined;
62969             }
62970             return typeAsAwaitable.awaitedTypeOfType = type;
62971         }
62972         /**
62973          * Checks the return type of an async function to ensure it is a compatible
62974          * Promise implementation.
62975          *
62976          * This checks that an async function has a valid Promise-compatible return type.
62977          * An async function has a valid Promise-compatible return type if the resolved value
62978          * of the return type has a construct signature that takes in an `initializer` function
62979          * that in turn supplies a `resolve` function as one of its arguments and results in an
62980          * object with a callable `then` signature.
62981          *
62982          * @param node The signature to check
62983          */
62984         function checkAsyncFunctionReturnType(node, returnTypeNode) {
62985             // As part of our emit for an async function, we will need to emit the entity name of
62986             // the return type annotation as an expression. To meet the necessary runtime semantics
62987             // for __awaiter, we must also check that the type of the declaration (e.g. the static
62988             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
62989             //
62990             // An example might be (from lib.es6.d.ts):
62991             //
62992             //  interface Promise<T> { ... }
62993             //  interface PromiseConstructor {
62994             //      new <T>(...): Promise<T>;
62995             //  }
62996             //  declare var Promise: PromiseConstructor;
62997             //
62998             // When an async function declares a return type annotation of `Promise<T>`, we
62999             // need to get the type of the `Promise` variable declaration above, which would
63000             // be `PromiseConstructor`.
63001             //
63002             // The same case applies to a class:
63003             //
63004             //  declare class Promise<T> {
63005             //      constructor(...);
63006             //      then<U>(...): Promise<U>;
63007             //  }
63008             //
63009             var returnType = getTypeFromTypeNode(returnTypeNode);
63010             if (languageVersion >= 2 /* ES2015 */) {
63011                 if (returnType === errorType) {
63012                     return;
63013                 }
63014                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
63015                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
63016                     // The promise type was not a valid type reference to the global promise type, so we
63017                     // report an error and return the unknown type.
63018                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
63019                     return;
63020                 }
63021             }
63022             else {
63023                 // Always mark the type node as referenced if it points to a value
63024                 markTypeNodeAsReferenced(returnTypeNode);
63025                 if (returnType === errorType) {
63026                     return;
63027                 }
63028                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
63029                 if (promiseConstructorName === undefined) {
63030                     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));
63031                     return;
63032                 }
63033                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
63034                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
63035                 if (promiseConstructorType === errorType) {
63036                     if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
63037                         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);
63038                     }
63039                     else {
63040                         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));
63041                     }
63042                     return;
63043                 }
63044                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
63045                 if (globalPromiseConstructorLikeType === emptyObjectType) {
63046                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
63047                     // compatibility with __awaiter.
63048                     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));
63049                     return;
63050                 }
63051                 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)) {
63052                     return;
63053                 }
63054                 // Verify there is no local declaration that could collide with the promise constructor.
63055                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
63056                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
63057                 if (collidingSymbol) {
63058                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
63059                     return;
63060                 }
63061             }
63062             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);
63063         }
63064         /** Check a decorator */
63065         function checkDecorator(node) {
63066             var signature = getResolvedSignature(node);
63067             var returnType = getReturnTypeOfSignature(signature);
63068             if (returnType.flags & 1 /* Any */) {
63069                 return;
63070             }
63071             var expectedReturnType;
63072             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
63073             var errorInfo;
63074             switch (node.parent.kind) {
63075                 case 245 /* ClassDeclaration */:
63076                     var classSymbol = getSymbolOfNode(node.parent);
63077                     var classConstructorType = getTypeOfSymbol(classSymbol);
63078                     expectedReturnType = getUnionType([classConstructorType, voidType]);
63079                     break;
63080                 case 156 /* Parameter */:
63081                     expectedReturnType = voidType;
63082                     errorInfo = ts.chainDiagnosticMessages(
63083                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
63084                     break;
63085                 case 159 /* PropertyDeclaration */:
63086                     expectedReturnType = voidType;
63087                     errorInfo = ts.chainDiagnosticMessages(
63088                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
63089                     break;
63090                 case 161 /* MethodDeclaration */:
63091                 case 163 /* GetAccessor */:
63092                 case 164 /* SetAccessor */:
63093                     var methodType = getTypeOfNode(node.parent);
63094                     var descriptorType = createTypedPropertyDescriptorType(methodType);
63095                     expectedReturnType = getUnionType([descriptorType, voidType]);
63096                     break;
63097                 default:
63098                     return ts.Debug.fail();
63099             }
63100             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
63101         }
63102         /**
63103          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
63104          * marked as referenced to prevent import elision.
63105          */
63106         function markTypeNodeAsReferenced(node) {
63107             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
63108         }
63109         function markEntityNameOrEntityExpressionAsReference(typeName) {
63110             if (!typeName)
63111                 return;
63112             var rootName = ts.getFirstIdentifier(typeName);
63113             var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
63114             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
63115             if (rootSymbol
63116                 && rootSymbol.flags & 2097152 /* Alias */
63117                 && symbolIsValue(rootSymbol)
63118                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
63119                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
63120                 markAliasSymbolAsReferenced(rootSymbol);
63121             }
63122         }
63123         /**
63124          * This function marks the type used for metadata decorator as referenced if it is import
63125          * from external module.
63126          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
63127          * union and intersection type
63128          * @param node
63129          */
63130         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
63131             var entityName = getEntityNameForDecoratorMetadata(node);
63132             if (entityName && ts.isEntityName(entityName)) {
63133                 markEntityNameOrEntityExpressionAsReference(entityName);
63134             }
63135         }
63136         function getEntityNameForDecoratorMetadata(node) {
63137             if (node) {
63138                 switch (node.kind) {
63139                     case 179 /* IntersectionType */:
63140                     case 178 /* UnionType */:
63141                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
63142                     case 180 /* ConditionalType */:
63143                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
63144                     case 182 /* ParenthesizedType */:
63145                         return getEntityNameForDecoratorMetadata(node.type);
63146                     case 169 /* TypeReference */:
63147                         return node.typeName;
63148                 }
63149             }
63150         }
63151         function getEntityNameForDecoratorMetadataFromTypeList(types) {
63152             var commonEntityName;
63153             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
63154                 var typeNode = types_20[_i];
63155                 while (typeNode.kind === 182 /* ParenthesizedType */) {
63156                     typeNode = typeNode.type; // Skip parens if need be
63157                 }
63158                 if (typeNode.kind === 137 /* NeverKeyword */) {
63159                     continue; // Always elide `never` from the union/intersection if possible
63160                 }
63161                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
63162                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
63163                 }
63164                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
63165                 if (!individualEntityName) {
63166                     // Individual is something like string number
63167                     // So it would be serialized to either that type or object
63168                     // Safe to return here
63169                     return undefined;
63170                 }
63171                 if (commonEntityName) {
63172                     // Note this is in sync with the transformation that happens for type node.
63173                     // Keep this in sync with serializeUnionOrIntersectionType
63174                     // Verify if they refer to same entity and is identifier
63175                     // return undefined if they dont match because we would emit object
63176                     if (!ts.isIdentifier(commonEntityName) ||
63177                         !ts.isIdentifier(individualEntityName) ||
63178                         commonEntityName.escapedText !== individualEntityName.escapedText) {
63179                         return undefined;
63180                     }
63181                 }
63182                 else {
63183                     commonEntityName = individualEntityName;
63184                 }
63185             }
63186             return commonEntityName;
63187         }
63188         function getParameterTypeNodeForDecoratorCheck(node) {
63189             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
63190             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
63191         }
63192         /** Check the decorators of a node */
63193         function checkDecorators(node) {
63194             if (!node.decorators) {
63195                 return;
63196             }
63197             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
63198             // checkGrammarDecorators.
63199             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
63200                 return;
63201             }
63202             if (!compilerOptions.experimentalDecorators) {
63203                 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);
63204             }
63205             var firstDecorator = node.decorators[0];
63206             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
63207             if (node.kind === 156 /* Parameter */) {
63208                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
63209             }
63210             if (compilerOptions.emitDecoratorMetadata) {
63211                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
63212                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
63213                 switch (node.kind) {
63214                     case 245 /* ClassDeclaration */:
63215                         var constructor = ts.getFirstConstructorWithBody(node);
63216                         if (constructor) {
63217                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
63218                                 var parameter = _a[_i];
63219                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63220                             }
63221                         }
63222                         break;
63223                     case 163 /* GetAccessor */:
63224                     case 164 /* SetAccessor */:
63225                         var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
63226                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
63227                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
63228                         break;
63229                     case 161 /* MethodDeclaration */:
63230                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
63231                             var parameter = _c[_b];
63232                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63233                         }
63234                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
63235                         break;
63236                     case 159 /* PropertyDeclaration */:
63237                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
63238                         break;
63239                     case 156 /* Parameter */:
63240                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
63241                         var containingSignature = node.parent;
63242                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
63243                             var parameter = _e[_d];
63244                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63245                         }
63246                         break;
63247                 }
63248             }
63249             ts.forEach(node.decorators, checkDecorator);
63250         }
63251         function checkFunctionDeclaration(node) {
63252             if (produceDiagnostics) {
63253                 checkFunctionOrMethodDeclaration(node);
63254                 checkGrammarForGenerator(node);
63255                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63256                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63257             }
63258         }
63259         function checkJSDocTypeAliasTag(node) {
63260             if (!node.typeExpression) {
63261                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
63262                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
63263             }
63264             if (node.name) {
63265                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
63266             }
63267             checkSourceElement(node.typeExpression);
63268         }
63269         function checkJSDocTemplateTag(node) {
63270             checkSourceElement(node.constraint);
63271             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
63272                 var tp = _a[_i];
63273                 checkSourceElement(tp);
63274             }
63275         }
63276         function checkJSDocTypeTag(node) {
63277             checkSourceElement(node.typeExpression);
63278         }
63279         function checkJSDocParameterTag(node) {
63280             checkSourceElement(node.typeExpression);
63281             if (!ts.getParameterSymbolFromJSDoc(node)) {
63282                 var decl = ts.getHostSignatureFromJSDoc(node);
63283                 // don't issue an error for invalid hosts -- just functions --
63284                 // and give a better error message when the host function mentions `arguments`
63285                 // but the tag doesn't have an array type
63286                 if (decl) {
63287                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
63288                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
63289                         return;
63290                     }
63291                     if (!containsArgumentsReference(decl)) {
63292                         if (ts.isQualifiedName(node.name)) {
63293                             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));
63294                         }
63295                         else {
63296                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
63297                         }
63298                     }
63299                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
63300                         node.typeExpression && node.typeExpression.type &&
63301                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
63302                         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));
63303                     }
63304                 }
63305             }
63306         }
63307         function checkJSDocPropertyTag(node) {
63308             checkSourceElement(node.typeExpression);
63309         }
63310         function checkJSDocFunctionType(node) {
63311             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
63312                 reportImplicitAny(node, anyType);
63313             }
63314             checkSignatureDeclaration(node);
63315         }
63316         function checkJSDocImplementsTag(node) {
63317             var classLike = ts.getEffectiveJSDocHost(node);
63318             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63319                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63320             }
63321         }
63322         function checkJSDocAugmentsTag(node) {
63323             var classLike = ts.getEffectiveJSDocHost(node);
63324             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63325                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63326                 return;
63327             }
63328             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
63329             ts.Debug.assert(augmentsTags.length > 0);
63330             if (augmentsTags.length > 1) {
63331                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
63332             }
63333             var name = getIdentifierFromEntityNameExpression(node.class.expression);
63334             var extend = ts.getClassExtendsHeritageElement(classLike);
63335             if (extend) {
63336                 var className = getIdentifierFromEntityNameExpression(extend.expression);
63337                 if (className && name.escapedText !== className.escapedText) {
63338                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
63339                 }
63340             }
63341         }
63342         function getIdentifierFromEntityNameExpression(node) {
63343             switch (node.kind) {
63344                 case 75 /* Identifier */:
63345                     return node;
63346                 case 194 /* PropertyAccessExpression */:
63347                     return node.name;
63348                 default:
63349                     return undefined;
63350             }
63351         }
63352         function checkFunctionOrMethodDeclaration(node) {
63353             checkDecorators(node);
63354             checkSignatureDeclaration(node);
63355             var functionFlags = ts.getFunctionFlags(node);
63356             // Do not use hasDynamicName here, because that returns false for well known symbols.
63357             // We want to perform checkComputedPropertyName for all computed properties, including
63358             // well known symbols.
63359             if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
63360                 // This check will account for methods in class/interface declarations,
63361                 // as well as accessors in classes/object literals
63362                 checkComputedPropertyName(node.name);
63363             }
63364             if (!hasNonBindableDynamicName(node)) {
63365                 // first we want to check the local symbol that contain this declaration
63366                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
63367                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
63368                 var symbol = getSymbolOfNode(node);
63369                 var localSymbol = node.localSymbol || symbol;
63370                 // Since the javascript won't do semantic analysis like typescript,
63371                 // if the javascript file comes before the typescript file and both contain same name functions,
63372                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
63373                 var firstDeclaration = ts.find(localSymbol.declarations, 
63374                 // Get first non javascript function declaration
63375                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
63376                 // Only type check the symbol once
63377                 if (node === firstDeclaration) {
63378                     checkFunctionOrConstructorSymbol(localSymbol);
63379                 }
63380                 if (symbol.parent) {
63381                     // run check once for the first declaration
63382                     if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
63383                         // run check on export symbol to check that modifiers agree across all exported declarations
63384                         checkFunctionOrConstructorSymbol(symbol);
63385                     }
63386                 }
63387             }
63388             var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
63389             checkSourceElement(body);
63390             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
63391             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
63392                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
63393                 // in an ambient context
63394                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
63395                     reportImplicitAny(node, anyType);
63396                 }
63397                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
63398                     // A generator with a body and no type annotation can still cause errors. It can error if the
63399                     // yielded values have no common supertype, or it can give an implicit any error if it has no
63400                     // yielded values. The only way to trigger these errors is to try checking its return type.
63401                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
63402                 }
63403             }
63404             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
63405             if (ts.isInJSFile(node)) {
63406                 var typeTag = ts.getJSDocTypeTag(node);
63407                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
63408                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
63409                 }
63410             }
63411         }
63412         function registerForUnusedIdentifiersCheck(node) {
63413             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
63414             if (produceDiagnostics) {
63415                 var sourceFile = ts.getSourceFileOfNode(node);
63416                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
63417                 if (!potentiallyUnusedIdentifiers) {
63418                     potentiallyUnusedIdentifiers = [];
63419                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
63420                 }
63421                 // TODO: GH#22580
63422                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
63423                 potentiallyUnusedIdentifiers.push(node);
63424             }
63425         }
63426         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
63427             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
63428                 var node = potentiallyUnusedIdentifiers_1[_i];
63429                 switch (node.kind) {
63430                     case 245 /* ClassDeclaration */:
63431                     case 214 /* ClassExpression */:
63432                         checkUnusedClassMembers(node, addDiagnostic);
63433                         checkUnusedTypeParameters(node, addDiagnostic);
63434                         break;
63435                     case 290 /* SourceFile */:
63436                     case 249 /* ModuleDeclaration */:
63437                     case 223 /* Block */:
63438                     case 251 /* CaseBlock */:
63439                     case 230 /* ForStatement */:
63440                     case 231 /* ForInStatement */:
63441                     case 232 /* ForOfStatement */:
63442                         checkUnusedLocalsAndParameters(node, addDiagnostic);
63443                         break;
63444                     case 162 /* Constructor */:
63445                     case 201 /* FunctionExpression */:
63446                     case 244 /* FunctionDeclaration */:
63447                     case 202 /* ArrowFunction */:
63448                     case 161 /* MethodDeclaration */:
63449                     case 163 /* GetAccessor */:
63450                     case 164 /* SetAccessor */:
63451                         if (node.body) { // Don't report unused parameters in overloads
63452                             checkUnusedLocalsAndParameters(node, addDiagnostic);
63453                         }
63454                         checkUnusedTypeParameters(node, addDiagnostic);
63455                         break;
63456                     case 160 /* MethodSignature */:
63457                     case 165 /* CallSignature */:
63458                     case 166 /* ConstructSignature */:
63459                     case 170 /* FunctionType */:
63460                     case 171 /* ConstructorType */:
63461                     case 247 /* TypeAliasDeclaration */:
63462                     case 246 /* InterfaceDeclaration */:
63463                         checkUnusedTypeParameters(node, addDiagnostic);
63464                         break;
63465                     case 181 /* InferType */:
63466                         checkUnusedInferTypeParameter(node, addDiagnostic);
63467                         break;
63468                     default:
63469                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
63470                 }
63471             }
63472         }
63473         function errorUnusedLocal(declaration, name, addDiagnostic) {
63474             var node = ts.getNameOfDeclaration(declaration) || declaration;
63475             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
63476             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
63477         }
63478         function isIdentifierThatStartsWithUnderscore(node) {
63479             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
63480         }
63481         function checkUnusedClassMembers(node, addDiagnostic) {
63482             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
63483                 var member = _a[_i];
63484                 switch (member.kind) {
63485                     case 161 /* MethodDeclaration */:
63486                     case 159 /* PropertyDeclaration */:
63487                     case 163 /* GetAccessor */:
63488                     case 164 /* SetAccessor */:
63489                         if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
63490                             // Already would have reported an error on the getter.
63491                             break;
63492                         }
63493                         var symbol = getSymbolOfNode(member);
63494                         if (!symbol.isReferenced
63495                             && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
63496                             && !(member.flags & 8388608 /* Ambient */)) {
63497                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
63498                         }
63499                         break;
63500                     case 162 /* Constructor */:
63501                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
63502                             var parameter = _c[_b];
63503                             if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
63504                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
63505                             }
63506                         }
63507                         break;
63508                     case 167 /* IndexSignature */:
63509                     case 222 /* SemicolonClassElement */:
63510                         // Can't be private
63511                         break;
63512                     default:
63513                         ts.Debug.fail();
63514                 }
63515             }
63516         }
63517         function checkUnusedInferTypeParameter(node, addDiagnostic) {
63518             var typeParameter = node.typeParameter;
63519             if (isTypeParameterUnused(typeParameter)) {
63520                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
63521             }
63522         }
63523         function checkUnusedTypeParameters(node, addDiagnostic) {
63524             // Only report errors on the last declaration for the type parameter container;
63525             // this ensures that all uses have been accounted for.
63526             if (ts.last(getSymbolOfNode(node).declarations) !== node)
63527                 return;
63528             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
63529             var seenParentsWithEveryUnused = new ts.NodeSet();
63530             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
63531                 var typeParameter = typeParameters_3[_i];
63532                 if (!isTypeParameterUnused(typeParameter))
63533                     continue;
63534                 var name = ts.idText(typeParameter.name);
63535                 var parent = typeParameter.parent;
63536                 if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
63537                     if (seenParentsWithEveryUnused.tryAdd(parent)) {
63538                         var range = ts.isJSDocTemplateTag(parent)
63539                             // Whole @template tag
63540                             ? ts.rangeOfNode(parent)
63541                             // Include the `<>` in the error message
63542                             : ts.rangeOfTypeParameters(parent.typeParameters);
63543                         var only = parent.typeParameters.length === 1;
63544                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
63545                         var arg0 = only ? name : undefined;
63546                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
63547                     }
63548                 }
63549                 else {
63550                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
63551                 }
63552             }
63553         }
63554         function isTypeParameterUnused(typeParameter) {
63555             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
63556         }
63557         function addToGroup(map, key, value, getKey) {
63558             var keyString = String(getKey(key));
63559             var group = map.get(keyString);
63560             if (group) {
63561                 group[1].push(value);
63562             }
63563             else {
63564                 map.set(keyString, [key, [value]]);
63565             }
63566         }
63567         function tryGetRootParameterDeclaration(node) {
63568             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
63569         }
63570         function isValidUnusedLocalDeclaration(declaration) {
63571             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
63572                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
63573                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
63574                         ts.isForOfStatement(ancestor) ? true : "quit";
63575                 });
63576             }
63577             return ts.isAmbientModule(declaration) ||
63578                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
63579         }
63580         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
63581             // 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.
63582             var unusedImports = ts.createMap();
63583             var unusedDestructures = ts.createMap();
63584             var unusedVariables = ts.createMap();
63585             nodeWithLocals.locals.forEach(function (local) {
63586                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
63587                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
63588                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
63589                     return;
63590                 }
63591                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
63592                     var declaration = _a[_i];
63593                     if (isValidUnusedLocalDeclaration(declaration)) {
63594                         continue;
63595                     }
63596                     if (isImportedDeclaration(declaration)) {
63597                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
63598                     }
63599                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
63600                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
63601                         var lastElement = ts.last(declaration.parent.elements);
63602                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
63603                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
63604                         }
63605                     }
63606                     else if (ts.isVariableDeclaration(declaration)) {
63607                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
63608                     }
63609                     else {
63610                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
63611                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
63612                         if (parameter && name) {
63613                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
63614                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
63615                             }
63616                         }
63617                         else {
63618                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
63619                         }
63620                     }
63621                 }
63622             });
63623             unusedImports.forEach(function (_a) {
63624                 var importClause = _a[0], unuseds = _a[1];
63625                 var importDecl = importClause.parent;
63626                 var nDeclarations = (importClause.name ? 1 : 0) +
63627                     (importClause.namedBindings ?
63628                         (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
63629                         : 0);
63630                 if (nDeclarations === unuseds.length) {
63631                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
63632                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
63633                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
63634                 }
63635                 else {
63636                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
63637                         var unused = unuseds_1[_i];
63638                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
63639                     }
63640                 }
63641             });
63642             unusedDestructures.forEach(function (_a) {
63643                 var bindingPattern = _a[0], bindingElements = _a[1];
63644                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
63645                 if (bindingPattern.elements.length === bindingElements.length) {
63646                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
63647                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
63648                     }
63649                     else {
63650                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
63651                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
63652                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
63653                     }
63654                 }
63655                 else {
63656                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
63657                         var e = bindingElements_1[_i];
63658                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
63659                     }
63660                 }
63661             });
63662             unusedVariables.forEach(function (_a) {
63663                 var declarationList = _a[0], declarations = _a[1];
63664                 if (declarationList.declarations.length === declarations.length) {
63665                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
63666                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
63667                         : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
63668                 }
63669                 else {
63670                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
63671                         var decl = declarations_5[_i];
63672                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
63673                     }
63674                 }
63675             });
63676         }
63677         function bindingNameText(name) {
63678             switch (name.kind) {
63679                 case 75 /* Identifier */:
63680                     return ts.idText(name);
63681                 case 190 /* ArrayBindingPattern */:
63682                 case 189 /* ObjectBindingPattern */:
63683                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
63684                 default:
63685                     return ts.Debug.assertNever(name);
63686             }
63687         }
63688         function isImportedDeclaration(node) {
63689             return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
63690         }
63691         function importClauseFromImported(decl) {
63692             return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
63693         }
63694         function checkBlock(node) {
63695             // Grammar checking for SyntaxKind.Block
63696             if (node.kind === 223 /* Block */) {
63697                 checkGrammarStatementInAmbientContext(node);
63698             }
63699             if (ts.isFunctionOrModuleBlock(node)) {
63700                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
63701                 ts.forEach(node.statements, checkSourceElement);
63702                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
63703             }
63704             else {
63705                 ts.forEach(node.statements, checkSourceElement);
63706             }
63707             if (node.locals) {
63708                 registerForUnusedIdentifiersCheck(node);
63709             }
63710         }
63711         function checkCollisionWithArgumentsInGeneratedCode(node) {
63712             // no rest parameters \ declaration context \ overload - no codegen impact
63713             if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
63714                 return;
63715             }
63716             ts.forEach(node.parameters, function (p) {
63717                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
63718                     error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
63719                 }
63720             });
63721         }
63722         function needCollisionCheckForIdentifier(node, identifier, name) {
63723             if (!(identifier && identifier.escapedText === name)) {
63724                 return false;
63725             }
63726             if (node.kind === 159 /* PropertyDeclaration */ ||
63727                 node.kind === 158 /* PropertySignature */ ||
63728                 node.kind === 161 /* MethodDeclaration */ ||
63729                 node.kind === 160 /* MethodSignature */ ||
63730                 node.kind === 163 /* GetAccessor */ ||
63731                 node.kind === 164 /* SetAccessor */) {
63732                 // it is ok to have member named '_super' or '_this' - member access is always qualified
63733                 return false;
63734             }
63735             if (node.flags & 8388608 /* Ambient */) {
63736                 // ambient context - no codegen impact
63737                 return false;
63738             }
63739             var root = ts.getRootDeclaration(node);
63740             if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
63741                 // just an overload - no codegen impact
63742                 return false;
63743             }
63744             return true;
63745         }
63746         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
63747         function checkIfThisIsCapturedInEnclosingScope(node) {
63748             ts.findAncestor(node, function (current) {
63749                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
63750                     var isDeclaration_1 = node.kind !== 75 /* Identifier */;
63751                     if (isDeclaration_1) {
63752                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
63753                     }
63754                     else {
63755                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
63756                     }
63757                     return true;
63758                 }
63759                 return false;
63760             });
63761         }
63762         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
63763             ts.findAncestor(node, function (current) {
63764                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
63765                     var isDeclaration_2 = node.kind !== 75 /* Identifier */;
63766                     if (isDeclaration_2) {
63767                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
63768                     }
63769                     else {
63770                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
63771                     }
63772                     return true;
63773                 }
63774                 return false;
63775             });
63776         }
63777         function checkWeakMapCollision(node) {
63778             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
63779             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
63780                 error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
63781             }
63782         }
63783         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
63784             // No need to check for require or exports for ES6 modules and later
63785             if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
63786                 return;
63787             }
63788             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
63789                 return;
63790             }
63791             // Uninstantiated modules shouldnt do this check
63792             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63793                 return;
63794             }
63795             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63796             var parent = getDeclarationContainer(node);
63797             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
63798                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
63799                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
63800             }
63801         }
63802         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
63803             if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
63804                 return;
63805             }
63806             // Uninstantiated modules shouldnt do this check
63807             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63808                 return;
63809             }
63810             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63811             var parent = getDeclarationContainer(node);
63812             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
63813                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
63814                 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));
63815             }
63816         }
63817         function checkVarDeclaredNamesNotShadowed(node) {
63818             // - ScriptBody : StatementList
63819             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63820             // also occurs in the VarDeclaredNames of StatementList.
63821             // - Block : { StatementList }
63822             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63823             // also occurs in the VarDeclaredNames of StatementList.
63824             // Variable declarations are hoisted to the top of their function scope. They can shadow
63825             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
63826             // by the binder as the declaration scope is different.
63827             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
63828             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
63829             // block declared value. this is fine for let, but not const.
63830             // Only consider declarations with initializers, uninitialized const declarations will not
63831             // step on a let/const variable.
63832             // Do not consider const and const declarations, as duplicate block-scoped declarations
63833             // are handled by the binder.
63834             // We are only looking for const declarations that step on let\const declarations from a
63835             // different scope. e.g.:
63836             //      {
63837             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
63838             //          const x = 0; // symbol for this declaration will be 'symbol'
63839             //      }
63840             // skip block-scoped variables and parameters
63841             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
63842                 return;
63843             }
63844             // skip variable declarations that don't have initializers
63845             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
63846             // so we'll always treat binding elements as initialized
63847             if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
63848                 return;
63849             }
63850             var symbol = getSymbolOfNode(node);
63851             if (symbol.flags & 1 /* FunctionScopedVariable */) {
63852                 if (!ts.isIdentifier(node.name))
63853                     return ts.Debug.fail();
63854                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
63855                 if (localDeclarationSymbol &&
63856                     localDeclarationSymbol !== symbol &&
63857                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
63858                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
63859                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
63860                         var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
63861                             ? varDeclList.parent.parent
63862                             : undefined;
63863                         // names of block-scoped and function scoped variables can collide only
63864                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
63865                         var namesShareScope = container &&
63866                             (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
63867                                 container.kind === 250 /* ModuleBlock */ ||
63868                                 container.kind === 249 /* ModuleDeclaration */ ||
63869                                 container.kind === 290 /* SourceFile */);
63870                         // here we know that function scoped variable is shadowed by block scoped one
63871                         // if they are defined in the same scope - binder has already reported redeclaration error
63872                         // otherwise if variable has an initializer - show error that initialization will fail
63873                         // since LHS will be block scoped name instead of function scoped
63874                         if (!namesShareScope) {
63875                             var name = symbolToString(localDeclarationSymbol);
63876                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
63877                         }
63878                     }
63879                 }
63880             }
63881         }
63882         function convertAutoToAny(type) {
63883             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
63884         }
63885         // Check variable, parameter, or property declaration
63886         function checkVariableLikeDeclaration(node) {
63887             checkDecorators(node);
63888             if (!ts.isBindingElement(node)) {
63889                 checkSourceElement(node.type);
63890             }
63891             // JSDoc `function(string, string): string` syntax results in parameters with no name
63892             if (!node.name) {
63893                 return;
63894             }
63895             // For a computed property, just check the initializer and exit
63896             // Do not use hasDynamicName here, because that returns false for well known symbols.
63897             // We want to perform checkComputedPropertyName for all computed properties, including
63898             // well known symbols.
63899             if (node.name.kind === 154 /* ComputedPropertyName */) {
63900                 checkComputedPropertyName(node.name);
63901                 if (node.initializer) {
63902                     checkExpressionCached(node.initializer);
63903                 }
63904             }
63905             if (node.kind === 191 /* BindingElement */) {
63906                 if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
63907                     checkExternalEmitHelpers(node, 4 /* Rest */);
63908                 }
63909                 // check computed properties inside property names of binding elements
63910                 if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
63911                     checkComputedPropertyName(node.propertyName);
63912                 }
63913                 // check private/protected variable access
63914                 var parent = node.parent.parent;
63915                 var parentType = getTypeForBindingElementParent(parent);
63916                 var name = node.propertyName || node.name;
63917                 if (parentType && !ts.isBindingPattern(name)) {
63918                     var exprType = getLiteralTypeFromPropertyName(name);
63919                     if (isTypeUsableAsPropertyName(exprType)) {
63920                         var nameText = getPropertyNameFromType(exprType);
63921                         var property = getPropertyOfType(parentType, nameText);
63922                         if (property) {
63923                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
63924                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
63925                         }
63926                     }
63927                 }
63928             }
63929             // For a binding pattern, check contained binding elements
63930             if (ts.isBindingPattern(node.name)) {
63931                 if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
63932                     checkExternalEmitHelpers(node, 512 /* Read */);
63933                 }
63934                 ts.forEach(node.name.elements, checkSourceElement);
63935             }
63936             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
63937             if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
63938                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
63939                 return;
63940             }
63941             // For a binding pattern, validate the initializer and exit
63942             if (ts.isBindingPattern(node.name)) {
63943                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
63944                 var needCheckWidenedType = node.name.elements.length === 0;
63945                 if (needCheckInitializer || needCheckWidenedType) {
63946                     // Don't validate for-in initializer as it is already an error
63947                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
63948                     if (needCheckInitializer) {
63949                         var initializerType = checkExpressionCached(node.initializer);
63950                         if (strictNullChecks && needCheckWidenedType) {
63951                             checkNonNullNonVoidType(initializerType, node);
63952                         }
63953                         else {
63954                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
63955                         }
63956                     }
63957                     // check the binding pattern with empty elements
63958                     if (needCheckWidenedType) {
63959                         if (ts.isArrayBindingPattern(node.name)) {
63960                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
63961                         }
63962                         else if (strictNullChecks) {
63963                             checkNonNullNonVoidType(widenedType, node);
63964                         }
63965                     }
63966                 }
63967                 return;
63968             }
63969             var symbol = getSymbolOfNode(node);
63970             var type = convertAutoToAny(getTypeOfSymbol(symbol));
63971             if (node === symbol.valueDeclaration) {
63972                 // Node is the primary declaration of the symbol, just validate the initializer
63973                 // Don't validate for-in initializer as it is already an error
63974                 var initializer = ts.getEffectiveInitializer(node);
63975                 if (initializer) {
63976                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
63977                         ts.isObjectLiteralExpression(initializer) &&
63978                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
63979                         ts.hasEntries(symbol.exports);
63980                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
63981                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
63982                     }
63983                 }
63984                 if (symbol.declarations.length > 1) {
63985                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
63986                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63987                     }
63988                 }
63989             }
63990             else {
63991                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
63992                 // initializer is consistent with type associated with the node
63993                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
63994                 if (type !== errorType && declarationType !== errorType &&
63995                     !isTypeIdenticalTo(type, declarationType) &&
63996                     !(symbol.flags & 67108864 /* Assignment */)) {
63997                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
63998                 }
63999                 if (node.initializer) {
64000                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
64001                 }
64002                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
64003                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
64004                 }
64005             }
64006             if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
64007                 // We know we don't have a binding pattern or computed name here
64008                 checkExportsOnMergedDeclarations(node);
64009                 if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
64010                     checkVarDeclaredNamesNotShadowed(node);
64011                 }
64012                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
64013                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
64014                 if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
64015                     potentialWeakMapCollisions.push(node);
64016                 }
64017             }
64018         }
64019         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
64020             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
64021             var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
64022                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
64023                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
64024             var declName = ts.declarationNameToString(nextDeclarationName);
64025             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
64026             if (firstDeclaration) {
64027                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
64028             }
64029         }
64030         function areDeclarationFlagsIdentical(left, right) {
64031             if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
64032                 (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
64033                 // Differences in optionality between parameters and variables are allowed.
64034                 return true;
64035             }
64036             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
64037                 return false;
64038             }
64039             var interestingFlags = 8 /* Private */ |
64040                 16 /* Protected */ |
64041                 256 /* Async */ |
64042                 128 /* Abstract */ |
64043                 64 /* Readonly */ |
64044                 32 /* Static */;
64045             return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
64046         }
64047         function checkVariableDeclaration(node) {
64048             checkGrammarVariableDeclaration(node);
64049             return checkVariableLikeDeclaration(node);
64050         }
64051         function checkBindingElement(node) {
64052             checkGrammarBindingElement(node);
64053             return checkVariableLikeDeclaration(node);
64054         }
64055         function checkVariableStatement(node) {
64056             // Grammar checking
64057             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
64058                 checkGrammarForDisallowedLetOrConstStatement(node);
64059             ts.forEach(node.declarationList.declarations, checkSourceElement);
64060         }
64061         function checkExpressionStatement(node) {
64062             // Grammar checking
64063             checkGrammarStatementInAmbientContext(node);
64064             checkExpression(node.expression);
64065         }
64066         function checkIfStatement(node) {
64067             // Grammar checking
64068             checkGrammarStatementInAmbientContext(node);
64069             var type = checkTruthinessExpression(node.expression);
64070             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
64071             checkSourceElement(node.thenStatement);
64072             if (node.thenStatement.kind === 224 /* EmptyStatement */) {
64073                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
64074             }
64075             checkSourceElement(node.elseStatement);
64076         }
64077         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
64078             if (!strictNullChecks) {
64079                 return;
64080             }
64081             var testedNode = ts.isIdentifier(condExpr)
64082                 ? condExpr
64083                 : ts.isPropertyAccessExpression(condExpr)
64084                     ? condExpr.name
64085                     : undefined;
64086             if (!testedNode) {
64087                 return;
64088             }
64089             var possiblyFalsy = getFalsyFlags(type);
64090             if (possiblyFalsy) {
64091                 return;
64092             }
64093             // While it technically should be invalid for any known-truthy value
64094             // to be tested, we de-scope to functions unrefenced in the block as a
64095             // heuristic to identify the most common bugs. There are too many
64096             // false positives for values sourced from type definitions without
64097             // strictNullChecks otherwise.
64098             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
64099             if (callSignatures.length === 0) {
64100                 return;
64101             }
64102             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
64103             if (!testedFunctionSymbol) {
64104                 return;
64105             }
64106             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
64107                 if (ts.isIdentifier(childNode)) {
64108                     var childSymbol = getSymbolAtLocation(childNode);
64109                     if (childSymbol && childSymbol === testedFunctionSymbol) {
64110                         // If the test was a simple identifier, the above check is sufficient
64111                         if (ts.isIdentifier(condExpr)) {
64112                             return true;
64113                         }
64114                         // Otherwise we need to ensure the symbol is called on the same target
64115                         var testedExpression = testedNode.parent;
64116                         var childExpression = childNode.parent;
64117                         while (testedExpression && childExpression) {
64118                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
64119                                 testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) {
64120                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
64121                             }
64122                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
64123                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
64124                                     return false;
64125                                 }
64126                                 childExpression = childExpression.expression;
64127                                 testedExpression = testedExpression.expression;
64128                             }
64129                             else {
64130                                 return false;
64131                             }
64132                         }
64133                     }
64134                 }
64135                 return ts.forEachChild(childNode, check);
64136             });
64137             if (!functionIsUsedInBody) {
64138                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
64139             }
64140         }
64141         function checkDoStatement(node) {
64142             // Grammar checking
64143             checkGrammarStatementInAmbientContext(node);
64144             checkSourceElement(node.statement);
64145             checkTruthinessExpression(node.expression);
64146         }
64147         function checkWhileStatement(node) {
64148             // Grammar checking
64149             checkGrammarStatementInAmbientContext(node);
64150             checkTruthinessExpression(node.expression);
64151             checkSourceElement(node.statement);
64152         }
64153         function checkTruthinessOfType(type, node) {
64154             if (type.flags & 16384 /* Void */) {
64155                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
64156             }
64157             return type;
64158         }
64159         function checkTruthinessExpression(node, checkMode) {
64160             return checkTruthinessOfType(checkExpression(node, checkMode), node);
64161         }
64162         function checkForStatement(node) {
64163             // Grammar checking
64164             if (!checkGrammarStatementInAmbientContext(node)) {
64165                 if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
64166                     checkGrammarVariableDeclarationList(node.initializer);
64167                 }
64168             }
64169             if (node.initializer) {
64170                 if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64171                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
64172                 }
64173                 else {
64174                     checkExpression(node.initializer);
64175                 }
64176             }
64177             if (node.condition)
64178                 checkTruthinessExpression(node.condition);
64179             if (node.incrementor)
64180                 checkExpression(node.incrementor);
64181             checkSourceElement(node.statement);
64182             if (node.locals) {
64183                 registerForUnusedIdentifiersCheck(node);
64184             }
64185         }
64186         function checkForOfStatement(node) {
64187             checkGrammarForInOrForOfStatement(node);
64188             if (node.awaitModifier) {
64189                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
64190                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
64191                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
64192                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
64193                 }
64194             }
64195             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
64196                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
64197                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
64198             }
64199             // Check the LHS and RHS
64200             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
64201             // via checkRightHandSideOfForOf.
64202             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
64203             // Then check that the RHS is assignable to it.
64204             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64205                 checkForInOrForOfVariableDeclaration(node);
64206             }
64207             else {
64208                 var varExpr = node.initializer;
64209                 var iteratedType = checkRightHandSideOfForOf(node);
64210                 // There may be a destructuring assignment on the left side
64211                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64212                     // iteratedType may be undefined. In this case, we still want to check the structure of
64213                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
64214                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
64215                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
64216                 }
64217                 else {
64218                     var leftType = checkExpression(varExpr);
64219                     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);
64220                     // iteratedType will be undefined if the rightType was missing properties/signatures
64221                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
64222                     // because we accessed properties from anyType, or it may have led to an error inside
64223                     // getElementTypeOfIterable.
64224                     if (iteratedType) {
64225                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
64226                     }
64227                 }
64228             }
64229             checkSourceElement(node.statement);
64230             if (node.locals) {
64231                 registerForUnusedIdentifiersCheck(node);
64232             }
64233         }
64234         function checkForInStatement(node) {
64235             // Grammar checking
64236             checkGrammarForInOrForOfStatement(node);
64237             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
64238             // TypeScript 1.0 spec (April 2014): 5.4
64239             // In a 'for-in' statement of the form
64240             // for (let VarDecl in Expr) Statement
64241             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
64242             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64243             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64244                 var variable = node.initializer.declarations[0];
64245                 if (variable && ts.isBindingPattern(variable.name)) {
64246                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64247                 }
64248                 checkForInOrForOfVariableDeclaration(node);
64249             }
64250             else {
64251                 // In a 'for-in' statement of the form
64252                 // for (Var in Expr) Statement
64253                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
64254                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64255                 var varExpr = node.initializer;
64256                 var leftType = checkExpression(varExpr);
64257                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64258                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64259                 }
64260                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
64261                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
64262                 }
64263                 else {
64264                     // run check only former check succeeded to avoid cascading errors
64265                     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);
64266                 }
64267             }
64268             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
64269             // in this case error about missing name is already reported - do not report extra one
64270             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
64271                 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));
64272             }
64273             checkSourceElement(node.statement);
64274             if (node.locals) {
64275                 registerForUnusedIdentifiersCheck(node);
64276             }
64277         }
64278         function checkForInOrForOfVariableDeclaration(iterationStatement) {
64279             var variableDeclarationList = iterationStatement.initializer;
64280             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
64281             if (variableDeclarationList.declarations.length >= 1) {
64282                 var decl = variableDeclarationList.declarations[0];
64283                 checkVariableDeclaration(decl);
64284             }
64285         }
64286         function checkRightHandSideOfForOf(statement) {
64287             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
64288             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
64289         }
64290         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
64291             if (isTypeAny(inputType)) {
64292                 return inputType;
64293             }
64294             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
64295         }
64296         /**
64297          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
64298          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
64299          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
64300          */
64301         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
64302             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
64303             if (inputType === neverType) {
64304                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
64305                 return undefined;
64306             }
64307             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
64308             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
64309             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
64310             // or higher, when inside of an async generator or for-await-if, or when
64311             // downlevelIteration is requested.
64312             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
64313                 // We only report errors for an invalid iterable type in ES2015 or higher.
64314                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
64315                 if (checkAssignability) {
64316                     if (iterationTypes) {
64317                         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 :
64318                             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 :
64319                                 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 :
64320                                     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 :
64321                                         undefined;
64322                         if (diagnostic) {
64323                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
64324                         }
64325                     }
64326                 }
64327                 if (iterationTypes || uplevelIteration) {
64328                     return iterationTypes && iterationTypes.yieldType;
64329                 }
64330             }
64331             var arrayType = inputType;
64332             var reportedError = false;
64333             var hasStringConstituent = false;
64334             // If strings are permitted, remove any string-like constituents from the array type.
64335             // This allows us to find other non-string element types from an array unioned with
64336             // a string.
64337             if (use & 4 /* AllowsStringInputFlag */) {
64338                 if (arrayType.flags & 1048576 /* Union */) {
64339                     // After we remove all types that are StringLike, we will know if there was a string constituent
64340                     // based on whether the result of filter is a new array.
64341                     var arrayTypes = inputType.types;
64342                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
64343                     if (filteredTypes !== arrayTypes) {
64344                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
64345                     }
64346                 }
64347                 else if (arrayType.flags & 132 /* StringLike */) {
64348                     arrayType = neverType;
64349                 }
64350                 hasStringConstituent = arrayType !== inputType;
64351                 if (hasStringConstituent) {
64352                     if (languageVersion < 1 /* ES5 */) {
64353                         if (errorNode) {
64354                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
64355                             reportedError = true;
64356                         }
64357                     }
64358                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
64359                     // arrayOrStringType was a string.
64360                     if (arrayType.flags & 131072 /* Never */) {
64361                         return stringType;
64362                     }
64363                 }
64364             }
64365             if (!isArrayLikeType(arrayType)) {
64366                 if (errorNode && !reportedError) {
64367                     // Which error we report depends on whether we allow strings or if there was a
64368                     // string constituent. For example, if the input type is number | string, we
64369                     // want to say that number is not an array type. But if the input was just
64370                     // number and string input is allowed, we want to say that number is not an
64371                     // array type or a string type.
64372                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
64373                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
64374                         ? downlevelIteration
64375                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
64376                             : yieldType
64377                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64378                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
64379                         : downlevelIteration
64380                             ? [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]
64381                             : yieldType
64382                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64383                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
64384                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
64385                 }
64386                 return hasStringConstituent ? stringType : undefined;
64387             }
64388             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
64389             if (hasStringConstituent && arrayElementType) {
64390                 // This is just an optimization for the case where arrayOrStringType is string | string[]
64391                 if (arrayElementType.flags & 132 /* StringLike */) {
64392                     return stringType;
64393                 }
64394                 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
64395             }
64396             return arrayElementType;
64397         }
64398         /**
64399          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
64400          */
64401         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
64402             if (isTypeAny(inputType)) {
64403                 return undefined;
64404             }
64405             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
64406             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
64407         }
64408         function createIterationTypes(yieldType, returnType, nextType) {
64409             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
64410             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
64411             // as it is combined via `getIntersectionType` when merging iteration types.
64412             if (yieldType === void 0) { yieldType = neverType; }
64413             if (returnType === void 0) { returnType = neverType; }
64414             if (nextType === void 0) { nextType = unknownType; }
64415             // Use the cache only for intrinsic types to keep it small as they are likely to be
64416             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
64417             // are also cached on the type they are requested for, so we shouldn't need to maintain
64418             // the cache for less-frequently used types.
64419             if (yieldType.flags & 67359327 /* Intrinsic */ &&
64420                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
64421                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
64422                 var id = getTypeListId([yieldType, returnType, nextType]);
64423                 var iterationTypes = iterationTypesCache.get(id);
64424                 if (!iterationTypes) {
64425                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
64426                     iterationTypesCache.set(id, iterationTypes);
64427                 }
64428                 return iterationTypes;
64429             }
64430             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
64431         }
64432         /**
64433          * Combines multiple `IterationTypes` records.
64434          *
64435          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
64436          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
64437          * for the combined iteration types.
64438          */
64439         function combineIterationTypes(array) {
64440             var yieldTypes;
64441             var returnTypes;
64442             var nextTypes;
64443             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
64444                 var iterationTypes = array_10[_i];
64445                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
64446                     continue;
64447                 }
64448                 if (iterationTypes === anyIterationTypes) {
64449                     return anyIterationTypes;
64450                 }
64451                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
64452                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64453                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
64454             }
64455             if (yieldTypes || returnTypes || nextTypes) {
64456                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
64457             }
64458             return noIterationTypes;
64459         }
64460         function getCachedIterationTypes(type, cacheKey) {
64461             return type[cacheKey];
64462         }
64463         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
64464             return type[cacheKey] = cachedTypes;
64465         }
64466         /**
64467          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
64468          *
64469          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
64470          *
64471          * Another thing to note is that at any step of this process, we could run into a dead end,
64472          * meaning either the property is missing, or we run into the anyType. If either of these things
64473          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
64474          * is missing, and the previous step did not result in `any`, then we also give an error if the
64475          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
64476          * type.
64477          *
64478          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
64479          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
64480          * method.
64481          *
64482          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
64483          *
64484          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
64485          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
64486          */
64487         function getIterationTypesOfIterable(type, use, errorNode) {
64488             if (isTypeAny(type)) {
64489                 return anyIterationTypes;
64490             }
64491             if (!(type.flags & 1048576 /* Union */)) {
64492                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
64493                 if (iterationTypes_1 === noIterationTypes) {
64494                     if (errorNode) {
64495                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64496                     }
64497                     return undefined;
64498                 }
64499                 return iterationTypes_1;
64500             }
64501             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
64502             var cachedTypes = getCachedIterationTypes(type, cacheKey);
64503             if (cachedTypes)
64504                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
64505             var allIterationTypes;
64506             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
64507                 var constituent = _a[_i];
64508                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
64509                 if (iterationTypes_2 === noIterationTypes) {
64510                     if (errorNode) {
64511                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64512                         errorNode = undefined;
64513                     }
64514                 }
64515                 else {
64516                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
64517                 }
64518             }
64519             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
64520             setCachedIterationTypes(type, cacheKey, iterationTypes);
64521             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64522         }
64523         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
64524             if (iterationTypes === noIterationTypes)
64525                 return noIterationTypes;
64526             if (iterationTypes === anyIterationTypes)
64527                 return anyIterationTypes;
64528             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
64529             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
64530         }
64531         /**
64532          * Gets the *yield*, *return*, and *next* types from a non-union type.
64533          *
64534          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
64535          * returned to indicate to the caller that it should report an error. Otherwise, an
64536          * `IterationTypes` record is returned.
64537          *
64538          * NOTE: You probably don't want to call this directly and should be calling
64539          * `getIterationTypesOfIterable` instead.
64540          */
64541         function getIterationTypesOfIterableWorker(type, use, errorNode) {
64542             if (isTypeAny(type)) {
64543                 return anyIterationTypes;
64544             }
64545             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64546                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
64547                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
64548                 if (iterationTypes) {
64549                     return iterationTypes;
64550                 }
64551             }
64552             if (use & 1 /* AllowsSyncIterablesFlag */) {
64553                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
64554                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
64555                 if (iterationTypes) {
64556                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64557                         // for a sync iterable in an async context, only use the cached types if they are valid.
64558                         if (iterationTypes !== noIterationTypes) {
64559                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
64560                         }
64561                     }
64562                     else {
64563                         return iterationTypes;
64564                     }
64565                 }
64566             }
64567             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64568                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
64569                 if (iterationTypes !== noIterationTypes) {
64570                     return iterationTypes;
64571                 }
64572             }
64573             if (use & 1 /* AllowsSyncIterablesFlag */) {
64574                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
64575                 if (iterationTypes !== noIterationTypes) {
64576                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64577                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
64578                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
64579                             : noIterationTypes);
64580                     }
64581                     else {
64582                         return iterationTypes;
64583                     }
64584                 }
64585             }
64586             return noIterationTypes;
64587         }
64588         /**
64589          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
64590          * `AsyncIterable`-like type from the cache.
64591          *
64592          * NOTE: You probably don't want to call this directly and should be calling
64593          * `getIterationTypesOfIterable` instead.
64594          */
64595         function getIterationTypesOfIterableCached(type, resolver) {
64596             return getCachedIterationTypes(type, resolver.iterableCacheKey);
64597         }
64598         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
64599             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
64600                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
64601             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
64602         }
64603         /**
64604          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64605          * type from from common heuristics.
64606          *
64607          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64608          * returned. If we found iteration types, an `IterationTypes` record is returned.
64609          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64610          * exhaustive analysis.
64611          *
64612          * NOTE: You probably don't want to call this directly and should be calling
64613          * `getIterationTypesOfIterable` instead.
64614          */
64615         function getIterationTypesOfIterableFast(type, resolver) {
64616             // As an optimization, if the type is an instantiation of one of the following global types, then
64617             // just grab its related type argument:
64618             // - `Iterable<T>` or `AsyncIterable<T>`
64619             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64620             var globalType;
64621             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
64622                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
64623                 var yieldType = getTypeArguments(type)[0];
64624                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
64625                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
64626                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
64627                 // different definitions.
64628                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
64629                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64630             }
64631             // As an optimization, if the type is an instantiation of the following global type, then
64632             // just grab its related type arguments:
64633             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64634             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64635                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64636                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64637             }
64638         }
64639         /**
64640          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64641          * type from its members.
64642          *
64643          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64644          * record is returned. Otherwise, `noIterationTypes` is returned.
64645          *
64646          * NOTE: You probably don't want to call this directly and should be calling
64647          * `getIterationTypesOfIterable` instead.
64648          */
64649         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
64650             var _a;
64651             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
64652             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
64653             if (isTypeAny(methodType)) {
64654                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
64655             }
64656             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
64657             if (!ts.some(signatures)) {
64658                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
64659             }
64660             var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
64661             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
64662             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
64663         }
64664         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
64665             var message = allowAsyncIterables
64666                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
64667                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
64668             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
64669         }
64670         /**
64671          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
64672          *
64673          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64674          * record is returned. Otherwise, `undefined` is returned.
64675          */
64676         function getIterationTypesOfIterator(type, resolver, errorNode) {
64677             if (isTypeAny(type)) {
64678                 return anyIterationTypes;
64679             }
64680             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
64681                 getIterationTypesOfIteratorFast(type, resolver) ||
64682                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
64683             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64684         }
64685         /**
64686          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64687          * cache.
64688          *
64689          * NOTE: You probably don't want to call this directly and should be calling
64690          * `getIterationTypesOfIterator` instead.
64691          */
64692         function getIterationTypesOfIteratorCached(type, resolver) {
64693             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
64694         }
64695         /**
64696          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64697          * cache or from common heuristics.
64698          *
64699          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64700          * returned. If we found iteration types, an `IterationTypes` record is returned.
64701          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64702          * exhaustive analysis.
64703          *
64704          * NOTE: You probably don't want to call this directly and should be calling
64705          * `getIterationTypesOfIterator` instead.
64706          */
64707         function getIterationTypesOfIteratorFast(type, resolver) {
64708             // As an optimization, if the type is an instantiation of one of the following global types,
64709             // then just grab its related type argument:
64710             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64711             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
64712             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64713             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
64714             if (isReferenceToType(type, globalType)) {
64715                 var yieldType = getTypeArguments(type)[0];
64716                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
64717                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
64718                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
64719                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
64720                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
64721                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
64722                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64723             }
64724             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
64725                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64726                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64727                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64728             }
64729         }
64730         function isIteratorResult(type, kind) {
64731             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
64732             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
64733             // > If the end was not reached `done` is `false` and a value is available.
64734             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
64735             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
64736             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
64737         }
64738         function isYieldIteratorResult(type) {
64739             return isIteratorResult(type, 0 /* Yield */);
64740         }
64741         function isReturnIteratorResult(type) {
64742             return isIteratorResult(type, 1 /* Return */);
64743         }
64744         /**
64745          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
64746          *
64747          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
64748          * returned to indicate to the caller that it should handle the error. Otherwise, an
64749          * `IterationTypes` record is returned.
64750          */
64751         function getIterationTypesOfIteratorResult(type) {
64752             if (isTypeAny(type)) {
64753                 return anyIterationTypes;
64754             }
64755             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
64756             if (cachedTypes) {
64757                 return cachedTypes;
64758             }
64759             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
64760             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
64761             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
64762                 var yieldType_1 = getTypeArguments(type)[0];
64763                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
64764             }
64765             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
64766                 var returnType_1 = getTypeArguments(type)[0];
64767                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
64768             }
64769             // Choose any constituents that can produce the requested iteration type.
64770             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
64771             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
64772             var returnIteratorResult = filterType(type, isReturnIteratorResult);
64773             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
64774             if (!yieldType && !returnType) {
64775                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
64776             }
64777             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
64778             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
64779             // > `value` property may be absent from the conforming object if it does not inherit an explicit
64780             // > `value` property.
64781             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
64782         }
64783         /**
64784          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
64785          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
64786          *
64787          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64788          * record is returned. Otherwise, we return `undefined`.
64789          */
64790         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
64791             var method = getPropertyOfType(type, methodName);
64792             // Ignore 'return' or 'throw' if they are missing.
64793             if (!method && methodName !== "next") {
64794                 return undefined;
64795             }
64796             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
64797                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
64798                 : undefined;
64799             if (isTypeAny(methodType)) {
64800                 // `return()` and `throw()` don't provide a *next* type.
64801                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
64802             }
64803             // Both async and non-async iterators *must* have a `next` method.
64804             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
64805             if (methodSignatures.length === 0) {
64806                 if (errorNode) {
64807                     var diagnostic = methodName === "next"
64808                         ? resolver.mustHaveANextMethodDiagnostic
64809                         : resolver.mustBeAMethodDiagnostic;
64810                     error(errorNode, diagnostic, methodName);
64811                 }
64812                 return methodName === "next" ? anyIterationTypes : undefined;
64813             }
64814             // Extract the first parameter and return type of each signature.
64815             var methodParameterTypes;
64816             var methodReturnTypes;
64817             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
64818                 var signature = methodSignatures_1[_i];
64819                 if (methodName !== "throw" && ts.some(signature.parameters)) {
64820                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
64821                 }
64822                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
64823             }
64824             // Resolve the *next* or *return* type from the first parameter of a `next()` or
64825             // `return()` method, respectively.
64826             var returnTypes;
64827             var nextType;
64828             if (methodName !== "throw") {
64829                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
64830                 if (methodName === "next") {
64831                     // The value of `next(value)` is *not* awaited by async generators
64832                     nextType = methodParameterType;
64833                 }
64834                 else if (methodName === "return") {
64835                     // The value of `return(value)` *is* awaited by async generators
64836                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
64837                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
64838                 }
64839             }
64840             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
64841             var yieldType;
64842             var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
64843             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
64844             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
64845             if (iterationTypes === noIterationTypes) {
64846                 if (errorNode) {
64847                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
64848                 }
64849                 yieldType = anyType;
64850                 returnTypes = ts.append(returnTypes, anyType);
64851             }
64852             else {
64853                 yieldType = iterationTypes.yieldType;
64854                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64855             }
64856             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
64857         }
64858         /**
64859          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
64860          * type from its members.
64861          *
64862          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64863          * record is returned. Otherwise, `noIterationTypes` is returned.
64864          *
64865          * NOTE: You probably don't want to call this directly and should be calling
64866          * `getIterationTypesOfIterator` instead.
64867          */
64868         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
64869             var iterationTypes = combineIterationTypes([
64870                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
64871                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
64872                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
64873             ]);
64874             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
64875         }
64876         /**
64877          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
64878          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
64879          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
64880          */
64881         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
64882             if (isTypeAny(returnType)) {
64883                 return undefined;
64884             }
64885             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
64886             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
64887         }
64888         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
64889             if (isTypeAny(type)) {
64890                 return anyIterationTypes;
64891             }
64892             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64893             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
64894             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
64895                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
64896         }
64897         function checkBreakOrContinueStatement(node) {
64898             // Grammar checking
64899             if (!checkGrammarStatementInAmbientContext(node))
64900                 checkGrammarBreakOrContinueStatement(node);
64901             // TODO: Check that target label is valid
64902         }
64903         function unwrapReturnType(returnType, functionFlags) {
64904             var _a, _b;
64905             var isGenerator = !!(functionFlags & 1 /* Generator */);
64906             var isAsync = !!(functionFlags & 2 /* Async */);
64907             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
64908                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
64909                     returnType;
64910         }
64911         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
64912             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
64913             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
64914         }
64915         function checkReturnStatement(node) {
64916             var _a;
64917             // Grammar checking
64918             if (checkGrammarStatementInAmbientContext(node)) {
64919                 return;
64920             }
64921             var func = ts.getContainingFunction(node);
64922             if (!func) {
64923                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
64924                 return;
64925             }
64926             var signature = getSignatureFromDeclaration(func);
64927             var returnType = getReturnTypeOfSignature(signature);
64928             var functionFlags = ts.getFunctionFlags(func);
64929             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
64930                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
64931                 if (func.kind === 164 /* SetAccessor */) {
64932                     if (node.expression) {
64933                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
64934                     }
64935                 }
64936                 else if (func.kind === 162 /* Constructor */) {
64937                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
64938                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
64939                     }
64940                 }
64941                 else if (getReturnTypeFromAnnotation(func)) {
64942                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
64943                     var unwrappedExprType = functionFlags & 2 /* Async */
64944                         ? 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)
64945                         : exprType;
64946                     if (unwrappedReturnType) {
64947                         // If the function has a return type, but promisedType is
64948                         // undefined, an error will be reported in checkAsyncFunctionReturnType
64949                         // so we don't need to report one here.
64950                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
64951                     }
64952                 }
64953             }
64954             else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
64955                 // The function has a return type, but the return statement doesn't have an expression.
64956                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
64957             }
64958         }
64959         function checkWithStatement(node) {
64960             // Grammar checking for withStatement
64961             if (!checkGrammarStatementInAmbientContext(node)) {
64962                 if (node.flags & 32768 /* AwaitContext */) {
64963                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
64964                 }
64965             }
64966             checkExpression(node.expression);
64967             var sourceFile = ts.getSourceFileOfNode(node);
64968             if (!hasParseDiagnostics(sourceFile)) {
64969                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
64970                 var end = node.statement.pos;
64971                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
64972             }
64973         }
64974         function checkSwitchStatement(node) {
64975             // Grammar checking
64976             checkGrammarStatementInAmbientContext(node);
64977             var firstDefaultClause;
64978             var hasDuplicateDefaultClause = false;
64979             var expressionType = checkExpression(node.expression);
64980             var expressionIsLiteral = isLiteralType(expressionType);
64981             ts.forEach(node.caseBlock.clauses, function (clause) {
64982                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
64983                 if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
64984                     if (firstDefaultClause === undefined) {
64985                         firstDefaultClause = clause;
64986                     }
64987                     else {
64988                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
64989                         hasDuplicateDefaultClause = true;
64990                     }
64991                 }
64992                 if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
64993                     // TypeScript 1.0 spec (April 2014): 5.9
64994                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
64995                     // to or from the type of the 'switch' expression.
64996                     var caseType = checkExpression(clause.expression);
64997                     var caseIsLiteral = isLiteralType(caseType);
64998                     var comparedExpressionType = expressionType;
64999                     if (!caseIsLiteral || !expressionIsLiteral) {
65000                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
65001                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
65002                     }
65003                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
65004                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
65005                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
65006                     }
65007                 }
65008                 ts.forEach(clause.statements, checkSourceElement);
65009                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
65010                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
65011                 }
65012             });
65013             if (node.caseBlock.locals) {
65014                 registerForUnusedIdentifiersCheck(node.caseBlock);
65015             }
65016         }
65017         function checkLabeledStatement(node) {
65018             // Grammar checking
65019             if (!checkGrammarStatementInAmbientContext(node)) {
65020                 ts.findAncestor(node.parent, function (current) {
65021                     if (ts.isFunctionLike(current)) {
65022                         return "quit";
65023                     }
65024                     if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
65025                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
65026                         return true;
65027                     }
65028                     return false;
65029                 });
65030             }
65031             // ensure that label is unique
65032             checkSourceElement(node.statement);
65033         }
65034         function checkThrowStatement(node) {
65035             // Grammar checking
65036             if (!checkGrammarStatementInAmbientContext(node)) {
65037                 if (node.expression === undefined) {
65038                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
65039                 }
65040             }
65041             if (node.expression) {
65042                 checkExpression(node.expression);
65043             }
65044         }
65045         function checkTryStatement(node) {
65046             // Grammar checking
65047             checkGrammarStatementInAmbientContext(node);
65048             checkBlock(node.tryBlock);
65049             var catchClause = node.catchClause;
65050             if (catchClause) {
65051                 // Grammar checking
65052                 if (catchClause.variableDeclaration) {
65053                     if (catchClause.variableDeclaration.type) {
65054                         grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
65055                     }
65056                     else if (catchClause.variableDeclaration.initializer) {
65057                         grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
65058                     }
65059                     else {
65060                         var blockLocals_1 = catchClause.block.locals;
65061                         if (blockLocals_1) {
65062                             ts.forEachKey(catchClause.locals, function (caughtName) {
65063                                 var blockLocal = blockLocals_1.get(caughtName);
65064                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
65065                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
65066                                 }
65067                             });
65068                         }
65069                     }
65070                 }
65071                 checkBlock(catchClause.block);
65072             }
65073             if (node.finallyBlock) {
65074                 checkBlock(node.finallyBlock);
65075             }
65076         }
65077         function checkIndexConstraints(type) {
65078             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
65079             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
65080             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
65081             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
65082             if (stringIndexType || numberIndexType) {
65083                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
65084                     var propType = getTypeOfSymbol(prop);
65085                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
65086                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
65087                 });
65088                 var classDeclaration = type.symbol.valueDeclaration;
65089                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
65090                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
65091                         var member = _a[_i];
65092                         // Only process instance properties with computed names here.
65093                         // Static properties cannot be in conflict with indexers,
65094                         // and properties with literal names were already checked.
65095                         if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
65096                             var symbol = getSymbolOfNode(member);
65097                             var propType = getTypeOfSymbol(symbol);
65098                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
65099                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
65100                         }
65101                     }
65102                 }
65103             }
65104             var errorNode;
65105             if (stringIndexType && numberIndexType) {
65106                 errorNode = declaredNumberIndexer || declaredStringIndexer;
65107                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
65108                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
65109                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
65110                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
65111                 }
65112             }
65113             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
65114                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
65115             }
65116             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
65117                 // ESSymbol properties apply to neither string nor numeric indexers.
65118                 if (!indexType || ts.isKnownSymbol(prop)) {
65119                     return;
65120                 }
65121                 var propDeclaration = prop.valueDeclaration;
65122                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
65123                 if (name && ts.isPrivateIdentifier(name)) {
65124                     return;
65125                 }
65126                 // index is numeric and property name is not valid numeric literal
65127                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
65128                     return;
65129                 }
65130                 // perform property check if property or indexer is declared in 'type'
65131                 // this allows us to rule out cases when both property and indexer are inherited from the base class
65132                 var errorNode;
65133                 if (propDeclaration && name &&
65134                     (propDeclaration.kind === 209 /* BinaryExpression */ ||
65135                         name.kind === 154 /* ComputedPropertyName */ ||
65136                         prop.parent === containingType.symbol)) {
65137                     errorNode = propDeclaration;
65138                 }
65139                 else if (indexDeclaration) {
65140                     errorNode = indexDeclaration;
65141                 }
65142                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
65143                     // for interfaces property and indexer might be inherited from different bases
65144                     // check if any base class already has both property and indexer.
65145                     // check should be performed only if 'type' is the first type that brings property\indexer together
65146                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
65147                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
65148                 }
65149                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
65150                     var errorMessage = indexKind === 0 /* String */
65151                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
65152                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
65153                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
65154                 }
65155             }
65156         }
65157         function checkTypeNameIsReserved(name, message) {
65158             // TS 1.0 spec (April 2014): 3.6.1
65159             // The predefined type keywords are reserved and cannot be used as names of user defined types.
65160             switch (name.escapedText) {
65161                 case "any":
65162                 case "unknown":
65163                 case "number":
65164                 case "bigint":
65165                 case "boolean":
65166                 case "string":
65167                 case "symbol":
65168                 case "void":
65169                 case "object":
65170                     error(name, message, name.escapedText);
65171             }
65172         }
65173         /**
65174          * The name cannot be used as 'Object' of user defined types with special target.
65175          */
65176         function checkClassNameCollisionWithObject(name) {
65177             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
65178                 && moduleKind < ts.ModuleKind.ES2015) {
65179                 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
65180             }
65181         }
65182         /**
65183          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
65184          */
65185         function checkTypeParameters(typeParameterDeclarations) {
65186             if (typeParameterDeclarations) {
65187                 var seenDefault = false;
65188                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
65189                     var node = typeParameterDeclarations[i];
65190                     checkTypeParameter(node);
65191                     if (produceDiagnostics) {
65192                         if (node.default) {
65193                             seenDefault = true;
65194                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
65195                         }
65196                         else if (seenDefault) {
65197                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
65198                         }
65199                         for (var j = 0; j < i; j++) {
65200                             if (typeParameterDeclarations[j].symbol === node.symbol) {
65201                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
65202                             }
65203                         }
65204                     }
65205                 }
65206             }
65207         }
65208         /** Check that type parameter defaults only reference previously declared type parameters */
65209         function checkTypeParametersNotReferenced(root, typeParameters, index) {
65210             visit(root);
65211             function visit(node) {
65212                 if (node.kind === 169 /* TypeReference */) {
65213                     var type = getTypeFromTypeReference(node);
65214                     if (type.flags & 262144 /* TypeParameter */) {
65215                         for (var i = index; i < typeParameters.length; i++) {
65216                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
65217                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
65218                             }
65219                         }
65220                     }
65221                 }
65222                 ts.forEachChild(node, visit);
65223             }
65224         }
65225         /** Check that type parameter lists are identical across multiple declarations */
65226         function checkTypeParameterListsIdentical(symbol) {
65227             if (symbol.declarations.length === 1) {
65228                 return;
65229             }
65230             var links = getSymbolLinks(symbol);
65231             if (!links.typeParametersChecked) {
65232                 links.typeParametersChecked = true;
65233                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
65234                 if (declarations.length <= 1) {
65235                     return;
65236                 }
65237                 var type = getDeclaredTypeOfSymbol(symbol);
65238                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
65239                     // Report an error on every conflicting declaration.
65240                     var name = symbolToString(symbol);
65241                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
65242                         var declaration = declarations_6[_i];
65243                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
65244                     }
65245                 }
65246             }
65247         }
65248         function areTypeParametersIdentical(declarations, targetParameters) {
65249             var maxTypeArgumentCount = ts.length(targetParameters);
65250             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
65251             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
65252                 var declaration = declarations_7[_i];
65253                 // If this declaration has too few or too many type parameters, we report an error
65254                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
65255                 var numTypeParameters = sourceParameters.length;
65256                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
65257                     return false;
65258                 }
65259                 for (var i = 0; i < numTypeParameters; i++) {
65260                     var source = sourceParameters[i];
65261                     var target = targetParameters[i];
65262                     // If the type parameter node does not have the same as the resolved type
65263                     // parameter at this position, we report an error.
65264                     if (source.name.escapedText !== target.symbol.escapedName) {
65265                         return false;
65266                     }
65267                     // If the type parameter node does not have an identical constraint as the resolved
65268                     // type parameter at this position, we report an error.
65269                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
65270                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
65271                     var targetConstraint = getConstraintOfTypeParameter(target);
65272                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
65273                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
65274                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
65275                         return false;
65276                     }
65277                     // If the type parameter node has a default and it is not identical to the default
65278                     // for the type parameter at this position, we report an error.
65279                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
65280                     var targetDefault = getDefaultFromTypeParameter(target);
65281                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
65282                         return false;
65283                     }
65284                 }
65285             }
65286             return true;
65287         }
65288         function checkClassExpression(node) {
65289             checkClassLikeDeclaration(node);
65290             checkNodeDeferred(node);
65291             return getTypeOfSymbol(getSymbolOfNode(node));
65292         }
65293         function checkClassExpressionDeferred(node) {
65294             ts.forEach(node.members, checkSourceElement);
65295             registerForUnusedIdentifiersCheck(node);
65296         }
65297         function checkClassDeclaration(node) {
65298             if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
65299                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
65300             }
65301             checkClassLikeDeclaration(node);
65302             ts.forEach(node.members, checkSourceElement);
65303             registerForUnusedIdentifiersCheck(node);
65304         }
65305         function checkClassLikeDeclaration(node) {
65306             checkGrammarClassLikeDeclaration(node);
65307             checkDecorators(node);
65308             if (node.name) {
65309                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
65310                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65311                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65312                 if (!(node.flags & 8388608 /* Ambient */)) {
65313                     checkClassNameCollisionWithObject(node.name);
65314                 }
65315             }
65316             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
65317             checkExportsOnMergedDeclarations(node);
65318             var symbol = getSymbolOfNode(node);
65319             var type = getDeclaredTypeOfSymbol(symbol);
65320             var typeWithThis = getTypeWithThisArgument(type);
65321             var staticType = getTypeOfSymbol(symbol);
65322             checkTypeParameterListsIdentical(symbol);
65323             checkClassForDuplicateDeclarations(node);
65324             // Only check for reserved static identifiers on non-ambient context.
65325             if (!(node.flags & 8388608 /* Ambient */)) {
65326                 checkClassForStaticPropertyNameConflicts(node);
65327             }
65328             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
65329             if (baseTypeNode) {
65330                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65331                 if (languageVersion < 2 /* ES2015 */) {
65332                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
65333                 }
65334                 // check both @extends and extends if both are specified.
65335                 var extendsNode = ts.getClassExtendsHeritageElement(node);
65336                 if (extendsNode && extendsNode !== baseTypeNode) {
65337                     checkExpression(extendsNode.expression);
65338                 }
65339                 var baseTypes = getBaseTypes(type);
65340                 if (baseTypes.length && produceDiagnostics) {
65341                     var baseType_1 = baseTypes[0];
65342                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
65343                     var staticBaseType = getApparentType(baseConstructorType);
65344                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
65345                     checkSourceElement(baseTypeNode.expression);
65346                     if (ts.some(baseTypeNode.typeArguments)) {
65347                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65348                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
65349                             var constructor = _a[_i];
65350                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
65351                                 break;
65352                             }
65353                         }
65354                     }
65355                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
65356                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65357                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
65358                     }
65359                     else {
65360                         // Report static side error only when instance type is assignable
65361                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
65362                     }
65363                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
65364                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
65365                     }
65366                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
65367                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
65368                         // that all instantiated base constructor signatures return the same type.
65369                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
65370                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
65371                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
65372                         }
65373                     }
65374                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
65375                 }
65376             }
65377             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
65378             if (implementedTypeNodes) {
65379                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
65380                     var typeRefNode = implementedTypeNodes_1[_b];
65381                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
65382                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
65383                     }
65384                     checkTypeReferenceNode(typeRefNode);
65385                     if (produceDiagnostics) {
65386                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
65387                         if (t !== errorType) {
65388                             if (isValidBaseType(t)) {
65389                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
65390                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
65391                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
65392                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
65393                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65394                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
65395                                 }
65396                             }
65397                             else {
65398                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
65399                             }
65400                         }
65401                     }
65402                 }
65403             }
65404             if (produceDiagnostics) {
65405                 checkIndexConstraints(type);
65406                 checkTypeForDuplicateIndexSignatures(node);
65407                 checkPropertyInitialization(node);
65408             }
65409         }
65410         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
65411             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
65412             var issuedMemberError = false;
65413             var _loop_19 = function (member) {
65414                 if (ts.hasStaticModifier(member)) {
65415                     return "continue";
65416                 }
65417                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
65418                 if (declaredProp) {
65419                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
65420                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
65421                     if (prop && baseProp) {
65422                         var rootChain = function () { return ts.chainDiagnosticMessages(
65423                         /*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)); };
65424                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
65425                             issuedMemberError = true;
65426                         }
65427                     }
65428                 }
65429             };
65430             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65431                 var member = _a[_i];
65432                 _loop_19(member);
65433             }
65434             if (!issuedMemberError) {
65435                 // check again with diagnostics to generate a less-specific error
65436                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
65437             }
65438         }
65439         function checkBaseTypeAccessibility(type, node) {
65440             var signatures = getSignaturesOfType(type, 1 /* Construct */);
65441             if (signatures.length) {
65442                 var declaration = signatures[0].declaration;
65443                 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
65444                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65445                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
65446                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
65447                     }
65448                 }
65449             }
65450         }
65451         function getTargetSymbol(s) {
65452             // if symbol is instantiated its flags are not copied from the 'target'
65453             // so we'll need to get back original 'target' symbol to work with correct set of flags
65454             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
65455         }
65456         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
65457             return ts.filter(symbol.declarations, function (d) {
65458                 return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
65459             });
65460         }
65461         function checkKindsOfPropertyMemberOverrides(type, baseType) {
65462             // TypeScript 1.0 spec (April 2014): 8.2.3
65463             // A derived class inherits all members from its base class it doesn't override.
65464             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
65465             // Both public and private property members are inherited, but only public property members can be overridden.
65466             // A property member in a derived class is said to override a property member in a base class
65467             // when the derived class property member has the same name and kind(instance or static)
65468             // as the base class property member.
65469             // The type of an overriding property member must be assignable(section 3.8.4)
65470             // to the type of the overridden property member, or otherwise a compile - time error occurs.
65471             // Base class instance member functions can be overridden by derived class instance member functions,
65472             // but not by other kinds of members.
65473             // Base class instance member variables and accessors can be overridden by
65474             // derived class instance member variables and accessors, but not by other kinds of members.
65475             // NOTE: assignability is checked in checkClassDeclaration
65476             var baseProperties = getPropertiesOfType(baseType);
65477             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
65478                 var baseProperty = baseProperties_1[_i];
65479                 var base = getTargetSymbol(baseProperty);
65480                 if (base.flags & 4194304 /* Prototype */) {
65481                     continue;
65482                 }
65483                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
65484                 if (!baseSymbol) {
65485                     continue;
65486                 }
65487                 var derived = getTargetSymbol(baseSymbol);
65488                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
65489                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
65490                 // In order to resolve whether the inherited method was overridden in the base class or not,
65491                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
65492                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
65493                 if (derived === base) {
65494                     // derived class inherits base without override/redeclaration
65495                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65496                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
65497                     // If there is no declaration for the derived class (as in the case of class expressions),
65498                     // then the class cannot be declared abstract.
65499                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
65500                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
65501                         // (The class may have more than one base type via declaration merging with an interface with the
65502                         // same name.)
65503                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
65504                             var otherBaseType = _b[_a];
65505                             if (otherBaseType === baseType)
65506                                 continue;
65507                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
65508                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
65509                             if (derivedElsewhere && derivedElsewhere !== base) {
65510                                 continue basePropertyCheck;
65511                             }
65512                         }
65513                         if (derivedClassDecl.kind === 214 /* ClassExpression */) {
65514                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
65515                         }
65516                         else {
65517                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
65518                         }
65519                     }
65520                 }
65521                 else {
65522                     // derived overrides base.
65523                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
65524                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
65525                         // either base or derived property is private - not override, skip it
65526                         continue;
65527                     }
65528                     var errorMessage = void 0;
65529                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
65530                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
65531                     if (basePropertyFlags && derivedPropertyFlags) {
65532                         // property/accessor is overridden with property/accessor
65533                         if (!compilerOptions.useDefineForClassFields
65534                             || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
65535                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
65536                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
65537                             // when the base property is abstract or from an interface, base/derived flags don't need to match
65538                             // same when the derived property is from an assignment
65539                             continue;
65540                         }
65541                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
65542                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
65543                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
65544                             var errorMessage_1 = overriddenInstanceProperty ?
65545                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
65546                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
65547                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
65548                         }
65549                         else {
65550                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
65551                             if (uninitialized
65552                                 && !(derived.flags & 33554432 /* Transient */)
65553                                 && !(baseDeclarationFlags & 128 /* Abstract */)
65554                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
65555                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
65556                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
65557                                 var propName = uninitialized.name;
65558                                 if (uninitialized.exclamationToken
65559                                     || !constructor
65560                                     || !ts.isIdentifier(propName)
65561                                     || !strictNullChecks
65562                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65563                                     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;
65564                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
65565                                 }
65566                             }
65567                         }
65568                         // correct case
65569                         continue;
65570                     }
65571                     else if (isPrototypeProperty(base)) {
65572                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
65573                             // method is overridden with method or property -- correct case
65574                             continue;
65575                         }
65576                         else {
65577                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
65578                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
65579                         }
65580                     }
65581                     else if (base.flags & 98304 /* Accessor */) {
65582                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
65583                     }
65584                     else {
65585                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
65586                     }
65587                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
65588                 }
65589             }
65590         }
65591         function getNonInterhitedProperties(type, baseTypes, properties) {
65592             if (!ts.length(baseTypes)) {
65593                 return properties;
65594             }
65595             var seen = ts.createUnderscoreEscapedMap();
65596             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
65597             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
65598                 var base = baseTypes_2[_i];
65599                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65600                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
65601                     var prop = properties_4[_a];
65602                     var existing = seen.get(prop.escapedName);
65603                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
65604                         seen.delete(prop.escapedName);
65605                     }
65606                 }
65607             }
65608             return ts.arrayFrom(seen.values());
65609         }
65610         function checkInheritedPropertiesAreIdentical(type, typeNode) {
65611             var baseTypes = getBaseTypes(type);
65612             if (baseTypes.length < 2) {
65613                 return true;
65614             }
65615             var seen = ts.createUnderscoreEscapedMap();
65616             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
65617             var ok = true;
65618             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
65619                 var base = baseTypes_3[_i];
65620                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65621                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
65622                     var prop = properties_6[_a];
65623                     var existing = seen.get(prop.escapedName);
65624                     if (!existing) {
65625                         seen.set(prop.escapedName, { prop: prop, containingType: base });
65626                     }
65627                     else {
65628                         var isInheritedProperty = existing.containingType !== type;
65629                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
65630                             ok = false;
65631                             var typeName1 = typeToString(existing.containingType);
65632                             var typeName2 = typeToString(base);
65633                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
65634                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
65635                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
65636                         }
65637                     }
65638                 }
65639             }
65640             return ok;
65641         }
65642         function checkPropertyInitialization(node) {
65643             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
65644                 return;
65645             }
65646             var constructor = findConstructorDeclaration(node);
65647             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65648                 var member = _a[_i];
65649                 if (ts.getModifierFlags(member) & 2 /* Ambient */) {
65650                     continue;
65651                 }
65652                 if (isInstancePropertyWithoutInitializer(member)) {
65653                     var propName = member.name;
65654                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
65655                         var type = getTypeOfSymbol(getSymbolOfNode(member));
65656                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
65657                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65658                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
65659                             }
65660                         }
65661                     }
65662                 }
65663             }
65664         }
65665         function isInstancePropertyWithoutInitializer(node) {
65666             return node.kind === 159 /* PropertyDeclaration */ &&
65667                 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
65668                 !node.exclamationToken &&
65669                 !node.initializer;
65670         }
65671         function isPropertyInitializedInConstructor(propName, propType, constructor) {
65672             var reference = ts.createPropertyAccess(ts.createThis(), propName);
65673             reference.expression.parent = reference;
65674             reference.parent = constructor;
65675             reference.flowNode = constructor.returnFlowNode;
65676             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
65677             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
65678         }
65679         function checkInterfaceDeclaration(node) {
65680             // Grammar checking
65681             if (!checkGrammarDecoratorsAndModifiers(node))
65682                 checkGrammarInterfaceDeclaration(node);
65683             checkTypeParameters(node.typeParameters);
65684             if (produceDiagnostics) {
65685                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
65686                 checkExportsOnMergedDeclarations(node);
65687                 var symbol = getSymbolOfNode(node);
65688                 checkTypeParameterListsIdentical(symbol);
65689                 // Only check this symbol once
65690                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
65691                 if (node === firstInterfaceDecl) {
65692                     var type = getDeclaredTypeOfSymbol(symbol);
65693                     var typeWithThis = getTypeWithThisArgument(type);
65694                     // run subsequent checks only if first set succeeded
65695                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
65696                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
65697                             var baseType = _a[_i];
65698                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
65699                         }
65700                         checkIndexConstraints(type);
65701                     }
65702                 }
65703                 checkObjectTypeForDuplicateDeclarations(node);
65704             }
65705             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
65706                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
65707                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
65708                 }
65709                 checkTypeReferenceNode(heritageElement);
65710             });
65711             ts.forEach(node.members, checkSourceElement);
65712             if (produceDiagnostics) {
65713                 checkTypeForDuplicateIndexSignatures(node);
65714                 registerForUnusedIdentifiersCheck(node);
65715             }
65716         }
65717         function checkTypeAliasDeclaration(node) {
65718             // Grammar checking
65719             checkGrammarDecoratorsAndModifiers(node);
65720             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
65721             checkExportsOnMergedDeclarations(node);
65722             checkTypeParameters(node.typeParameters);
65723             checkSourceElement(node.type);
65724             registerForUnusedIdentifiersCheck(node);
65725         }
65726         function computeEnumMemberValues(node) {
65727             var nodeLinks = getNodeLinks(node);
65728             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
65729                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
65730                 var autoValue = 0;
65731                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65732                     var member = _a[_i];
65733                     var value = computeMemberValue(member, autoValue);
65734                     getNodeLinks(member).enumMemberValue = value;
65735                     autoValue = typeof value === "number" ? value + 1 : undefined;
65736                 }
65737             }
65738         }
65739         function computeMemberValue(member, autoValue) {
65740             if (ts.isComputedNonLiteralName(member.name)) {
65741                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
65742             }
65743             else {
65744                 var text = ts.getTextOfPropertyName(member.name);
65745                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
65746                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
65747                 }
65748             }
65749             if (member.initializer) {
65750                 return computeConstantValue(member);
65751             }
65752             // In ambient non-const numeric enum declarations, enum members without initializers are
65753             // considered computed members (as opposed to having auto-incremented values).
65754             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
65755                 return undefined;
65756             }
65757             // If the member declaration specifies no value, the member is considered a constant enum member.
65758             // If the member is the first member in the enum declaration, it is assigned the value zero.
65759             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
65760             // occurs if the immediately preceding member is not a constant enum member.
65761             if (autoValue !== undefined) {
65762                 return autoValue;
65763             }
65764             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
65765             return undefined;
65766         }
65767         function computeConstantValue(member) {
65768             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
65769             var isConstEnum = ts.isEnumConst(member.parent);
65770             var initializer = member.initializer;
65771             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
65772             if (value !== undefined) {
65773                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
65774                     error(initializer, isNaN(value) ?
65775                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
65776                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
65777                 }
65778             }
65779             else if (enumKind === 1 /* Literal */) {
65780                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
65781                 return 0;
65782             }
65783             else if (isConstEnum) {
65784                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
65785             }
65786             else if (member.parent.flags & 8388608 /* Ambient */) {
65787                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
65788             }
65789             else {
65790                 // Only here do we need to check that the initializer is assignable to the enum type.
65791                 var source = checkExpression(initializer);
65792                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
65793                     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));
65794                 }
65795                 else {
65796                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
65797                 }
65798             }
65799             return value;
65800             function evaluate(expr) {
65801                 switch (expr.kind) {
65802                     case 207 /* PrefixUnaryExpression */:
65803                         var value_2 = evaluate(expr.operand);
65804                         if (typeof value_2 === "number") {
65805                             switch (expr.operator) {
65806                                 case 39 /* PlusToken */: return value_2;
65807                                 case 40 /* MinusToken */: return -value_2;
65808                                 case 54 /* TildeToken */: return ~value_2;
65809                             }
65810                         }
65811                         break;
65812                     case 209 /* BinaryExpression */:
65813                         var left = evaluate(expr.left);
65814                         var right = evaluate(expr.right);
65815                         if (typeof left === "number" && typeof right === "number") {
65816                             switch (expr.operatorToken.kind) {
65817                                 case 51 /* BarToken */: return left | right;
65818                                 case 50 /* AmpersandToken */: return left & right;
65819                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
65820                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
65821                                 case 47 /* LessThanLessThanToken */: return left << right;
65822                                 case 52 /* CaretToken */: return left ^ right;
65823                                 case 41 /* AsteriskToken */: return left * right;
65824                                 case 43 /* SlashToken */: return left / right;
65825                                 case 39 /* PlusToken */: return left + right;
65826                                 case 40 /* MinusToken */: return left - right;
65827                                 case 44 /* PercentToken */: return left % right;
65828                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
65829                             }
65830                         }
65831                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
65832                             return left + right;
65833                         }
65834                         break;
65835                     case 10 /* StringLiteral */:
65836                     case 14 /* NoSubstitutionTemplateLiteral */:
65837                         return expr.text;
65838                     case 8 /* NumericLiteral */:
65839                         checkGrammarNumericLiteral(expr);
65840                         return +expr.text;
65841                     case 200 /* ParenthesizedExpression */:
65842                         return evaluate(expr.expression);
65843                     case 75 /* Identifier */:
65844                         var identifier = expr;
65845                         if (isInfinityOrNaNString(identifier.escapedText)) {
65846                             return +(identifier.escapedText);
65847                         }
65848                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
65849                     case 195 /* ElementAccessExpression */:
65850                     case 194 /* PropertyAccessExpression */:
65851                         var ex = expr;
65852                         if (isConstantMemberAccess(ex)) {
65853                             var type = getTypeOfExpression(ex.expression);
65854                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
65855                                 var name = void 0;
65856                                 if (ex.kind === 194 /* PropertyAccessExpression */) {
65857                                     name = ex.name.escapedText;
65858                                 }
65859                                 else {
65860                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
65861                                 }
65862                                 return evaluateEnumMember(expr, type.symbol, name);
65863                             }
65864                         }
65865                         break;
65866                 }
65867                 return undefined;
65868             }
65869             function evaluateEnumMember(expr, enumSymbol, name) {
65870                 var memberSymbol = enumSymbol.exports.get(name);
65871                 if (memberSymbol) {
65872                     var declaration = memberSymbol.valueDeclaration;
65873                     if (declaration !== member) {
65874                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
65875                             return getEnumMemberValue(declaration);
65876                         }
65877                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
65878                         return 0;
65879                     }
65880                     else {
65881                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
65882                     }
65883                 }
65884                 return undefined;
65885             }
65886         }
65887         function isConstantMemberAccess(node) {
65888             return node.kind === 75 /* Identifier */ ||
65889                 node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
65890                 node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
65891                     ts.isStringLiteralLike(node.argumentExpression);
65892         }
65893         function checkEnumDeclaration(node) {
65894             if (!produceDiagnostics) {
65895                 return;
65896             }
65897             // Grammar checking
65898             checkGrammarDecoratorsAndModifiers(node);
65899             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
65900             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65901             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65902             checkExportsOnMergedDeclarations(node);
65903             node.members.forEach(checkEnumMember);
65904             computeEnumMemberValues(node);
65905             // Spec 2014 - Section 9.3:
65906             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
65907             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
65908             // for the first member.
65909             //
65910             // Only perform this check once per symbol
65911             var enumSymbol = getSymbolOfNode(node);
65912             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
65913             if (node === firstDeclaration) {
65914                 if (enumSymbol.declarations.length > 1) {
65915                     var enumIsConst_1 = ts.isEnumConst(node);
65916                     // check that const is placed\omitted on all enum declarations
65917                     ts.forEach(enumSymbol.declarations, function (decl) {
65918                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
65919                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
65920                         }
65921                     });
65922                 }
65923                 var seenEnumMissingInitialInitializer_1 = false;
65924                 ts.forEach(enumSymbol.declarations, function (declaration) {
65925                     // return true if we hit a violation of the rule, false otherwise
65926                     if (declaration.kind !== 248 /* EnumDeclaration */) {
65927                         return false;
65928                     }
65929                     var enumDeclaration = declaration;
65930                     if (!enumDeclaration.members.length) {
65931                         return false;
65932                     }
65933                     var firstEnumMember = enumDeclaration.members[0];
65934                     if (!firstEnumMember.initializer) {
65935                         if (seenEnumMissingInitialInitializer_1) {
65936                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
65937                         }
65938                         else {
65939                             seenEnumMissingInitialInitializer_1 = true;
65940                         }
65941                     }
65942                 });
65943             }
65944         }
65945         function checkEnumMember(node) {
65946             if (ts.isPrivateIdentifier(node.name)) {
65947                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
65948             }
65949         }
65950         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
65951             var declarations = symbol.declarations;
65952             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
65953                 var declaration = declarations_8[_i];
65954                 if ((declaration.kind === 245 /* ClassDeclaration */ ||
65955                     (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
65956                     !(declaration.flags & 8388608 /* Ambient */)) {
65957                     return declaration;
65958                 }
65959             }
65960             return undefined;
65961         }
65962         function inSameLexicalScope(node1, node2) {
65963             var container1 = ts.getEnclosingBlockScopeContainer(node1);
65964             var container2 = ts.getEnclosingBlockScopeContainer(node2);
65965             if (isGlobalSourceFile(container1)) {
65966                 return isGlobalSourceFile(container2);
65967             }
65968             else if (isGlobalSourceFile(container2)) {
65969                 return false;
65970             }
65971             else {
65972                 return container1 === container2;
65973             }
65974         }
65975         function checkModuleDeclaration(node) {
65976             if (produceDiagnostics) {
65977                 // Grammar checking
65978                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
65979                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
65980                 if (isGlobalAugmentation && !inAmbientContext) {
65981                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
65982                 }
65983                 var isAmbientExternalModule = ts.isAmbientModule(node);
65984                 var contextErrorMessage = isAmbientExternalModule
65985                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
65986                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
65987                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
65988                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
65989                     return;
65990                 }
65991                 if (!checkGrammarDecoratorsAndModifiers(node)) {
65992                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
65993                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
65994                     }
65995                 }
65996                 if (ts.isIdentifier(node.name)) {
65997                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65998                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65999                 }
66000                 checkExportsOnMergedDeclarations(node);
66001                 var symbol = getSymbolOfNode(node);
66002                 // The following checks only apply on a non-ambient instantiated module declaration.
66003                 if (symbol.flags & 512 /* ValueModule */
66004                     && !inAmbientContext
66005                     && symbol.declarations.length > 1
66006                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
66007                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
66008                     if (firstNonAmbientClassOrFunc) {
66009                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
66010                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
66011                         }
66012                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
66013                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
66014                         }
66015                     }
66016                     // if the module merges with a class declaration in the same lexical scope,
66017                     // we need to track this to ensure the correct emit.
66018                     var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
66019                     if (mergedClass &&
66020                         inSameLexicalScope(node, mergedClass)) {
66021                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
66022                     }
66023                 }
66024                 if (isAmbientExternalModule) {
66025                     if (ts.isExternalModuleAugmentation(node)) {
66026                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
66027                         // otherwise we'll be swamped in cascading errors.
66028                         // We can detect if augmentation was applied using following rules:
66029                         // - augmentation for a global scope is always applied
66030                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
66031                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
66032                         if (checkBody && node.body) {
66033                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
66034                                 var statement = _a[_i];
66035                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
66036                             }
66037                         }
66038                     }
66039                     else if (isGlobalSourceFile(node.parent)) {
66040                         if (isGlobalAugmentation) {
66041                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
66042                         }
66043                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
66044                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
66045                         }
66046                     }
66047                     else {
66048                         if (isGlobalAugmentation) {
66049                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
66050                         }
66051                         else {
66052                             // Node is not an augmentation and is not located on the script level.
66053                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
66054                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
66055                         }
66056                     }
66057                 }
66058             }
66059             if (node.body) {
66060                 checkSourceElement(node.body);
66061                 if (!ts.isGlobalScopeAugmentation(node)) {
66062                     registerForUnusedIdentifiersCheck(node);
66063                 }
66064             }
66065         }
66066         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
66067             switch (node.kind) {
66068                 case 225 /* VariableStatement */:
66069                     // error each individual name in variable statement instead of marking the entire variable statement
66070                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
66071                         var decl = _a[_i];
66072                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
66073                     }
66074                     break;
66075                 case 259 /* ExportAssignment */:
66076                 case 260 /* ExportDeclaration */:
66077                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
66078                     break;
66079                 case 253 /* ImportEqualsDeclaration */:
66080                 case 254 /* ImportDeclaration */:
66081                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
66082                     break;
66083                 case 191 /* BindingElement */:
66084                 case 242 /* VariableDeclaration */:
66085                     var name = node.name;
66086                     if (ts.isBindingPattern(name)) {
66087                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
66088                             var el = _c[_b];
66089                             // mark individual names in binding pattern
66090                             checkModuleAugmentationElement(el, isGlobalAugmentation);
66091                         }
66092                         break;
66093                     }
66094                 // falls through
66095                 case 245 /* ClassDeclaration */:
66096                 case 248 /* EnumDeclaration */:
66097                 case 244 /* FunctionDeclaration */:
66098                 case 246 /* InterfaceDeclaration */:
66099                 case 249 /* ModuleDeclaration */:
66100                 case 247 /* TypeAliasDeclaration */:
66101                     if (isGlobalAugmentation) {
66102                         return;
66103                     }
66104                     var symbol = getSymbolOfNode(node);
66105                     if (symbol) {
66106                         // module augmentations cannot introduce new names on the top level scope of the module
66107                         // this is done it two steps
66108                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
66109                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
66110                         var reportError = !(symbol.flags & 33554432 /* Transient */);
66111                         if (!reportError) {
66112                             // symbol should not originate in augmentation
66113                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
66114                         }
66115                     }
66116                     break;
66117             }
66118         }
66119         function getFirstNonModuleExportsIdentifier(node) {
66120             switch (node.kind) {
66121                 case 75 /* Identifier */:
66122                     return node;
66123                 case 153 /* QualifiedName */:
66124                     do {
66125                         node = node.left;
66126                     } while (node.kind !== 75 /* Identifier */);
66127                     return node;
66128                 case 194 /* PropertyAccessExpression */:
66129                     do {
66130                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
66131                             return node.name;
66132                         }
66133                         node = node.expression;
66134                     } while (node.kind !== 75 /* Identifier */);
66135                     return node;
66136             }
66137         }
66138         function checkExternalImportOrExportDeclaration(node) {
66139             var moduleName = ts.getExternalModuleName(node);
66140             if (!moduleName || ts.nodeIsMissing(moduleName)) {
66141                 // Should be a parse error.
66142                 return false;
66143             }
66144             if (!ts.isStringLiteral(moduleName)) {
66145                 error(moduleName, ts.Diagnostics.String_literal_expected);
66146                 return false;
66147             }
66148             var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66149             if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
66150                 error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
66151                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
66152                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
66153                 return false;
66154             }
66155             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
66156                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
66157                 // no need to do this again.
66158                 if (!isTopLevelInExternalModuleAugmentation(node)) {
66159                     // TypeScript 1.0 spec (April 2013): 12.1.6
66160                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
66161                     // other external modules only through top - level external module names.
66162                     // Relative external module names are not permitted.
66163                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
66164                     return false;
66165                 }
66166             }
66167             return true;
66168         }
66169         function checkAliasSymbol(node) {
66170             var symbol = getSymbolOfNode(node);
66171             var target = resolveAlias(symbol);
66172             var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
66173             if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
66174                 // For external modules symbol represents local symbol for an alias.
66175                 // This local symbol will merge any other local declarations (excluding other aliases)
66176                 // and symbol.flags will contains combined representation for all merged declaration.
66177                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
66178                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
66179                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
66180                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
66181                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
66182                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
66183                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
66184                 if (target.flags & excludedMeanings) {
66185                     var message = node.kind === 263 /* ExportSpecifier */ ?
66186                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
66187                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
66188                     error(node, message, symbolToString(symbol));
66189                 }
66190                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
66191                 if (compilerOptions.isolatedModules
66192                     && node.kind === 263 /* ExportSpecifier */
66193                     && !node.parent.parent.isTypeOnly
66194                     && !(target.flags & 111551 /* Value */)
66195                     && !(node.flags & 8388608 /* Ambient */)) {
66196                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
66197                 }
66198             }
66199         }
66200         function checkImportBinding(node) {
66201             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
66202             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
66203             checkAliasSymbol(node);
66204         }
66205         function checkImportDeclaration(node) {
66206             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66207                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66208                 return;
66209             }
66210             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66211                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
66212             }
66213             if (checkExternalImportOrExportDeclaration(node)) {
66214                 var importClause = node.importClause;
66215                 if (importClause && !checkGrammarImportClause(importClause)) {
66216                     if (importClause.name) {
66217                         checkImportBinding(importClause);
66218                     }
66219                     if (importClause.namedBindings) {
66220                         if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
66221                             checkImportBinding(importClause.namedBindings);
66222                         }
66223                         else {
66224                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
66225                             if (moduleExisted) {
66226                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
66227                             }
66228                         }
66229                     }
66230                 }
66231             }
66232         }
66233         function checkImportEqualsDeclaration(node) {
66234             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66235                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66236                 return;
66237             }
66238             checkGrammarDecoratorsAndModifiers(node);
66239             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
66240                 checkImportBinding(node);
66241                 if (ts.hasModifier(node, 1 /* Export */)) {
66242                     markExportAsReferenced(node);
66243                 }
66244                 if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
66245                     var target = resolveAlias(getSymbolOfNode(node));
66246                     if (target !== unknownSymbol) {
66247                         if (target.flags & 111551 /* Value */) {
66248                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
66249                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
66250                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
66251                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
66252                             }
66253                         }
66254                         if (target.flags & 788968 /* Type */) {
66255                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
66256                         }
66257                     }
66258                 }
66259                 else {
66260                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
66261                         // Import equals declaration is deprecated in es6 or above
66262                         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);
66263                     }
66264                 }
66265             }
66266         }
66267         function checkExportDeclaration(node) {
66268             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
66269                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
66270                 return;
66271             }
66272             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66273                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
66274             }
66275             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
66276                 checkExternalEmitHelpers(node, 1048576 /* CreateBinding */);
66277             }
66278             checkGrammarExportDeclaration(node);
66279             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
66280                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
66281                     // export { x, y }
66282                     // export { x, y } from "foo"
66283                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
66284                     var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66285                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
66286                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
66287                     if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
66288                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
66289                     }
66290                 }
66291                 else {
66292                     // export * from "foo"
66293                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
66294                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
66295                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
66296                     }
66297                     else if (node.exportClause) {
66298                         checkAliasSymbol(node.exportClause);
66299                     }
66300                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
66301                         checkExternalEmitHelpers(node, 65536 /* ExportStar */);
66302                     }
66303                 }
66304             }
66305         }
66306         function checkGrammarExportDeclaration(node) {
66307             var _a;
66308             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
66309             if (isTypeOnlyExportStar) {
66310                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
66311             }
66312             return !isTypeOnlyExportStar;
66313         }
66314         function checkGrammarModuleElementContext(node, errorMessage) {
66315             var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
66316             if (!isInAppropriateContext) {
66317                 grammarErrorOnFirstToken(node, errorMessage);
66318             }
66319             return !isInAppropriateContext;
66320         }
66321         function importClauseContainsReferencedImport(importClause) {
66322             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66323                 return !!getSymbolOfNode(declaration).isReferenced;
66324             });
66325         }
66326         function importClauseContainsConstEnumUsedAsValue(importClause) {
66327             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66328                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
66329             });
66330         }
66331         function checkImportsForTypeOnlyConversion(sourceFile) {
66332             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66333                 var statement = _a[_i];
66334                 if (ts.isImportDeclaration(statement) &&
66335                     statement.importClause &&
66336                     !statement.importClause.isTypeOnly &&
66337                     importClauseContainsReferencedImport(statement.importClause) &&
66338                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
66339                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
66340                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
66341                 }
66342             }
66343         }
66344         function checkExportSpecifier(node) {
66345             checkAliasSymbol(node);
66346             if (ts.getEmitDeclarations(compilerOptions)) {
66347                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
66348             }
66349             if (!node.parent.parent.moduleSpecifier) {
66350                 var exportedName = node.propertyName || node.name;
66351                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
66352                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
66353                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
66354                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
66355                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
66356                 }
66357                 else {
66358                     markExportAsReferenced(node);
66359                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
66360                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
66361                         checkExpressionCached(node.propertyName || node.name);
66362                     }
66363                 }
66364             }
66365         }
66366         function checkExportAssignment(node) {
66367             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
66368                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
66369                 return;
66370             }
66371             var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
66372             if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
66373                 if (node.isExportEquals) {
66374                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
66375                 }
66376                 else {
66377                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
66378                 }
66379                 return;
66380             }
66381             // Grammar checking
66382             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66383                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
66384             }
66385             if (node.expression.kind === 75 /* Identifier */) {
66386                 var id = node.expression;
66387                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
66388                 if (sym) {
66389                     markAliasReferenced(sym, id);
66390                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
66391                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
66392                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
66393                         // However if it is a value, we need to check it's being used correctly
66394                         checkExpressionCached(node.expression);
66395                     }
66396                 }
66397                 if (ts.getEmitDeclarations(compilerOptions)) {
66398                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
66399                 }
66400             }
66401             else {
66402                 checkExpressionCached(node.expression);
66403             }
66404             checkExternalModuleExports(container);
66405             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
66406                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
66407             }
66408             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
66409                 if (moduleKind >= ts.ModuleKind.ES2015) {
66410                     // export assignment is not supported in es6 modules
66411                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
66412                 }
66413                 else if (moduleKind === ts.ModuleKind.System) {
66414                     // system modules does not support export assignment
66415                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
66416                 }
66417             }
66418         }
66419         function hasExportedMembers(moduleSymbol) {
66420             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
66421         }
66422         function checkExternalModuleExports(node) {
66423             var moduleSymbol = getSymbolOfNode(node);
66424             var links = getSymbolLinks(moduleSymbol);
66425             if (!links.exportsChecked) {
66426                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
66427                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
66428                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
66429                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
66430                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
66431                     }
66432                 }
66433                 // Checks for export * conflicts
66434                 var exports_2 = getExportsOfModule(moduleSymbol);
66435                 if (exports_2) {
66436                     exports_2.forEach(function (_a, id) {
66437                         var declarations = _a.declarations, flags = _a.flags;
66438                         if (id === "__export") {
66439                             return;
66440                         }
66441                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
66442                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
66443                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
66444                             return;
66445                         }
66446                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
66447                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
66448                             // it is legal to merge type alias with other values
66449                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
66450                             return;
66451                         }
66452                         if (exportedDeclarationsCount > 1) {
66453                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
66454                                 var declaration = declarations_9[_i];
66455                                 if (isNotOverload(declaration)) {
66456                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
66457                                 }
66458                             }
66459                         }
66460                     });
66461                 }
66462                 links.exportsChecked = true;
66463             }
66464         }
66465         function checkSourceElement(node) {
66466             if (node) {
66467                 var saveCurrentNode = currentNode;
66468                 currentNode = node;
66469                 instantiationCount = 0;
66470                 checkSourceElementWorker(node);
66471                 currentNode = saveCurrentNode;
66472             }
66473         }
66474         function checkSourceElementWorker(node) {
66475             if (ts.isInJSFile(node)) {
66476                 ts.forEach(node.jsDoc, function (_a) {
66477                     var tags = _a.tags;
66478                     return ts.forEach(tags, checkSourceElement);
66479                 });
66480             }
66481             var kind = node.kind;
66482             if (cancellationToken) {
66483                 // Only bother checking on a few construct kinds.  We don't want to be excessively
66484                 // hitting the cancellation token on every node we check.
66485                 switch (kind) {
66486                     case 249 /* ModuleDeclaration */:
66487                     case 245 /* ClassDeclaration */:
66488                     case 246 /* InterfaceDeclaration */:
66489                     case 244 /* FunctionDeclaration */:
66490                         cancellationToken.throwIfCancellationRequested();
66491                 }
66492             }
66493             if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
66494                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
66495             }
66496             switch (kind) {
66497                 case 155 /* TypeParameter */:
66498                     return checkTypeParameter(node);
66499                 case 156 /* Parameter */:
66500                     return checkParameter(node);
66501                 case 159 /* PropertyDeclaration */:
66502                     return checkPropertyDeclaration(node);
66503                 case 158 /* PropertySignature */:
66504                     return checkPropertySignature(node);
66505                 case 170 /* FunctionType */:
66506                 case 171 /* ConstructorType */:
66507                 case 165 /* CallSignature */:
66508                 case 166 /* ConstructSignature */:
66509                 case 167 /* IndexSignature */:
66510                     return checkSignatureDeclaration(node);
66511                 case 161 /* MethodDeclaration */:
66512                 case 160 /* MethodSignature */:
66513                     return checkMethodDeclaration(node);
66514                 case 162 /* Constructor */:
66515                     return checkConstructorDeclaration(node);
66516                 case 163 /* GetAccessor */:
66517                 case 164 /* SetAccessor */:
66518                     return checkAccessorDeclaration(node);
66519                 case 169 /* TypeReference */:
66520                     return checkTypeReferenceNode(node);
66521                 case 168 /* TypePredicate */:
66522                     return checkTypePredicate(node);
66523                 case 172 /* TypeQuery */:
66524                     return checkTypeQuery(node);
66525                 case 173 /* TypeLiteral */:
66526                     return checkTypeLiteral(node);
66527                 case 174 /* ArrayType */:
66528                     return checkArrayType(node);
66529                 case 175 /* TupleType */:
66530                     return checkTupleType(node);
66531                 case 178 /* UnionType */:
66532                 case 179 /* IntersectionType */:
66533                     return checkUnionOrIntersectionType(node);
66534                 case 182 /* ParenthesizedType */:
66535                 case 176 /* OptionalType */:
66536                 case 177 /* RestType */:
66537                     return checkSourceElement(node.type);
66538                 case 183 /* ThisType */:
66539                     return checkThisType(node);
66540                 case 184 /* TypeOperator */:
66541                     return checkTypeOperator(node);
66542                 case 180 /* ConditionalType */:
66543                     return checkConditionalType(node);
66544                 case 181 /* InferType */:
66545                     return checkInferType(node);
66546                 case 188 /* ImportType */:
66547                     return checkImportType(node);
66548                 case 307 /* JSDocAugmentsTag */:
66549                     return checkJSDocAugmentsTag(node);
66550                 case 308 /* JSDocImplementsTag */:
66551                     return checkJSDocImplementsTag(node);
66552                 case 322 /* JSDocTypedefTag */:
66553                 case 315 /* JSDocCallbackTag */:
66554                 case 316 /* JSDocEnumTag */:
66555                     return checkJSDocTypeAliasTag(node);
66556                 case 321 /* JSDocTemplateTag */:
66557                     return checkJSDocTemplateTag(node);
66558                 case 320 /* JSDocTypeTag */:
66559                     return checkJSDocTypeTag(node);
66560                 case 317 /* JSDocParameterTag */:
66561                     return checkJSDocParameterTag(node);
66562                 case 323 /* JSDocPropertyTag */:
66563                     return checkJSDocPropertyTag(node);
66564                 case 300 /* JSDocFunctionType */:
66565                     checkJSDocFunctionType(node);
66566                 // falls through
66567                 case 298 /* JSDocNonNullableType */:
66568                 case 297 /* JSDocNullableType */:
66569                 case 295 /* JSDocAllType */:
66570                 case 296 /* JSDocUnknownType */:
66571                 case 304 /* JSDocTypeLiteral */:
66572                     checkJSDocTypeIsInJsFile(node);
66573                     ts.forEachChild(node, checkSourceElement);
66574                     return;
66575                 case 301 /* JSDocVariadicType */:
66576                     checkJSDocVariadicType(node);
66577                     return;
66578                 case 294 /* JSDocTypeExpression */:
66579                     return checkSourceElement(node.type);
66580                 case 185 /* IndexedAccessType */:
66581                     return checkIndexedAccessType(node);
66582                 case 186 /* MappedType */:
66583                     return checkMappedType(node);
66584                 case 244 /* FunctionDeclaration */:
66585                     return checkFunctionDeclaration(node);
66586                 case 223 /* Block */:
66587                 case 250 /* ModuleBlock */:
66588                     return checkBlock(node);
66589                 case 225 /* VariableStatement */:
66590                     return checkVariableStatement(node);
66591                 case 226 /* ExpressionStatement */:
66592                     return checkExpressionStatement(node);
66593                 case 227 /* IfStatement */:
66594                     return checkIfStatement(node);
66595                 case 228 /* DoStatement */:
66596                     return checkDoStatement(node);
66597                 case 229 /* WhileStatement */:
66598                     return checkWhileStatement(node);
66599                 case 230 /* ForStatement */:
66600                     return checkForStatement(node);
66601                 case 231 /* ForInStatement */:
66602                     return checkForInStatement(node);
66603                 case 232 /* ForOfStatement */:
66604                     return checkForOfStatement(node);
66605                 case 233 /* ContinueStatement */:
66606                 case 234 /* BreakStatement */:
66607                     return checkBreakOrContinueStatement(node);
66608                 case 235 /* ReturnStatement */:
66609                     return checkReturnStatement(node);
66610                 case 236 /* WithStatement */:
66611                     return checkWithStatement(node);
66612                 case 237 /* SwitchStatement */:
66613                     return checkSwitchStatement(node);
66614                 case 238 /* LabeledStatement */:
66615                     return checkLabeledStatement(node);
66616                 case 239 /* ThrowStatement */:
66617                     return checkThrowStatement(node);
66618                 case 240 /* TryStatement */:
66619                     return checkTryStatement(node);
66620                 case 242 /* VariableDeclaration */:
66621                     return checkVariableDeclaration(node);
66622                 case 191 /* BindingElement */:
66623                     return checkBindingElement(node);
66624                 case 245 /* ClassDeclaration */:
66625                     return checkClassDeclaration(node);
66626                 case 246 /* InterfaceDeclaration */:
66627                     return checkInterfaceDeclaration(node);
66628                 case 247 /* TypeAliasDeclaration */:
66629                     return checkTypeAliasDeclaration(node);
66630                 case 248 /* EnumDeclaration */:
66631                     return checkEnumDeclaration(node);
66632                 case 249 /* ModuleDeclaration */:
66633                     return checkModuleDeclaration(node);
66634                 case 254 /* ImportDeclaration */:
66635                     return checkImportDeclaration(node);
66636                 case 253 /* ImportEqualsDeclaration */:
66637                     return checkImportEqualsDeclaration(node);
66638                 case 260 /* ExportDeclaration */:
66639                     return checkExportDeclaration(node);
66640                 case 259 /* ExportAssignment */:
66641                     return checkExportAssignment(node);
66642                 case 224 /* EmptyStatement */:
66643                 case 241 /* DebuggerStatement */:
66644                     checkGrammarStatementInAmbientContext(node);
66645                     return;
66646                 case 264 /* MissingDeclaration */:
66647                     return checkMissingDeclaration(node);
66648             }
66649         }
66650         function checkJSDocTypeIsInJsFile(node) {
66651             if (!ts.isInJSFile(node)) {
66652                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
66653             }
66654         }
66655         function checkJSDocVariadicType(node) {
66656             checkJSDocTypeIsInJsFile(node);
66657             checkSourceElement(node.type);
66658             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
66659             var parent = node.parent;
66660             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66661                 if (ts.last(parent.parent.parameters) !== parent) {
66662                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66663                 }
66664                 return;
66665             }
66666             if (!ts.isJSDocTypeExpression(parent)) {
66667                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66668             }
66669             var paramTag = node.parent.parent;
66670             if (!ts.isJSDocParameterTag(paramTag)) {
66671                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66672                 return;
66673             }
66674             var param = ts.getParameterSymbolFromJSDoc(paramTag);
66675             if (!param) {
66676                 // We will error in `checkJSDocParameterTag`.
66677                 return;
66678             }
66679             var host = ts.getHostSignatureFromJSDoc(paramTag);
66680             if (!host || ts.last(host.parameters).symbol !== param) {
66681                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66682             }
66683         }
66684         function getTypeFromJSDocVariadicType(node) {
66685             var type = getTypeFromTypeNode(node.type);
66686             var parent = node.parent;
66687             var paramTag = node.parent.parent;
66688             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
66689                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
66690                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
66691                 if (host_1) {
66692                     /*
66693                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
66694                     So in the following situation we will not create an array type:
66695                         /** @param {...number} a * /
66696                         function f(a) {}
66697                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
66698                     */
66699                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
66700                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
66701                     if (!lastParamDeclaration ||
66702                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
66703                         return createArrayType(type);
66704                     }
66705                 }
66706             }
66707             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66708                 return createArrayType(type);
66709             }
66710             return addOptionality(type);
66711         }
66712         // Function and class expression bodies are checked after all statements in the enclosing body. This is
66713         // to ensure constructs like the following are permitted:
66714         //     const foo = function () {
66715         //        const s = foo();
66716         //        return "hello";
66717         //     }
66718         // Here, performing a full type check of the body of the function expression whilst in the process of
66719         // determining the type of foo would cause foo to be given type any because of the recursive reference.
66720         // Delaying the type check of the body ensures foo has been assigned a type.
66721         function checkNodeDeferred(node) {
66722             var enclosingFile = ts.getSourceFileOfNode(node);
66723             var links = getNodeLinks(enclosingFile);
66724             if (!(links.flags & 1 /* TypeChecked */)) {
66725                 links.deferredNodes = links.deferredNodes || ts.createMap();
66726                 var id = "" + getNodeId(node);
66727                 links.deferredNodes.set(id, node);
66728             }
66729         }
66730         function checkDeferredNodes(context) {
66731             var links = getNodeLinks(context);
66732             if (links.deferredNodes) {
66733                 links.deferredNodes.forEach(checkDeferredNode);
66734             }
66735         }
66736         function checkDeferredNode(node) {
66737             var saveCurrentNode = currentNode;
66738             currentNode = node;
66739             instantiationCount = 0;
66740             switch (node.kind) {
66741                 case 196 /* CallExpression */:
66742                 case 197 /* NewExpression */:
66743                 case 198 /* TaggedTemplateExpression */:
66744                 case 157 /* Decorator */:
66745                 case 268 /* JsxOpeningElement */:
66746                     // These node kinds are deferred checked when overload resolution fails
66747                     // To save on work, we ensure the arguments are checked just once, in
66748                     // a deferred way
66749                     resolveUntypedCall(node);
66750                     break;
66751                 case 201 /* FunctionExpression */:
66752                 case 202 /* ArrowFunction */:
66753                 case 161 /* MethodDeclaration */:
66754                 case 160 /* MethodSignature */:
66755                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
66756                     break;
66757                 case 163 /* GetAccessor */:
66758                 case 164 /* SetAccessor */:
66759                     checkAccessorDeclaration(node);
66760                     break;
66761                 case 214 /* ClassExpression */:
66762                     checkClassExpressionDeferred(node);
66763                     break;
66764                 case 267 /* JsxSelfClosingElement */:
66765                     checkJsxSelfClosingElementDeferred(node);
66766                     break;
66767                 case 266 /* JsxElement */:
66768                     checkJsxElementDeferred(node);
66769                     break;
66770             }
66771             currentNode = saveCurrentNode;
66772         }
66773         function checkSourceFile(node) {
66774             ts.performance.mark("beforeCheck");
66775             checkSourceFileWorker(node);
66776             ts.performance.mark("afterCheck");
66777             ts.performance.measure("Check", "beforeCheck", "afterCheck");
66778         }
66779         function unusedIsError(kind, isAmbient) {
66780             if (isAmbient) {
66781                 return false;
66782             }
66783             switch (kind) {
66784                 case 0 /* Local */:
66785                     return !!compilerOptions.noUnusedLocals;
66786                 case 1 /* Parameter */:
66787                     return !!compilerOptions.noUnusedParameters;
66788                 default:
66789                     return ts.Debug.assertNever(kind);
66790             }
66791         }
66792         function getPotentiallyUnusedIdentifiers(sourceFile) {
66793             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
66794         }
66795         // Fully type check a source file and collect the relevant diagnostics.
66796         function checkSourceFileWorker(node) {
66797             var links = getNodeLinks(node);
66798             if (!(links.flags & 1 /* TypeChecked */)) {
66799                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
66800                     return;
66801                 }
66802                 // Grammar checking
66803                 checkGrammarSourceFile(node);
66804                 ts.clear(potentialThisCollisions);
66805                 ts.clear(potentialNewTargetCollisions);
66806                 ts.clear(potentialWeakMapCollisions);
66807                 ts.forEach(node.statements, checkSourceElement);
66808                 checkSourceElement(node.endOfFileToken);
66809                 checkDeferredNodes(node);
66810                 if (ts.isExternalOrCommonJsModule(node)) {
66811                     registerForUnusedIdentifiersCheck(node);
66812                 }
66813                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
66814                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
66815                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
66816                             diagnostics.add(diag);
66817                         }
66818                     });
66819                 }
66820                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
66821                     !node.isDeclarationFile &&
66822                     ts.isExternalModule(node)) {
66823                     checkImportsForTypeOnlyConversion(node);
66824                 }
66825                 if (ts.isExternalOrCommonJsModule(node)) {
66826                     checkExternalModuleExports(node);
66827                 }
66828                 if (potentialThisCollisions.length) {
66829                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
66830                     ts.clear(potentialThisCollisions);
66831                 }
66832                 if (potentialNewTargetCollisions.length) {
66833                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
66834                     ts.clear(potentialNewTargetCollisions);
66835                 }
66836                 if (potentialWeakMapCollisions.length) {
66837                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
66838                     ts.clear(potentialWeakMapCollisions);
66839                 }
66840                 links.flags |= 1 /* TypeChecked */;
66841             }
66842         }
66843         function getDiagnostics(sourceFile, ct) {
66844             try {
66845                 // Record the cancellation token so it can be checked later on during checkSourceElement.
66846                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
66847                 // this call is done.
66848                 cancellationToken = ct;
66849                 return getDiagnosticsWorker(sourceFile);
66850             }
66851             finally {
66852                 cancellationToken = undefined;
66853             }
66854         }
66855         function getDiagnosticsWorker(sourceFile) {
66856             throwIfNonDiagnosticsProducing();
66857             if (sourceFile) {
66858                 // Some global diagnostics are deferred until they are needed and
66859                 // may not be reported in the first call to getGlobalDiagnostics.
66860                 // We should catch these changes and report them.
66861                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66862                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
66863                 checkSourceFile(sourceFile);
66864                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
66865                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66866                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
66867                     // If the arrays are not the same reference, new diagnostics were added.
66868                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
66869                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
66870                 }
66871                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
66872                     // If the arrays are the same reference, but the length has changed, a single
66873                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
66874                     // same array.
66875                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
66876                 }
66877                 return semanticDiagnostics;
66878             }
66879             // Global diagnostics are always added when a file is not provided to
66880             // getDiagnostics
66881             ts.forEach(host.getSourceFiles(), checkSourceFile);
66882             return diagnostics.getDiagnostics();
66883         }
66884         function getGlobalDiagnostics() {
66885             throwIfNonDiagnosticsProducing();
66886             return diagnostics.getGlobalDiagnostics();
66887         }
66888         function throwIfNonDiagnosticsProducing() {
66889             if (!produceDiagnostics) {
66890                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
66891             }
66892         }
66893         // Language service support
66894         function getSymbolsInScope(location, meaning) {
66895             if (location.flags & 16777216 /* InWithStatement */) {
66896                 // We cannot answer semantic questions within a with block, do not proceed any further
66897                 return [];
66898             }
66899             var symbols = ts.createSymbolTable();
66900             var isStatic = false;
66901             populateSymbols();
66902             symbols.delete("this" /* This */); // Not a symbol, a keyword
66903             return symbolsToArray(symbols);
66904             function populateSymbols() {
66905                 while (location) {
66906                     if (location.locals && !isGlobalSourceFile(location)) {
66907                         copySymbols(location.locals, meaning);
66908                     }
66909                     switch (location.kind) {
66910                         case 290 /* SourceFile */:
66911                             if (!ts.isExternalOrCommonJsModule(location))
66912                                 break;
66913                         // falls through
66914                         case 249 /* ModuleDeclaration */:
66915                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
66916                             break;
66917                         case 248 /* EnumDeclaration */:
66918                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
66919                             break;
66920                         case 214 /* ClassExpression */:
66921                             var className = location.name;
66922                             if (className) {
66923                                 copySymbol(location.symbol, meaning);
66924                             }
66925                         // this fall-through is necessary because we would like to handle
66926                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
66927                         // falls through
66928                         case 245 /* ClassDeclaration */:
66929                         case 246 /* InterfaceDeclaration */:
66930                             // If we didn't come from static member of class or interface,
66931                             // add the type parameters into the symbol table
66932                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
66933                             // Note: that the memberFlags come from previous iteration.
66934                             if (!isStatic) {
66935                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
66936                             }
66937                             break;
66938                         case 201 /* FunctionExpression */:
66939                             var funcName = location.name;
66940                             if (funcName) {
66941                                 copySymbol(location.symbol, meaning);
66942                             }
66943                             break;
66944                     }
66945                     if (ts.introducesArgumentsExoticObject(location)) {
66946                         copySymbol(argumentsSymbol, meaning);
66947                     }
66948                     isStatic = ts.hasModifier(location, 32 /* Static */);
66949                     location = location.parent;
66950                 }
66951                 copySymbols(globals, meaning);
66952             }
66953             /**
66954              * Copy the given symbol into symbol tables if the symbol has the given meaning
66955              * and it doesn't already existed in the symbol table
66956              * @param key a key for storing in symbol table; if undefined, use symbol.name
66957              * @param symbol the symbol to be added into symbol table
66958              * @param meaning meaning of symbol to filter by before adding to symbol table
66959              */
66960             function copySymbol(symbol, meaning) {
66961                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
66962                     var id = symbol.escapedName;
66963                     // We will copy all symbol regardless of its reserved name because
66964                     // symbolsToArray will check whether the key is a reserved name and
66965                     // it will not copy symbol with reserved name to the array
66966                     if (!symbols.has(id)) {
66967                         symbols.set(id, symbol);
66968                     }
66969                 }
66970             }
66971             function copySymbols(source, meaning) {
66972                 if (meaning) {
66973                     source.forEach(function (symbol) {
66974                         copySymbol(symbol, meaning);
66975                     });
66976                 }
66977             }
66978         }
66979         function isTypeDeclarationName(name) {
66980             return name.kind === 75 /* Identifier */ &&
66981                 isTypeDeclaration(name.parent) &&
66982                 name.parent.name === name;
66983         }
66984         function isTypeDeclaration(node) {
66985             switch (node.kind) {
66986                 case 155 /* TypeParameter */:
66987                 case 245 /* ClassDeclaration */:
66988                 case 246 /* InterfaceDeclaration */:
66989                 case 247 /* TypeAliasDeclaration */:
66990                 case 248 /* EnumDeclaration */:
66991                     return true;
66992                 case 255 /* ImportClause */:
66993                     return node.isTypeOnly;
66994                 case 258 /* ImportSpecifier */:
66995                 case 263 /* ExportSpecifier */:
66996                     return node.parent.parent.isTypeOnly;
66997                 default:
66998                     return false;
66999             }
67000         }
67001         // True if the given identifier is part of a type reference
67002         function isTypeReferenceIdentifier(node) {
67003             while (node.parent.kind === 153 /* QualifiedName */) {
67004                 node = node.parent;
67005             }
67006             return node.parent.kind === 169 /* TypeReference */;
67007         }
67008         function isHeritageClauseElementIdentifier(node) {
67009             while (node.parent.kind === 194 /* PropertyAccessExpression */) {
67010                 node = node.parent;
67011             }
67012             return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
67013         }
67014         function forEachEnclosingClass(node, callback) {
67015             var result;
67016             while (true) {
67017                 node = ts.getContainingClass(node);
67018                 if (!node)
67019                     break;
67020                 if (result = callback(node))
67021                     break;
67022             }
67023             return result;
67024         }
67025         function isNodeUsedDuringClassInitialization(node) {
67026             return !!ts.findAncestor(node, function (element) {
67027                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
67028                     return true;
67029                 }
67030                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
67031                     return "quit";
67032                 }
67033                 return false;
67034             });
67035         }
67036         function isNodeWithinClass(node, classDeclaration) {
67037             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
67038         }
67039         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
67040             while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
67041                 nodeOnRightSide = nodeOnRightSide.parent;
67042             }
67043             if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
67044                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
67045             }
67046             if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
67047                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
67048             }
67049             return undefined;
67050         }
67051         function isInRightSideOfImportOrExportAssignment(node) {
67052             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
67053         }
67054         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
67055             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
67056             switch (specialPropertyAssignmentKind) {
67057                 case 1 /* ExportsProperty */:
67058                 case 3 /* PrototypeProperty */:
67059                     return getSymbolOfNode(entityName.parent);
67060                 case 4 /* ThisProperty */:
67061                 case 2 /* ModuleExports */:
67062                 case 5 /* Property */:
67063                     return getSymbolOfNode(entityName.parent.parent);
67064             }
67065         }
67066         function isImportTypeQualifierPart(node) {
67067             var parent = node.parent;
67068             while (ts.isQualifiedName(parent)) {
67069                 node = parent;
67070                 parent = parent.parent;
67071             }
67072             if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
67073                 return parent;
67074             }
67075             return undefined;
67076         }
67077         function getSymbolOfNameOrPropertyAccessExpression(name) {
67078             if (ts.isDeclarationName(name)) {
67079                 return getSymbolOfNode(name.parent);
67080             }
67081             if (ts.isInJSFile(name) &&
67082                 name.parent.kind === 194 /* PropertyAccessExpression */ &&
67083                 name.parent === name.parent.parent.left) {
67084                 // Check if this is a special property assignment
67085                 if (!ts.isPrivateIdentifier(name)) {
67086                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
67087                     if (specialPropertyAssignmentSymbol) {
67088                         return specialPropertyAssignmentSymbol;
67089                     }
67090                 }
67091             }
67092             if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
67093                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
67094                 var success = resolveEntityName(name, 
67095                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
67096                 if (success && success !== unknownSymbol) {
67097                     return success;
67098                 }
67099             }
67100             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
67101                 // Since we already checked for ExportAssignment, this really could only be an Import
67102                 var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
67103                 ts.Debug.assert(importEqualsDeclaration !== undefined);
67104                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
67105             }
67106             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
67107                 var possibleImportNode = isImportTypeQualifierPart(name);
67108                 if (possibleImportNode) {
67109                     getTypeFromTypeNode(possibleImportNode);
67110                     var sym = getNodeLinks(name).resolvedSymbol;
67111                     return sym === unknownSymbol ? undefined : sym;
67112                 }
67113             }
67114             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
67115                 name = name.parent;
67116             }
67117             if (isHeritageClauseElementIdentifier(name)) {
67118                 var meaning = 0 /* None */;
67119                 // In an interface or class, we're definitely interested in a type.
67120                 if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
67121                     meaning = 788968 /* Type */;
67122                     // In a class 'extends' clause we are also looking for a value.
67123                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
67124                         meaning |= 111551 /* Value */;
67125                     }
67126                 }
67127                 else {
67128                     meaning = 1920 /* Namespace */;
67129                 }
67130                 meaning |= 2097152 /* Alias */;
67131                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
67132                 if (entityNameSymbol) {
67133                     return entityNameSymbol;
67134                 }
67135             }
67136             if (name.parent.kind === 317 /* JSDocParameterTag */) {
67137                 return ts.getParameterSymbolFromJSDoc(name.parent);
67138             }
67139             if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) {
67140                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
67141                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
67142                 return typeParameter && typeParameter.symbol;
67143             }
67144             if (ts.isExpressionNode(name)) {
67145                 if (ts.nodeIsMissing(name)) {
67146                     // Missing entity name.
67147                     return undefined;
67148                 }
67149                 if (name.kind === 75 /* Identifier */) {
67150                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
67151                         var symbol = getIntrinsicTagSymbol(name.parent);
67152                         return symbol === unknownSymbol ? undefined : symbol;
67153                     }
67154                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67155                 }
67156                 else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
67157                     var links = getNodeLinks(name);
67158                     if (links.resolvedSymbol) {
67159                         return links.resolvedSymbol;
67160                     }
67161                     if (name.kind === 194 /* PropertyAccessExpression */) {
67162                         checkPropertyAccessExpression(name);
67163                     }
67164                     else {
67165                         checkQualifiedName(name);
67166                     }
67167                     return links.resolvedSymbol;
67168                 }
67169             }
67170             else if (isTypeReferenceIdentifier(name)) {
67171                 var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
67172                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67173             }
67174             if (name.parent.kind === 168 /* TypePredicate */) {
67175                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
67176             }
67177             // Do we want to return undefined here?
67178             return undefined;
67179         }
67180         function getSymbolAtLocation(node, ignoreErrors) {
67181             if (node.kind === 290 /* SourceFile */) {
67182                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
67183             }
67184             var parent = node.parent;
67185             var grandParent = parent.parent;
67186             if (node.flags & 16777216 /* InWithStatement */) {
67187                 // We cannot answer semantic questions within a with block, do not proceed any further
67188                 return undefined;
67189             }
67190             if (isDeclarationNameOrImportPropertyName(node)) {
67191                 // This is a declaration, call getSymbolOfNode
67192                 var parentSymbol = getSymbolOfNode(parent);
67193                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
67194                     ? getImmediateAliasedSymbol(parentSymbol)
67195                     : parentSymbol;
67196             }
67197             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
67198                 return getSymbolOfNode(parent.parent);
67199             }
67200             if (node.kind === 75 /* Identifier */) {
67201                 if (isInRightSideOfImportOrExportAssignment(node)) {
67202                     return getSymbolOfNameOrPropertyAccessExpression(node);
67203                 }
67204                 else if (parent.kind === 191 /* BindingElement */ &&
67205                     grandParent.kind === 189 /* ObjectBindingPattern */ &&
67206                     node === parent.propertyName) {
67207                     var typeOfPattern = getTypeOfNode(grandParent);
67208                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
67209                     if (propertyDeclaration) {
67210                         return propertyDeclaration;
67211                     }
67212                 }
67213             }
67214             switch (node.kind) {
67215                 case 75 /* Identifier */:
67216                 case 76 /* PrivateIdentifier */:
67217                 case 194 /* PropertyAccessExpression */:
67218                 case 153 /* QualifiedName */:
67219                     return getSymbolOfNameOrPropertyAccessExpression(node);
67220                 case 104 /* ThisKeyword */:
67221                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
67222                     if (ts.isFunctionLike(container)) {
67223                         var sig = getSignatureFromDeclaration(container);
67224                         if (sig.thisParameter) {
67225                             return sig.thisParameter;
67226                         }
67227                     }
67228                     if (ts.isInExpressionContext(node)) {
67229                         return checkExpression(node).symbol;
67230                     }
67231                 // falls through
67232                 case 183 /* ThisType */:
67233                     return getTypeFromThisTypeNode(node).symbol;
67234                 case 102 /* SuperKeyword */:
67235                     return checkExpression(node).symbol;
67236                 case 129 /* ConstructorKeyword */:
67237                     // constructor keyword for an overload, should take us to the definition if it exist
67238                     var constructorDeclaration = node.parent;
67239                     if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
67240                         return constructorDeclaration.parent.symbol;
67241                     }
67242                     return undefined;
67243                 case 10 /* StringLiteral */:
67244                 case 14 /* NoSubstitutionTemplateLiteral */:
67245                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
67246                     // 2). External module name in an import declaration
67247                     // 3). Dynamic import call or require in javascript
67248                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
67249                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
67250                         ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
67251                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
67252                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
67253                         return resolveExternalModuleName(node, node, ignoreErrors);
67254                     }
67255                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
67256                         return getSymbolOfNode(parent);
67257                     }
67258                 // falls through
67259                 case 8 /* NumericLiteral */:
67260                     // index access
67261                     var objectType = ts.isElementAccessExpression(parent)
67262                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
67263                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
67264                             ? getTypeFromTypeNode(grandParent.objectType)
67265                             : undefined;
67266                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
67267                 case 84 /* DefaultKeyword */:
67268                 case 94 /* FunctionKeyword */:
67269                 case 38 /* EqualsGreaterThanToken */:
67270                 case 80 /* ClassKeyword */:
67271                     return getSymbolOfNode(node.parent);
67272                 case 188 /* ImportType */:
67273                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
67274                 case 89 /* ExportKeyword */:
67275                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
67276                 default:
67277                     return undefined;
67278             }
67279         }
67280         function getShorthandAssignmentValueSymbol(location) {
67281             if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
67282                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
67283             }
67284             return undefined;
67285         }
67286         /** Returns the target of an export specifier without following aliases */
67287         function getExportSpecifierLocalTargetSymbol(node) {
67288             return node.parent.parent.moduleSpecifier ?
67289                 getExternalModuleMember(node.parent.parent, node) :
67290                 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
67291         }
67292         function getTypeOfNode(node) {
67293             if (node.flags & 16777216 /* InWithStatement */) {
67294                 // We cannot answer semantic questions within a with block, do not proceed any further
67295                 return errorType;
67296             }
67297             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
67298             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
67299             if (ts.isPartOfTypeNode(node)) {
67300                 var typeFromTypeNode = getTypeFromTypeNode(node);
67301                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
67302             }
67303             if (ts.isExpressionNode(node)) {
67304                 return getRegularTypeOfExpression(node);
67305             }
67306             if (classType && !classDecl.isImplements) {
67307                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
67308                 // extends clause of a class. We handle that case here.
67309                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
67310                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
67311             }
67312             if (isTypeDeclaration(node)) {
67313                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67314                 var symbol = getSymbolOfNode(node);
67315                 return getDeclaredTypeOfSymbol(symbol);
67316             }
67317             if (isTypeDeclarationName(node)) {
67318                 var symbol = getSymbolAtLocation(node);
67319                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
67320             }
67321             if (ts.isDeclaration(node)) {
67322                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67323                 var symbol = getSymbolOfNode(node);
67324                 return getTypeOfSymbol(symbol);
67325             }
67326             if (isDeclarationNameOrImportPropertyName(node)) {
67327                 var symbol = getSymbolAtLocation(node);
67328                 if (symbol) {
67329                     return getTypeOfSymbol(symbol);
67330                 }
67331                 return errorType;
67332             }
67333             if (ts.isBindingPattern(node)) {
67334                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
67335             }
67336             if (isInRightSideOfImportOrExportAssignment(node)) {
67337                 var symbol = getSymbolAtLocation(node);
67338                 if (symbol) {
67339                     var declaredType = getDeclaredTypeOfSymbol(symbol);
67340                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
67341                 }
67342             }
67343             return errorType;
67344         }
67345         // Gets the type of object literal or array literal of destructuring assignment.
67346         // { a } from
67347         //     for ( { a } of elems) {
67348         //     }
67349         // [ a ] from
67350         //     [a] = [ some array ...]
67351         function getTypeOfAssignmentPattern(expr) {
67352             ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
67353             // If this is from "for of"
67354             //     for ( { a } of elems) {
67355             //     }
67356             if (expr.parent.kind === 232 /* ForOfStatement */) {
67357                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
67358                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67359             }
67360             // If this is from "for" initializer
67361             //     for ({a } = elems[0];.....) { }
67362             if (expr.parent.kind === 209 /* BinaryExpression */) {
67363                 var iteratedType = getTypeOfExpression(expr.parent.right);
67364                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67365             }
67366             // If this is from nested object binding pattern
67367             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
67368             if (expr.parent.kind === 281 /* PropertyAssignment */) {
67369                 var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
67370                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
67371                 var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
67372                 return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
67373             }
67374             // Array literal assignment - array destructuring pattern
67375             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
67376             //    [{ property1: p1, property2 }] = elems;
67377             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
67378             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
67379             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
67380         }
67381         // Gets the property symbol corresponding to the property in destructuring assignment
67382         // 'property1' from
67383         //     for ( { property1: a } of elems) {
67384         //     }
67385         // 'property1' at location 'a' from:
67386         //     [a] = [ property1, property2 ]
67387         function getPropertySymbolOfDestructuringAssignment(location) {
67388             // Get the type of the object or array literal and then look for property of given name in the type
67389             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
67390             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
67391         }
67392         function getRegularTypeOfExpression(expr) {
67393             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
67394                 expr = expr.parent;
67395             }
67396             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
67397         }
67398         /**
67399          * Gets either the static or instance type of a class element, based on
67400          * whether the element is declared as "static".
67401          */
67402         function getParentTypeOfClassElement(node) {
67403             var classSymbol = getSymbolOfNode(node.parent);
67404             return ts.hasModifier(node, 32 /* Static */)
67405                 ? getTypeOfSymbol(classSymbol)
67406                 : getDeclaredTypeOfSymbol(classSymbol);
67407         }
67408         function getClassElementPropertyKeyType(element) {
67409             var name = element.name;
67410             switch (name.kind) {
67411                 case 75 /* Identifier */:
67412                     return getLiteralType(ts.idText(name));
67413                 case 8 /* NumericLiteral */:
67414                 case 10 /* StringLiteral */:
67415                     return getLiteralType(name.text);
67416                 case 154 /* ComputedPropertyName */:
67417                     var nameType = checkComputedPropertyName(name);
67418                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
67419                 default:
67420                     return ts.Debug.fail("Unsupported property name.");
67421             }
67422         }
67423         // Return the list of properties of the given type, augmented with properties from Function
67424         // if the type has call or construct signatures
67425         function getAugmentedPropertiesOfType(type) {
67426             type = getApparentType(type);
67427             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
67428             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
67429                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
67430                     undefined;
67431             if (functionType) {
67432                 ts.forEach(getPropertiesOfType(functionType), function (p) {
67433                     if (!propsByName.has(p.escapedName)) {
67434                         propsByName.set(p.escapedName, p);
67435                     }
67436                 });
67437             }
67438             return getNamedMembers(propsByName);
67439         }
67440         function typeHasCallOrConstructSignatures(type) {
67441             return ts.typeHasCallOrConstructSignatures(type, checker);
67442         }
67443         function getRootSymbols(symbol) {
67444             var roots = getImmediateRootSymbols(symbol);
67445             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
67446         }
67447         function getImmediateRootSymbols(symbol) {
67448             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
67449                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
67450             }
67451             else if (symbol.flags & 33554432 /* Transient */) {
67452                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
67453                 return leftSpread ? [leftSpread, rightSpread]
67454                     : syntheticOrigin ? [syntheticOrigin]
67455                         : ts.singleElementArray(tryGetAliasTarget(symbol));
67456             }
67457             return undefined;
67458         }
67459         function tryGetAliasTarget(symbol) {
67460             var target;
67461             var next = symbol;
67462             while (next = getSymbolLinks(next).target) {
67463                 target = next;
67464             }
67465             return target;
67466         }
67467         // Emitter support
67468         function isArgumentsLocalBinding(nodeIn) {
67469             if (!ts.isGeneratedIdentifier(nodeIn)) {
67470                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67471                 if (node) {
67472                     var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
67473                     return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
67474                 }
67475             }
67476             return false;
67477         }
67478         function moduleExportsSomeValue(moduleReferenceExpression) {
67479             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
67480             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
67481                 // If the module is not found or is shorthand, assume that it may export a value.
67482                 return true;
67483             }
67484             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
67485             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
67486             // otherwise it will return moduleSymbol itself
67487             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
67488             var symbolLinks = getSymbolLinks(moduleSymbol);
67489             if (symbolLinks.exportsSomeValue === undefined) {
67490                 // for export assignments - check if resolved symbol for RHS is itself a value
67491                 // otherwise - check if at least one export is value
67492                 symbolLinks.exportsSomeValue = hasExportAssignment
67493                     ? !!(moduleSymbol.flags & 111551 /* Value */)
67494                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
67495             }
67496             return symbolLinks.exportsSomeValue;
67497             function isValue(s) {
67498                 s = resolveSymbol(s);
67499                 return s && !!(s.flags & 111551 /* Value */);
67500             }
67501         }
67502         function isNameOfModuleOrEnumDeclaration(node) {
67503             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
67504         }
67505         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
67506         // node of the exported entity's container. Otherwise, return undefined.
67507         function getReferencedExportContainer(nodeIn, prefixLocals) {
67508             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67509             if (node) {
67510                 // When resolving the export container for the name of a module or enum
67511                 // declaration, we need to start resolution at the declaration's container.
67512                 // Otherwise, we could incorrectly resolve the export container as the
67513                 // declaration if it contains an exported member with the same name.
67514                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
67515                 if (symbol) {
67516                     if (symbol.flags & 1048576 /* ExportValue */) {
67517                         // If we reference an exported entity within the same module declaration, then whether
67518                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
67519                         // kinds that we do NOT prefix.
67520                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
67521                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
67522                             return undefined;
67523                         }
67524                         symbol = exportSymbol;
67525                     }
67526                     var parentSymbol_1 = getParentOfSymbol(symbol);
67527                     if (parentSymbol_1) {
67528                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
67529                             var symbolFile = parentSymbol_1.valueDeclaration;
67530                             var referenceFile = ts.getSourceFileOfNode(node);
67531                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
67532                             var symbolIsUmdExport = symbolFile !== referenceFile;
67533                             return symbolIsUmdExport ? undefined : symbolFile;
67534                         }
67535                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
67536                     }
67537                 }
67538             }
67539         }
67540         // When resolved as an expression identifier, if the given node references an import, return the declaration of
67541         // that import. Otherwise, return undefined.
67542         function getReferencedImportDeclaration(nodeIn) {
67543             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67544             if (node) {
67545                 var symbol = getReferencedValueSymbol(node);
67546                 // We should only get the declaration of an alias if there isn't a local value
67547                 // declaration for the symbol
67548                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
67549                     return getDeclarationOfAliasSymbol(symbol);
67550                 }
67551             }
67552             return undefined;
67553         }
67554         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
67555             return ts.isBindingElement(symbol.valueDeclaration)
67556                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
67557         }
67558         function isSymbolOfDeclarationWithCollidingName(symbol) {
67559             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
67560                 var links = getSymbolLinks(symbol);
67561                 if (links.isDeclarationWithCollidingName === undefined) {
67562                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
67563                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
67564                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
67565                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
67566                             // redeclaration - always should be renamed
67567                             links.isDeclarationWithCollidingName = true;
67568                         }
67569                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
67570                             // binding is captured in the function
67571                             // should be renamed if:
67572                             // - binding is not top level - top level bindings never collide with anything
67573                             // AND
67574                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
67575                             //     let a, b
67576                             //     { let x = 1; a = () => x; }
67577                             //     { let x = 100; b = () => x; }
67578                             //     console.log(a()); // should print '1'
67579                             //     console.log(b()); // should print '100'
67580                             //     OR
67581                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
67582                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
67583                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
67584                             //       they will not collide with anything
67585                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
67586                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
67587                             var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
67588                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
67589                         }
67590                         else {
67591                             links.isDeclarationWithCollidingName = false;
67592                         }
67593                     }
67594                 }
67595                 return links.isDeclarationWithCollidingName;
67596             }
67597             return false;
67598         }
67599         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
67600         // a name that either hides an existing name or might hide it when compiled downlevel,
67601         // return the declaration of that entity. Otherwise, return undefined.
67602         function getReferencedDeclarationWithCollidingName(nodeIn) {
67603             if (!ts.isGeneratedIdentifier(nodeIn)) {
67604                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67605                 if (node) {
67606                     var symbol = getReferencedValueSymbol(node);
67607                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
67608                         return symbol.valueDeclaration;
67609                     }
67610                 }
67611             }
67612             return undefined;
67613         }
67614         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
67615         // existing name or might hide a name when compiled downlevel
67616         function isDeclarationWithCollidingName(nodeIn) {
67617             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67618             if (node) {
67619                 var symbol = getSymbolOfNode(node);
67620                 if (symbol) {
67621                     return isSymbolOfDeclarationWithCollidingName(symbol);
67622                 }
67623             }
67624             return false;
67625         }
67626         function isValueAliasDeclaration(node) {
67627             switch (node.kind) {
67628                 case 253 /* ImportEqualsDeclaration */:
67629                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
67630                 case 255 /* ImportClause */:
67631                 case 256 /* NamespaceImport */:
67632                 case 258 /* ImportSpecifier */:
67633                 case 263 /* ExportSpecifier */:
67634                     var symbol = getSymbolOfNode(node) || unknownSymbol;
67635                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
67636                 case 260 /* ExportDeclaration */:
67637                     var exportClause = node.exportClause;
67638                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
67639                         ts.some(exportClause.elements, isValueAliasDeclaration));
67640                 case 259 /* ExportAssignment */:
67641                     return node.expression && node.expression.kind === 75 /* Identifier */ ?
67642                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
67643                         true;
67644             }
67645             return false;
67646         }
67647         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
67648             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
67649             if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
67650                 // parent is not source file or it is not reference to internal module
67651                 return false;
67652             }
67653             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
67654             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
67655         }
67656         function isAliasResolvedToValue(symbol) {
67657             var target = resolveAlias(symbol);
67658             if (target === unknownSymbol) {
67659                 return true;
67660             }
67661             // const enums and modules that contain only const enums are not considered values from the emit perspective
67662             // unless 'preserveConstEnums' option is set to true
67663             return !!(target.flags & 111551 /* Value */) &&
67664                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
67665         }
67666         function isConstEnumOrConstEnumOnlyModule(s) {
67667             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
67668         }
67669         function isReferencedAliasDeclaration(node, checkChildren) {
67670             if (isAliasSymbolDeclaration(node)) {
67671                 var symbol = getSymbolOfNode(node);
67672                 if (symbol && getSymbolLinks(symbol).referenced) {
67673                     return true;
67674                 }
67675                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
67676                 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
67677                     target.flags & 111551 /* Value */ &&
67678                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
67679                     // An `export import ... =` of a value symbol is always considered referenced
67680                     return true;
67681                 }
67682             }
67683             if (checkChildren) {
67684                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
67685             }
67686             return false;
67687         }
67688         function isImplementationOfOverload(node) {
67689             if (ts.nodeIsPresent(node.body)) {
67690                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
67691                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
67692                 var symbol = getSymbolOfNode(node);
67693                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
67694                 // If this function body corresponds to function with multiple signature, it is implementation of overload
67695                 // e.g.: function foo(a: string): string;
67696                 //       function foo(a: number): number;
67697                 //       function foo(a: any) { // This is implementation of the overloads
67698                 //           return a;
67699                 //       }
67700                 return signaturesOfSymbol.length > 1 ||
67701                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
67702                     // e.g.: function foo(a: string): string;
67703                     //       function foo(a: any) { // This is implementation of the overloads
67704                     //           return a;
67705                     //       }
67706                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
67707             }
67708             return false;
67709         }
67710         function isRequiredInitializedParameter(parameter) {
67711             return !!strictNullChecks &&
67712                 !isOptionalParameter(parameter) &&
67713                 !ts.isJSDocParameterTag(parameter) &&
67714                 !!parameter.initializer &&
67715                 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67716         }
67717         function isOptionalUninitializedParameterProperty(parameter) {
67718             return strictNullChecks &&
67719                 isOptionalParameter(parameter) &&
67720                 !parameter.initializer &&
67721                 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67722         }
67723         function isExpandoFunctionDeclaration(node) {
67724             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67725             if (!declaration) {
67726                 return false;
67727             }
67728             var symbol = getSymbolOfNode(declaration);
67729             if (!symbol || !(symbol.flags & 16 /* Function */)) {
67730                 return false;
67731             }
67732             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
67733         }
67734         function getPropertiesOfContainerFunction(node) {
67735             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67736             if (!declaration) {
67737                 return ts.emptyArray;
67738             }
67739             var symbol = getSymbolOfNode(declaration);
67740             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
67741         }
67742         function getNodeCheckFlags(node) {
67743             return getNodeLinks(node).flags || 0;
67744         }
67745         function getEnumMemberValue(node) {
67746             computeEnumMemberValues(node.parent);
67747             return getNodeLinks(node).enumMemberValue;
67748         }
67749         function canHaveConstantValue(node) {
67750             switch (node.kind) {
67751                 case 284 /* EnumMember */:
67752                 case 194 /* PropertyAccessExpression */:
67753                 case 195 /* ElementAccessExpression */:
67754                     return true;
67755             }
67756             return false;
67757         }
67758         function getConstantValue(node) {
67759             if (node.kind === 284 /* EnumMember */) {
67760                 return getEnumMemberValue(node);
67761             }
67762             var symbol = getNodeLinks(node).resolvedSymbol;
67763             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
67764                 // inline property\index accesses only for const enums
67765                 var member = symbol.valueDeclaration;
67766                 if (ts.isEnumConst(member.parent)) {
67767                     return getEnumMemberValue(member);
67768                 }
67769             }
67770             return undefined;
67771         }
67772         function isFunctionType(type) {
67773             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
67774         }
67775         function getTypeReferenceSerializationKind(typeNameIn, location) {
67776             // ensure both `typeName` and `location` are parse tree nodes.
67777             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
67778             if (!typeName)
67779                 return ts.TypeReferenceSerializationKind.Unknown;
67780             if (location) {
67781                 location = ts.getParseTreeNode(location);
67782                 if (!location)
67783                     return ts.TypeReferenceSerializationKind.Unknown;
67784             }
67785             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
67786             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67787             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
67788             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67789             if (valueSymbol && valueSymbol === typeSymbol) {
67790                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
67791                 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
67792                     return ts.TypeReferenceSerializationKind.Promise;
67793                 }
67794                 var constructorType = getTypeOfSymbol(valueSymbol);
67795                 if (constructorType && isConstructorType(constructorType)) {
67796                     return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
67797                 }
67798             }
67799             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
67800             if (!typeSymbol) {
67801                 return ts.TypeReferenceSerializationKind.Unknown;
67802             }
67803             var type = getDeclaredTypeOfSymbol(typeSymbol);
67804             if (type === errorType) {
67805                 return ts.TypeReferenceSerializationKind.Unknown;
67806             }
67807             else if (type.flags & 3 /* AnyOrUnknown */) {
67808                 return ts.TypeReferenceSerializationKind.ObjectType;
67809             }
67810             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
67811                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
67812             }
67813             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
67814                 return ts.TypeReferenceSerializationKind.BooleanType;
67815             }
67816             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
67817                 return ts.TypeReferenceSerializationKind.NumberLikeType;
67818             }
67819             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
67820                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
67821             }
67822             else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
67823                 return ts.TypeReferenceSerializationKind.StringLikeType;
67824             }
67825             else if (isTupleType(type)) {
67826                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67827             }
67828             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
67829                 return ts.TypeReferenceSerializationKind.ESSymbolType;
67830             }
67831             else if (isFunctionType(type)) {
67832                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
67833             }
67834             else if (isArrayType(type)) {
67835                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67836             }
67837             else {
67838                 return ts.TypeReferenceSerializationKind.ObjectType;
67839             }
67840         }
67841         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
67842             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
67843             if (!declaration) {
67844                 return ts.createToken(125 /* AnyKeyword */);
67845             }
67846             // Get type of the symbol if this is the valid symbol otherwise get type at location
67847             var symbol = getSymbolOfNode(declaration);
67848             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
67849                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
67850                 : errorType;
67851             if (type.flags & 8192 /* UniqueESSymbol */ &&
67852                 type.symbol === symbol) {
67853                 flags |= 1048576 /* AllowUniqueESSymbolType */;
67854             }
67855             if (addUndefined) {
67856                 type = getOptionalType(type);
67857             }
67858             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67859         }
67860         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
67861             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
67862             if (!signatureDeclaration) {
67863                 return ts.createToken(125 /* AnyKeyword */);
67864             }
67865             var signature = getSignatureFromDeclaration(signatureDeclaration);
67866             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67867         }
67868         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
67869             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
67870             if (!expr) {
67871                 return ts.createToken(125 /* AnyKeyword */);
67872             }
67873             var type = getWidenedType(getRegularTypeOfExpression(expr));
67874             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67875         }
67876         function hasGlobalName(name) {
67877             return globals.has(ts.escapeLeadingUnderscores(name));
67878         }
67879         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
67880             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
67881             if (resolvedSymbol) {
67882                 return resolvedSymbol;
67883             }
67884             var location = reference;
67885             if (startInDeclarationContainer) {
67886                 // When resolving the name of a declaration as a value, we need to start resolution
67887                 // at a point outside of the declaration.
67888                 var parent = reference.parent;
67889                 if (ts.isDeclaration(parent) && reference === parent.name) {
67890                     location = getDeclarationContainer(parent);
67891                 }
67892             }
67893             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
67894         }
67895         function getReferencedValueDeclaration(referenceIn) {
67896             if (!ts.isGeneratedIdentifier(referenceIn)) {
67897                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
67898                 if (reference) {
67899                     var symbol = getReferencedValueSymbol(reference);
67900                     if (symbol) {
67901                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
67902                     }
67903                 }
67904             }
67905             return undefined;
67906         }
67907         function isLiteralConstDeclaration(node) {
67908             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
67909                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
67910             }
67911             return false;
67912         }
67913         function literalTypeToNode(type, enclosing, tracker) {
67914             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
67915                 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
67916             return enumResult || ts.createLiteral(type.value);
67917         }
67918         function createLiteralConstValue(node, tracker) {
67919             var type = getTypeOfSymbol(getSymbolOfNode(node));
67920             return literalTypeToNode(type, node, tracker);
67921         }
67922         function getJsxFactoryEntity(location) {
67923             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
67924         }
67925         function createResolver() {
67926             // this variable and functions that use it are deliberately moved here from the outer scope
67927             // to avoid scope pollution
67928             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
67929             var fileToDirective;
67930             if (resolvedTypeReferenceDirectives) {
67931                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
67932                 fileToDirective = ts.createMap();
67933                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
67934                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
67935                         return;
67936                     }
67937                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
67938                     if (file) {
67939                         // Add the transitive closure of path references loaded by this file (as long as they are not)
67940                         // part of an existing type reference.
67941                         addReferencedFilesToTypeDirective(file, key);
67942                     }
67943                 });
67944             }
67945             return {
67946                 getReferencedExportContainer: getReferencedExportContainer,
67947                 getReferencedImportDeclaration: getReferencedImportDeclaration,
67948                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
67949                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
67950                 isValueAliasDeclaration: function (node) {
67951                     node = ts.getParseTreeNode(node);
67952                     // Synthesized nodes are always treated like values.
67953                     return node ? isValueAliasDeclaration(node) : true;
67954                 },
67955                 hasGlobalName: hasGlobalName,
67956                 isReferencedAliasDeclaration: function (node, checkChildren) {
67957                     node = ts.getParseTreeNode(node);
67958                     // Synthesized nodes are always treated as referenced.
67959                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
67960                 },
67961                 getNodeCheckFlags: function (node) {
67962                     node = ts.getParseTreeNode(node);
67963                     return node ? getNodeCheckFlags(node) : 0;
67964                 },
67965                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
67966                 isDeclarationVisible: isDeclarationVisible,
67967                 isImplementationOfOverload: isImplementationOfOverload,
67968                 isRequiredInitializedParameter: isRequiredInitializedParameter,
67969                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
67970                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
67971                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
67972                 createTypeOfDeclaration: createTypeOfDeclaration,
67973                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
67974                 createTypeOfExpression: createTypeOfExpression,
67975                 createLiteralConstValue: createLiteralConstValue,
67976                 isSymbolAccessible: isSymbolAccessible,
67977                 isEntityNameVisible: isEntityNameVisible,
67978                 getConstantValue: function (nodeIn) {
67979                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
67980                     return node ? getConstantValue(node) : undefined;
67981                 },
67982                 collectLinkedAliases: collectLinkedAliases,
67983                 getReferencedValueDeclaration: getReferencedValueDeclaration,
67984                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
67985                 isOptionalParameter: isOptionalParameter,
67986                 moduleExportsSomeValue: moduleExportsSomeValue,
67987                 isArgumentsLocalBinding: isArgumentsLocalBinding,
67988                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
67989                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
67990                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
67991                 isLiteralConstDeclaration: isLiteralConstDeclaration,
67992                 isLateBound: function (nodeIn) {
67993                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67994                     var symbol = node && getSymbolOfNode(node);
67995                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
67996                 },
67997                 getJsxFactoryEntity: getJsxFactoryEntity,
67998                 getAllAccessorDeclarations: function (accessor) {
67999                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
68000                     var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
68001                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
68002                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
68003                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
68004                     var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
68005                     var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
68006                     return {
68007                         firstAccessor: firstAccessor,
68008                         secondAccessor: secondAccessor,
68009                         setAccessor: setAccessor,
68010                         getAccessor: getAccessor
68011                     };
68012                 },
68013                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
68014                 isBindingCapturedByNode: function (node, decl) {
68015                     var parseNode = ts.getParseTreeNode(node);
68016                     var parseDecl = ts.getParseTreeNode(decl);
68017                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
68018                 },
68019                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
68020                     var n = ts.getParseTreeNode(node);
68021                     ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
68022                     var sym = getSymbolOfNode(node);
68023                     if (!sym) {
68024                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
68025                     }
68026                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
68027                 },
68028                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
68029             };
68030             function isImportRequiredByAugmentation(node) {
68031                 var file = ts.getSourceFileOfNode(node);
68032                 if (!file.symbol)
68033                     return false;
68034                 var importTarget = getExternalModuleFileFromDeclaration(node);
68035                 if (!importTarget)
68036                     return false;
68037                 if (importTarget === file)
68038                     return false;
68039                 var exports = getExportsOfModule(file.symbol);
68040                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
68041                     var s = _a[_i];
68042                     if (s.mergeId) {
68043                         var merged = getMergedSymbol(s);
68044                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
68045                             var d = _c[_b];
68046                             var declFile = ts.getSourceFileOfNode(d);
68047                             if (declFile === importTarget) {
68048                                 return true;
68049                             }
68050                         }
68051                     }
68052                 }
68053                 return false;
68054             }
68055             function isInHeritageClause(node) {
68056                 return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
68057             }
68058             // defined here to avoid outer scope pollution
68059             function getTypeReferenceDirectivesForEntityName(node) {
68060                 // program does not have any files with type reference directives - bail out
68061                 if (!fileToDirective) {
68062                     return undefined;
68063                 }
68064                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
68065                 // qualified names can only be used as types\namespaces
68066                 // identifiers are treated as values only if they appear in type queries
68067                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
68068                 if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
68069                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
68070                 }
68071                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
68072                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
68073             }
68074             // defined here to avoid outer scope pollution
68075             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
68076                 // program does not have any files with type reference directives - bail out
68077                 if (!fileToDirective) {
68078                     return undefined;
68079                 }
68080                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
68081                     return undefined;
68082                 }
68083                 // check what declarations in the symbol can contribute to the target meaning
68084                 var typeReferenceDirectives;
68085                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
68086                     var decl = _a[_i];
68087                     // check meaning of the local symbol to see if declaration needs to be analyzed further
68088                     if (decl.symbol && decl.symbol.flags & meaning) {
68089                         var file = ts.getSourceFileOfNode(decl);
68090                         var typeReferenceDirective = fileToDirective.get(file.path);
68091                         if (typeReferenceDirective) {
68092                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
68093                         }
68094                         else {
68095                             // found at least one entry that does not originate from type reference directive
68096                             return undefined;
68097                         }
68098                     }
68099                 }
68100                 return typeReferenceDirectives;
68101             }
68102             function isSymbolFromTypeDeclarationFile(symbol) {
68103                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
68104                 if (!symbol.declarations) {
68105                     return false;
68106                 }
68107                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
68108                 // external modules cannot define or contribute to type declaration files
68109                 var current = symbol;
68110                 while (true) {
68111                     var parent = getParentOfSymbol(current);
68112                     if (parent) {
68113                         current = parent;
68114                     }
68115                     else {
68116                         break;
68117                     }
68118                 }
68119                 if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
68120                     return false;
68121                 }
68122                 // check that at least one declaration of top level symbol originates from type declaration file
68123                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
68124                     var decl = _a[_i];
68125                     var file = ts.getSourceFileOfNode(decl);
68126                     if (fileToDirective.has(file.path)) {
68127                         return true;
68128                     }
68129                 }
68130                 return false;
68131             }
68132             function addReferencedFilesToTypeDirective(file, key) {
68133                 if (fileToDirective.has(file.path))
68134                     return;
68135                 fileToDirective.set(file.path, key);
68136                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
68137                     var fileName = _a[_i].fileName;
68138                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
68139                     var referencedFile = host.getSourceFile(resolvedFile);
68140                     if (referencedFile) {
68141                         addReferencedFilesToTypeDirective(referencedFile, key);
68142                     }
68143                 }
68144             }
68145         }
68146         function getExternalModuleFileFromDeclaration(declaration) {
68147             var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
68148             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
68149             if (!moduleSymbol) {
68150                 return undefined;
68151             }
68152             return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
68153         }
68154         function initializeTypeChecker() {
68155             // Bind all source files and propagate errors
68156             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
68157                 var file = _a[_i];
68158                 ts.bindSourceFile(file, compilerOptions);
68159             }
68160             amalgamatedDuplicates = ts.createMap();
68161             // Initialize global symbol table
68162             var augmentations;
68163             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
68164                 var file = _c[_b];
68165                 if (file.redirectInfo) {
68166                     continue;
68167                 }
68168                 if (!ts.isExternalOrCommonJsModule(file)) {
68169                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
68170                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
68171                     var fileGlobalThisSymbol = file.locals.get("globalThis");
68172                     if (fileGlobalThisSymbol) {
68173                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
68174                             var declaration = _e[_d];
68175                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
68176                         }
68177                     }
68178                     mergeSymbolTable(globals, file.locals);
68179                 }
68180                 if (file.jsGlobalAugmentations) {
68181                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
68182                 }
68183                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
68184                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
68185                 }
68186                 if (file.moduleAugmentations.length) {
68187                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
68188                 }
68189                 if (file.symbol && file.symbol.globalExports) {
68190                     // Merge in UMD exports with first-in-wins semantics (see #9771)
68191                     var source = file.symbol.globalExports;
68192                     source.forEach(function (sourceSymbol, id) {
68193                         if (!globals.has(id)) {
68194                             globals.set(id, sourceSymbol);
68195                         }
68196                     });
68197                 }
68198             }
68199             // We do global augmentations separately from module augmentations (and before creating global types) because they
68200             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
68201             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
68202             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
68203             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
68204             //       did module augmentations prior to finalizing the global types.
68205             if (augmentations) {
68206                 // merge _global_ module augmentations.
68207                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68208                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
68209                     var list = augmentations_1[_f];
68210                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
68211                         var augmentation = list_1[_g];
68212                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
68213                             continue;
68214                         mergeModuleAugmentation(augmentation);
68215                     }
68216                 }
68217             }
68218             // Setup global builtins
68219             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
68220             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
68221             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
68222             getSymbolLinks(unknownSymbol).type = errorType;
68223             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
68224             // Initialize special types
68225             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
68226             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
68227             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
68228             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68229             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68230             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
68231             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
68232             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
68233             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
68234             anyArrayType = createArrayType(anyType);
68235             autoArrayType = createArrayType(autoType);
68236             if (autoArrayType === emptyObjectType) {
68237                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
68238                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
68239             }
68240             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
68241             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
68242             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
68243             if (augmentations) {
68244                 // merge _nonglobal_ module augmentations.
68245                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68246                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
68247                     var list = augmentations_2[_h];
68248                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
68249                         var augmentation = list_2[_j];
68250                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
68251                             continue;
68252                         mergeModuleAugmentation(augmentation);
68253                     }
68254                 }
68255             }
68256             amalgamatedDuplicates.forEach(function (_a) {
68257                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
68258                 // If not many things conflict, issue individual errors
68259                 if (conflictingSymbols.size < 8) {
68260                     conflictingSymbols.forEach(function (_a, symbolName) {
68261                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
68262                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
68263                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
68264                             var node = firstFileLocations_1[_i];
68265                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
68266                         }
68267                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
68268                             var node = secondFileLocations_1[_b];
68269                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
68270                         }
68271                     });
68272                 }
68273                 else {
68274                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
68275                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
68276                     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)));
68277                     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)));
68278                 }
68279             });
68280             amalgamatedDuplicates = undefined;
68281         }
68282         function checkExternalEmitHelpers(location, helpers) {
68283             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
68284                 var sourceFile = ts.getSourceFileOfNode(location);
68285                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
68286                     var helpersModule = resolveHelpersModule(sourceFile, location);
68287                     if (helpersModule !== unknownSymbol) {
68288                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
68289                         for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) {
68290                             if (uncheckedHelpers & helper) {
68291                                 var name = getHelperName(helper);
68292                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
68293                                 if (!symbol) {
68294                                     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);
68295                                 }
68296                             }
68297                         }
68298                     }
68299                     requestedExternalEmitHelpers |= helpers;
68300                 }
68301             }
68302         }
68303         function getHelperName(helper) {
68304             switch (helper) {
68305                 case 1 /* Extends */: return "__extends";
68306                 case 2 /* Assign */: return "__assign";
68307                 case 4 /* Rest */: return "__rest";
68308                 case 8 /* Decorate */: return "__decorate";
68309                 case 16 /* Metadata */: return "__metadata";
68310                 case 32 /* Param */: return "__param";
68311                 case 64 /* Awaiter */: return "__awaiter";
68312                 case 128 /* Generator */: return "__generator";
68313                 case 256 /* Values */: return "__values";
68314                 case 512 /* Read */: return "__read";
68315                 case 1024 /* Spread */: return "__spread";
68316                 case 2048 /* SpreadArrays */: return "__spreadArrays";
68317                 case 4096 /* Await */: return "__await";
68318                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
68319                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
68320                 case 32768 /* AsyncValues */: return "__asyncValues";
68321                 case 65536 /* ExportStar */: return "__exportStar";
68322                 case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
68323                 case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
68324                 case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
68325                 case 1048576 /* CreateBinding */: return "__createBinding";
68326                 default: return ts.Debug.fail("Unrecognized helper");
68327             }
68328         }
68329         function resolveHelpersModule(node, errorNode) {
68330             if (!externalHelpersModule) {
68331                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
68332             }
68333             return externalHelpersModule;
68334         }
68335         // GRAMMAR CHECKING
68336         function checkGrammarDecoratorsAndModifiers(node) {
68337             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
68338         }
68339         function checkGrammarDecorators(node) {
68340             if (!node.decorators) {
68341                 return false;
68342             }
68343             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
68344                 if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
68345                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
68346                 }
68347                 else {
68348                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
68349                 }
68350             }
68351             else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
68352                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
68353                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
68354                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
68355                 }
68356             }
68357             return false;
68358         }
68359         function checkGrammarModifiers(node) {
68360             var quickResult = reportObviousModifierErrors(node);
68361             if (quickResult !== undefined) {
68362                 return quickResult;
68363             }
68364             var lastStatic, lastDeclare, lastAsync, lastReadonly;
68365             var flags = 0 /* None */;
68366             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
68367                 var modifier = _a[_i];
68368                 if (modifier.kind !== 138 /* ReadonlyKeyword */) {
68369                     if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
68370                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
68371                     }
68372                     if (node.kind === 167 /* IndexSignature */) {
68373                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
68374                     }
68375                 }
68376                 switch (modifier.kind) {
68377                     case 81 /* ConstKeyword */:
68378                         if (node.kind !== 248 /* EnumDeclaration */) {
68379                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
68380                         }
68381                         break;
68382                     case 119 /* PublicKeyword */:
68383                     case 118 /* ProtectedKeyword */:
68384                     case 117 /* PrivateKeyword */:
68385                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
68386                         if (flags & 28 /* AccessibilityModifier */) {
68387                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
68388                         }
68389                         else if (flags & 32 /* Static */) {
68390                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
68391                         }
68392                         else if (flags & 64 /* Readonly */) {
68393                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
68394                         }
68395                         else if (flags & 256 /* Async */) {
68396                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
68397                         }
68398                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68399                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
68400                         }
68401                         else if (flags & 128 /* Abstract */) {
68402                             if (modifier.kind === 117 /* PrivateKeyword */) {
68403                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
68404                             }
68405                             else {
68406                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
68407                             }
68408                         }
68409                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68410                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
68411                         }
68412                         flags |= ts.modifierToFlag(modifier.kind);
68413                         break;
68414                     case 120 /* StaticKeyword */:
68415                         if (flags & 32 /* Static */) {
68416                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
68417                         }
68418                         else if (flags & 64 /* Readonly */) {
68419                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
68420                         }
68421                         else if (flags & 256 /* Async */) {
68422                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
68423                         }
68424                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68425                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
68426                         }
68427                         else if (node.kind === 156 /* Parameter */) {
68428                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
68429                         }
68430                         else if (flags & 128 /* Abstract */) {
68431                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68432                         }
68433                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68434                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
68435                         }
68436                         flags |= 32 /* Static */;
68437                         lastStatic = modifier;
68438                         break;
68439                     case 138 /* ReadonlyKeyword */:
68440                         if (flags & 64 /* Readonly */) {
68441                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
68442                         }
68443                         else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
68444                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
68445                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
68446                         }
68447                         flags |= 64 /* Readonly */;
68448                         lastReadonly = modifier;
68449                         break;
68450                     case 89 /* ExportKeyword */:
68451                         if (flags & 1 /* Export */) {
68452                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
68453                         }
68454                         else if (flags & 2 /* Ambient */) {
68455                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
68456                         }
68457                         else if (flags & 128 /* Abstract */) {
68458                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
68459                         }
68460                         else if (flags & 256 /* Async */) {
68461                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
68462                         }
68463                         else if (ts.isClassLike(node.parent)) {
68464                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
68465                         }
68466                         else if (node.kind === 156 /* Parameter */) {
68467                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
68468                         }
68469                         flags |= 1 /* Export */;
68470                         break;
68471                     case 84 /* DefaultKeyword */:
68472                         var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
68473                         if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
68474                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
68475                         }
68476                         flags |= 512 /* Default */;
68477                         break;
68478                     case 130 /* DeclareKeyword */:
68479                         if (flags & 2 /* Ambient */) {
68480                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
68481                         }
68482                         else if (flags & 256 /* Async */) {
68483                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68484                         }
68485                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
68486                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
68487                         }
68488                         else if (node.kind === 156 /* Parameter */) {
68489                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
68490                         }
68491                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
68492                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
68493                         }
68494                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68495                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
68496                         }
68497                         flags |= 2 /* Ambient */;
68498                         lastDeclare = modifier;
68499                         break;
68500                     case 122 /* AbstractKeyword */:
68501                         if (flags & 128 /* Abstract */) {
68502                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
68503                         }
68504                         if (node.kind !== 245 /* ClassDeclaration */) {
68505                             if (node.kind !== 161 /* MethodDeclaration */ &&
68506                                 node.kind !== 159 /* PropertyDeclaration */ &&
68507                                 node.kind !== 163 /* GetAccessor */ &&
68508                                 node.kind !== 164 /* SetAccessor */) {
68509                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
68510                             }
68511                             if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
68512                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
68513                             }
68514                             if (flags & 32 /* Static */) {
68515                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68516                             }
68517                             if (flags & 8 /* Private */) {
68518                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
68519                             }
68520                         }
68521                         if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
68522                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
68523                         }
68524                         flags |= 128 /* Abstract */;
68525                         break;
68526                     case 126 /* AsyncKeyword */:
68527                         if (flags & 256 /* Async */) {
68528                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
68529                         }
68530                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
68531                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68532                         }
68533                         else if (node.kind === 156 /* Parameter */) {
68534                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
68535                         }
68536                         flags |= 256 /* Async */;
68537                         lastAsync = modifier;
68538                         break;
68539                 }
68540             }
68541             if (node.kind === 162 /* Constructor */) {
68542                 if (flags & 32 /* Static */) {
68543                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
68544                 }
68545                 if (flags & 128 /* Abstract */) {
68546                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
68547                 }
68548                 else if (flags & 256 /* Async */) {
68549                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
68550                 }
68551                 else if (flags & 64 /* Readonly */) {
68552                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
68553                 }
68554                 return false;
68555             }
68556             else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
68557                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
68558             }
68559             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
68560                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
68561             }
68562             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
68563                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
68564             }
68565             if (flags & 256 /* Async */) {
68566                 return checkGrammarAsyncModifier(node, lastAsync);
68567             }
68568             return false;
68569         }
68570         /**
68571          * true | false: Early return this value from checkGrammarModifiers.
68572          * undefined: Need to do full checking on the modifiers.
68573          */
68574         function reportObviousModifierErrors(node) {
68575             return !node.modifiers
68576                 ? false
68577                 : shouldReportBadModifier(node)
68578                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
68579                     : undefined;
68580         }
68581         function shouldReportBadModifier(node) {
68582             switch (node.kind) {
68583                 case 163 /* GetAccessor */:
68584                 case 164 /* SetAccessor */:
68585                 case 162 /* Constructor */:
68586                 case 159 /* PropertyDeclaration */:
68587                 case 158 /* PropertySignature */:
68588                 case 161 /* MethodDeclaration */:
68589                 case 160 /* MethodSignature */:
68590                 case 167 /* IndexSignature */:
68591                 case 249 /* ModuleDeclaration */:
68592                 case 254 /* ImportDeclaration */:
68593                 case 253 /* ImportEqualsDeclaration */:
68594                 case 260 /* ExportDeclaration */:
68595                 case 259 /* ExportAssignment */:
68596                 case 201 /* FunctionExpression */:
68597                 case 202 /* ArrowFunction */:
68598                 case 156 /* Parameter */:
68599                     return false;
68600                 default:
68601                     if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68602                         return false;
68603                     }
68604                     switch (node.kind) {
68605                         case 244 /* FunctionDeclaration */:
68606                             return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
68607                         case 245 /* ClassDeclaration */:
68608                             return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
68609                         case 246 /* InterfaceDeclaration */:
68610                         case 225 /* VariableStatement */:
68611                         case 247 /* TypeAliasDeclaration */:
68612                             return true;
68613                         case 248 /* EnumDeclaration */:
68614                             return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
68615                         default:
68616                             ts.Debug.fail();
68617                             return false;
68618                     }
68619             }
68620         }
68621         function nodeHasAnyModifiersExcept(node, allowedModifier) {
68622             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
68623         }
68624         function checkGrammarAsyncModifier(node, asyncModifier) {
68625             switch (node.kind) {
68626                 case 161 /* MethodDeclaration */:
68627                 case 244 /* FunctionDeclaration */:
68628                 case 201 /* FunctionExpression */:
68629                 case 202 /* ArrowFunction */:
68630                     return false;
68631             }
68632             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
68633         }
68634         function checkGrammarForDisallowedTrailingComma(list, diag) {
68635             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
68636             if (list && list.hasTrailingComma) {
68637                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
68638             }
68639             return false;
68640         }
68641         function checkGrammarTypeParameterList(typeParameters, file) {
68642             if (typeParameters && typeParameters.length === 0) {
68643                 var start = typeParameters.pos - "<".length;
68644                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
68645                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
68646             }
68647             return false;
68648         }
68649         function checkGrammarParameterList(parameters) {
68650             var seenOptionalParameter = false;
68651             var parameterCount = parameters.length;
68652             for (var i = 0; i < parameterCount; i++) {
68653                 var parameter = parameters[i];
68654                 if (parameter.dotDotDotToken) {
68655                     if (i !== (parameterCount - 1)) {
68656                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
68657                     }
68658                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
68659                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68660                     }
68661                     if (parameter.questionToken) {
68662                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
68663                     }
68664                     if (parameter.initializer) {
68665                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
68666                     }
68667                 }
68668                 else if (parameter.questionToken) {
68669                     seenOptionalParameter = true;
68670                     if (parameter.initializer) {
68671                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
68672                     }
68673                 }
68674                 else if (seenOptionalParameter && !parameter.initializer) {
68675                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
68676                 }
68677             }
68678         }
68679         function getNonSimpleParameters(parameters) {
68680             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
68681         }
68682         function checkGrammarForUseStrictSimpleParameterList(node) {
68683             if (languageVersion >= 3 /* ES2016 */) {
68684                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
68685                 if (useStrictDirective_1) {
68686                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
68687                     if (ts.length(nonSimpleParameters)) {
68688                         ts.forEach(nonSimpleParameters, function (parameter) {
68689                             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));
68690                         });
68691                         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)); });
68692                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
68693                         return true;
68694                     }
68695                 }
68696             }
68697             return false;
68698         }
68699         function checkGrammarFunctionLikeDeclaration(node) {
68700             // Prevent cascading error by short-circuit
68701             var file = ts.getSourceFileOfNode(node);
68702             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
68703                 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
68704                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
68705         }
68706         function checkGrammarClassLikeDeclaration(node) {
68707             var file = ts.getSourceFileOfNode(node);
68708             return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
68709         }
68710         function checkGrammarArrowFunction(node, file) {
68711             if (!ts.isArrowFunction(node)) {
68712                 return false;
68713             }
68714             var equalsGreaterThanToken = node.equalsGreaterThanToken;
68715             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
68716             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
68717             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
68718         }
68719         function checkGrammarIndexSignatureParameters(node) {
68720             var parameter = node.parameters[0];
68721             if (node.parameters.length !== 1) {
68722                 if (parameter) {
68723                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68724                 }
68725                 else {
68726                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68727                 }
68728             }
68729             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
68730             if (parameter.dotDotDotToken) {
68731                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
68732             }
68733             if (ts.hasModifiers(parameter)) {
68734                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
68735             }
68736             if (parameter.questionToken) {
68737                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
68738             }
68739             if (parameter.initializer) {
68740                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
68741             }
68742             if (!parameter.type) {
68743                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
68744             }
68745             if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
68746                 var type = getTypeFromTypeNode(parameter.type);
68747                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
68748                     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));
68749                 }
68750                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
68751                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
68752                 }
68753                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
68754             }
68755             if (!node.type) {
68756                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
68757             }
68758             return false;
68759         }
68760         function checkGrammarIndexSignature(node) {
68761             // Prevent cascading error by short-circuit
68762             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
68763         }
68764         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
68765             if (typeArguments && typeArguments.length === 0) {
68766                 var sourceFile = ts.getSourceFileOfNode(node);
68767                 var start = typeArguments.pos - "<".length;
68768                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
68769                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
68770             }
68771             return false;
68772         }
68773         function checkGrammarTypeArguments(node, typeArguments) {
68774             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
68775                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
68776         }
68777         function checkGrammarTaggedTemplateChain(node) {
68778             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
68779                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
68780             }
68781             return false;
68782         }
68783         function checkGrammarForOmittedArgument(args) {
68784             if (args) {
68785                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
68786                     var arg = args_4[_i];
68787                     if (arg.kind === 215 /* OmittedExpression */) {
68788                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
68789                     }
68790                 }
68791             }
68792             return false;
68793         }
68794         function checkGrammarArguments(args) {
68795             return checkGrammarForOmittedArgument(args);
68796         }
68797         function checkGrammarHeritageClause(node) {
68798             var types = node.types;
68799             if (checkGrammarForDisallowedTrailingComma(types)) {
68800                 return true;
68801             }
68802             if (types && types.length === 0) {
68803                 var listType = ts.tokenToString(node.token);
68804                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
68805             }
68806             return ts.some(types, checkGrammarExpressionWithTypeArguments);
68807         }
68808         function checkGrammarExpressionWithTypeArguments(node) {
68809             return checkGrammarTypeArguments(node, node.typeArguments);
68810         }
68811         function checkGrammarClassDeclarationHeritageClauses(node) {
68812             var seenExtendsClause = false;
68813             var seenImplementsClause = false;
68814             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
68815                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68816                     var heritageClause = _a[_i];
68817                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68818                         if (seenExtendsClause) {
68819                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68820                         }
68821                         if (seenImplementsClause) {
68822                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
68823                         }
68824                         if (heritageClause.types.length > 1) {
68825                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
68826                         }
68827                         seenExtendsClause = true;
68828                     }
68829                     else {
68830                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68831                         if (seenImplementsClause) {
68832                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
68833                         }
68834                         seenImplementsClause = true;
68835                     }
68836                     // Grammar checking heritageClause inside class declaration
68837                     checkGrammarHeritageClause(heritageClause);
68838                 }
68839             }
68840         }
68841         function checkGrammarInterfaceDeclaration(node) {
68842             var seenExtendsClause = false;
68843             if (node.heritageClauses) {
68844                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68845                     var heritageClause = _a[_i];
68846                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68847                         if (seenExtendsClause) {
68848                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68849                         }
68850                         seenExtendsClause = true;
68851                     }
68852                     else {
68853                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68854                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
68855                     }
68856                     // Grammar checking heritageClause inside class declaration
68857                     checkGrammarHeritageClause(heritageClause);
68858                 }
68859             }
68860             return false;
68861         }
68862         function checkGrammarComputedPropertyName(node) {
68863             // If node is not a computedPropertyName, just skip the grammar checking
68864             if (node.kind !== 154 /* ComputedPropertyName */) {
68865                 return false;
68866             }
68867             var computedPropertyName = node;
68868             if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
68869                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
68870             }
68871             return false;
68872         }
68873         function checkGrammarForGenerator(node) {
68874             if (node.asteriskToken) {
68875                 ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
68876                     node.kind === 201 /* FunctionExpression */ ||
68877                     node.kind === 161 /* MethodDeclaration */);
68878                 if (node.flags & 8388608 /* Ambient */) {
68879                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
68880                 }
68881                 if (!node.body) {
68882                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
68883                 }
68884             }
68885         }
68886         function checkGrammarForInvalidQuestionMark(questionToken, message) {
68887             return !!questionToken && grammarErrorOnNode(questionToken, message);
68888         }
68889         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
68890             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
68891         }
68892         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
68893             var seen = ts.createUnderscoreEscapedMap();
68894             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
68895                 var prop = _a[_i];
68896                 if (prop.kind === 283 /* SpreadAssignment */) {
68897                     if (inDestructuring) {
68898                         // a rest property cannot be destructured any further
68899                         var expression = ts.skipParentheses(prop.expression);
68900                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
68901                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
68902                         }
68903                     }
68904                     continue;
68905                 }
68906                 var name = prop.name;
68907                 if (name.kind === 154 /* ComputedPropertyName */) {
68908                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
68909                     checkGrammarComputedPropertyName(name);
68910                 }
68911                 if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
68912                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
68913                     // outside of destructuring it is a syntax error
68914                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
68915                 }
68916                 if (name.kind === 76 /* PrivateIdentifier */) {
68917                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
68918                 }
68919                 // Modifiers are never allowed on properties except for 'async' on a method declaration
68920                 if (prop.modifiers) {
68921                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
68922                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
68923                         var mod = _c[_b];
68924                         if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
68925                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
68926                         }
68927                     }
68928                 }
68929                 // ECMA-262 11.1.5 Object Initializer
68930                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
68931                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
68932                 // IsDataDescriptor(propId.descriptor) is true.
68933                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
68934                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
68935                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
68936                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
68937                 var currentKind = void 0;
68938                 switch (prop.kind) {
68939                     case 282 /* ShorthandPropertyAssignment */:
68940                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
68941                     // falls through
68942                     case 281 /* PropertyAssignment */:
68943                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
68944                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
68945                         if (name.kind === 8 /* NumericLiteral */) {
68946                             checkGrammarNumericLiteral(name);
68947                         }
68948                         currentKind = 4 /* PropertyAssignment */;
68949                         break;
68950                     case 161 /* MethodDeclaration */:
68951                         currentKind = 8 /* Method */;
68952                         break;
68953                     case 163 /* GetAccessor */:
68954                         currentKind = 1 /* GetAccessor */;
68955                         break;
68956                     case 164 /* SetAccessor */:
68957                         currentKind = 2 /* SetAccessor */;
68958                         break;
68959                     default:
68960                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
68961                 }
68962                 if (!inDestructuring) {
68963                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
68964                     if (effectiveName === undefined) {
68965                         continue;
68966                     }
68967                     var existingKind = seen.get(effectiveName);
68968                     if (!existingKind) {
68969                         seen.set(effectiveName, currentKind);
68970                     }
68971                     else {
68972                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
68973                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
68974                         }
68975                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
68976                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
68977                                 seen.set(effectiveName, currentKind | existingKind);
68978                             }
68979                             else {
68980                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
68981                             }
68982                         }
68983                         else {
68984                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
68985                         }
68986                     }
68987                 }
68988             }
68989         }
68990         function checkGrammarJsxElement(node) {
68991             checkGrammarTypeArguments(node, node.typeArguments);
68992             var seen = ts.createUnderscoreEscapedMap();
68993             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
68994                 var attr = _a[_i];
68995                 if (attr.kind === 275 /* JsxSpreadAttribute */) {
68996                     continue;
68997                 }
68998                 var name = attr.name, initializer = attr.initializer;
68999                 if (!seen.get(name.escapedText)) {
69000                     seen.set(name.escapedText, true);
69001                 }
69002                 else {
69003                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
69004                 }
69005                 if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
69006                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
69007                 }
69008             }
69009         }
69010         function checkGrammarJsxExpression(node) {
69011             if (node.expression && ts.isCommaSequence(node.expression)) {
69012                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
69013             }
69014         }
69015         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
69016             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
69017                 return true;
69018             }
69019             if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
69020                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
69021                     // use of 'for-await-of' in non-async function
69022                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
69023                     if (!hasParseDiagnostics(sourceFile)) {
69024                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
69025                         var func = ts.getContainingFunction(forInOrOfStatement);
69026                         if (func && func.kind !== 162 /* Constructor */) {
69027                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
69028                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
69029                             ts.addRelatedInfo(diagnostic, relatedInfo);
69030                         }
69031                         diagnostics.add(diagnostic);
69032                         return true;
69033                     }
69034                     return false;
69035                 }
69036             }
69037             if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
69038                 var variableList = forInOrOfStatement.initializer;
69039                 if (!checkGrammarVariableDeclarationList(variableList)) {
69040                     var declarations = variableList.declarations;
69041                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
69042                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
69043                     // For example:
69044                     //      var let = 10;
69045                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
69046                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
69047                     // We will then want to skip on grammar checking on variableList declaration
69048                     if (!declarations.length) {
69049                         return false;
69050                     }
69051                     if (declarations.length > 1) {
69052                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
69053                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
69054                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
69055                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
69056                     }
69057                     var firstDeclaration = declarations[0];
69058                     if (firstDeclaration.initializer) {
69059                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
69060                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
69061                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
69062                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
69063                     }
69064                     if (firstDeclaration.type) {
69065                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
69066                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
69067                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
69068                         return grammarErrorOnNode(firstDeclaration, diagnostic);
69069                     }
69070                 }
69071             }
69072             return false;
69073         }
69074         function checkGrammarAccessor(accessor) {
69075             if (!(accessor.flags & 8388608 /* Ambient */)) {
69076                 if (languageVersion < 1 /* ES5 */) {
69077                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
69078                 }
69079                 if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
69080                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69081                 }
69082             }
69083             if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
69084                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
69085             }
69086             if (accessor.typeParameters) {
69087                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
69088             }
69089             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
69090                 return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
69091                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
69092                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
69093             }
69094             if (accessor.kind === 164 /* SetAccessor */) {
69095                 if (accessor.type) {
69096                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
69097                 }
69098                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
69099                 if (parameter.dotDotDotToken) {
69100                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
69101                 }
69102                 if (parameter.questionToken) {
69103                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
69104                 }
69105                 if (parameter.initializer) {
69106                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
69107                 }
69108             }
69109             return false;
69110         }
69111         /** Does the accessor have the right number of parameters?
69112          * A get accessor has no parameters or a single `this` parameter.
69113          * A set accessor has one parameter or a `this` parameter and one more parameter.
69114          */
69115         function doesAccessorHaveCorrectParameterCount(accessor) {
69116             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
69117         }
69118         function getAccessorThisParameter(accessor) {
69119             if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
69120                 return ts.getThisParameter(accessor);
69121             }
69122         }
69123         function checkGrammarTypeOperatorNode(node) {
69124             if (node.operator === 147 /* UniqueKeyword */) {
69125                 if (node.type.kind !== 144 /* SymbolKeyword */) {
69126                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
69127                 }
69128                 var parent = ts.walkUpParenthesizedTypes(node.parent);
69129                 switch (parent.kind) {
69130                     case 242 /* VariableDeclaration */:
69131                         var decl = parent;
69132                         if (decl.name.kind !== 75 /* Identifier */) {
69133                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
69134                         }
69135                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
69136                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
69137                         }
69138                         if (!(decl.parent.flags & 2 /* Const */)) {
69139                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
69140                         }
69141                         break;
69142                     case 159 /* PropertyDeclaration */:
69143                         if (!ts.hasModifier(parent, 32 /* Static */) ||
69144                             !ts.hasModifier(parent, 64 /* Readonly */)) {
69145                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
69146                         }
69147                         break;
69148                     case 158 /* PropertySignature */:
69149                         if (!ts.hasModifier(parent, 64 /* Readonly */)) {
69150                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
69151                         }
69152                         break;
69153                     default:
69154                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
69155                 }
69156             }
69157             else if (node.operator === 138 /* ReadonlyKeyword */) {
69158                 if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
69159                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
69160                 }
69161             }
69162         }
69163         function checkGrammarForInvalidDynamicName(node, message) {
69164             if (isNonBindableDynamicName(node)) {
69165                 return grammarErrorOnNode(node, message);
69166             }
69167         }
69168         function checkGrammarMethod(node) {
69169             if (checkGrammarFunctionLikeDeclaration(node)) {
69170                 return true;
69171             }
69172             if (node.kind === 161 /* MethodDeclaration */) {
69173                 if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
69174                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
69175                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
69176                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
69177                     }
69178                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
69179                         return true;
69180                     }
69181                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
69182                         return true;
69183                     }
69184                     else if (node.body === undefined) {
69185                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69186                     }
69187                 }
69188                 if (checkGrammarForGenerator(node)) {
69189                     return true;
69190                 }
69191             }
69192             if (ts.isClassLike(node.parent)) {
69193                 // Technically, computed properties in ambient contexts is disallowed
69194                 // for property declarations and accessors too, not just methods.
69195                 // However, property declarations disallow computed names in general,
69196                 // and accessors are not allowed in ambient contexts in general,
69197                 // so this error only really matters for methods.
69198                 if (node.flags & 8388608 /* Ambient */) {
69199                     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);
69200                 }
69201                 else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
69202                     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);
69203                 }
69204             }
69205             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69206                 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);
69207             }
69208             else if (node.parent.kind === 173 /* TypeLiteral */) {
69209                 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);
69210             }
69211         }
69212         function checkGrammarBreakOrContinueStatement(node) {
69213             var current = node;
69214             while (current) {
69215                 if (ts.isFunctionLike(current)) {
69216                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
69217                 }
69218                 switch (current.kind) {
69219                     case 238 /* LabeledStatement */:
69220                         if (node.label && current.label.escapedText === node.label.escapedText) {
69221                             // found matching label - verify that label usage is correct
69222                             // continue can only target labels that are on iteration statements
69223                             var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
69224                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
69225                             if (isMisplacedContinueLabel) {
69226                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
69227                             }
69228                             return false;
69229                         }
69230                         break;
69231                     case 237 /* SwitchStatement */:
69232                         if (node.kind === 234 /* BreakStatement */ && !node.label) {
69233                             // unlabeled break within switch statement - ok
69234                             return false;
69235                         }
69236                         break;
69237                     default:
69238                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
69239                             // unlabeled break or continue within iteration statement - ok
69240                             return false;
69241                         }
69242                         break;
69243                 }
69244                 current = current.parent;
69245             }
69246             if (node.label) {
69247                 var message = node.kind === 234 /* BreakStatement */
69248                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
69249                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
69250                 return grammarErrorOnNode(node, message);
69251             }
69252             else {
69253                 var message = node.kind === 234 /* BreakStatement */
69254                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
69255                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
69256                 return grammarErrorOnNode(node, message);
69257             }
69258         }
69259         function checkGrammarBindingElement(node) {
69260             if (node.dotDotDotToken) {
69261                 var elements = node.parent.elements;
69262                 if (node !== ts.last(elements)) {
69263                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
69264                 }
69265                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
69266                 if (node.propertyName) {
69267                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
69268                 }
69269                 if (node.initializer) {
69270                     // Error on equals token which immediately precedes the initializer
69271                     return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
69272                 }
69273             }
69274         }
69275         function isStringOrNumberLiteralExpression(expr) {
69276             return ts.isStringOrNumericLiteralLike(expr) ||
69277                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69278                     expr.operand.kind === 8 /* NumericLiteral */;
69279         }
69280         function isBigIntLiteralExpression(expr) {
69281             return expr.kind === 9 /* BigIntLiteral */ ||
69282                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69283                     expr.operand.kind === 9 /* BigIntLiteral */;
69284         }
69285         function isSimpleLiteralEnumReference(expr) {
69286             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
69287                 ts.isEntityNameExpression(expr.expression)) {
69288                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
69289             }
69290         }
69291         function checkAmbientInitializer(node) {
69292             var initializer = node.initializer;
69293             if (initializer) {
69294                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
69295                     isSimpleLiteralEnumReference(initializer) ||
69296                     initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
69297                     isBigIntLiteralExpression(initializer));
69298                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
69299                 if (isConstOrReadonly && !node.type) {
69300                     if (isInvalidInitializer) {
69301                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
69302                     }
69303                 }
69304                 else {
69305                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69306                 }
69307                 if (!isConstOrReadonly || isInvalidInitializer) {
69308                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69309                 }
69310             }
69311         }
69312         function checkGrammarVariableDeclaration(node) {
69313             if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
69314                 if (node.flags & 8388608 /* Ambient */) {
69315                     checkAmbientInitializer(node);
69316                 }
69317                 else if (!node.initializer) {
69318                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
69319                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
69320                     }
69321                     if (ts.isVarConst(node)) {
69322                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
69323                     }
69324                 }
69325             }
69326             if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
69327                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
69328             }
69329             var moduleKind = ts.getEmitModuleKind(compilerOptions);
69330             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
69331                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
69332                 checkESModuleMarker(node.name);
69333             }
69334             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
69335             // 1. LexicalDeclaration : LetOrConst BindingList ;
69336             // It is a Syntax Error if the BoundNames of BindingList contains "let".
69337             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
69338             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
69339             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
69340             // and its Identifier is eval or arguments
69341             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
69342         }
69343         function checkESModuleMarker(name) {
69344             if (name.kind === 75 /* Identifier */) {
69345                 if (ts.idText(name) === "__esModule") {
69346                     return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
69347                 }
69348             }
69349             else {
69350                 var elements = name.elements;
69351                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
69352                     var element = elements_1[_i];
69353                     if (!ts.isOmittedExpression(element)) {
69354                         return checkESModuleMarker(element.name);
69355                     }
69356                 }
69357             }
69358             return false;
69359         }
69360         function checkGrammarNameInLetOrConstDeclarations(name) {
69361             if (name.kind === 75 /* Identifier */) {
69362                 if (name.originalKeywordKind === 115 /* LetKeyword */) {
69363                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
69364                 }
69365             }
69366             else {
69367                 var elements = name.elements;
69368                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
69369                     var element = elements_2[_i];
69370                     if (!ts.isOmittedExpression(element)) {
69371                         checkGrammarNameInLetOrConstDeclarations(element.name);
69372                     }
69373                 }
69374             }
69375             return false;
69376         }
69377         function checkGrammarVariableDeclarationList(declarationList) {
69378             var declarations = declarationList.declarations;
69379             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
69380                 return true;
69381             }
69382             if (!declarationList.declarations.length) {
69383                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
69384             }
69385             return false;
69386         }
69387         function allowLetAndConstDeclarations(parent) {
69388             switch (parent.kind) {
69389                 case 227 /* IfStatement */:
69390                 case 228 /* DoStatement */:
69391                 case 229 /* WhileStatement */:
69392                 case 236 /* WithStatement */:
69393                 case 230 /* ForStatement */:
69394                 case 231 /* ForInStatement */:
69395                 case 232 /* ForOfStatement */:
69396                     return false;
69397                 case 238 /* LabeledStatement */:
69398                     return allowLetAndConstDeclarations(parent.parent);
69399             }
69400             return true;
69401         }
69402         function checkGrammarForDisallowedLetOrConstStatement(node) {
69403             if (!allowLetAndConstDeclarations(node.parent)) {
69404                 if (ts.isLet(node.declarationList)) {
69405                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
69406                 }
69407                 else if (ts.isVarConst(node.declarationList)) {
69408                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
69409                 }
69410             }
69411         }
69412         function checkGrammarMetaProperty(node) {
69413             var escapedText = node.name.escapedText;
69414             switch (node.keywordToken) {
69415                 case 99 /* NewKeyword */:
69416                     if (escapedText !== "target") {
69417                         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");
69418                     }
69419                     break;
69420                 case 96 /* ImportKeyword */:
69421                     if (escapedText !== "meta") {
69422                         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");
69423                     }
69424                     break;
69425             }
69426         }
69427         function hasParseDiagnostics(sourceFile) {
69428             return sourceFile.parseDiagnostics.length > 0;
69429         }
69430         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
69431             var sourceFile = ts.getSourceFileOfNode(node);
69432             if (!hasParseDiagnostics(sourceFile)) {
69433                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69434                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
69435                 return true;
69436             }
69437             return false;
69438         }
69439         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
69440             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
69441             if (!hasParseDiagnostics(sourceFile)) {
69442                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
69443                 return true;
69444             }
69445             return false;
69446         }
69447         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
69448             var sourceFile = ts.getSourceFileOfNode(node);
69449             if (!hasParseDiagnostics(sourceFile)) {
69450                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
69451                 return true;
69452             }
69453             return false;
69454         }
69455         function checkGrammarConstructorTypeParameters(node) {
69456             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
69457             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
69458             if (range) {
69459                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
69460                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
69461             }
69462         }
69463         function checkGrammarConstructorTypeAnnotation(node) {
69464             var type = ts.getEffectiveReturnTypeNode(node);
69465             if (type) {
69466                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
69467             }
69468         }
69469         function checkGrammarProperty(node) {
69470             if (ts.isClassLike(node.parent)) {
69471                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
69472                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
69473                 }
69474                 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)) {
69475                     return true;
69476                 }
69477                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
69478                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
69479                 }
69480             }
69481             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69482                 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)) {
69483                     return true;
69484                 }
69485                 if (node.initializer) {
69486                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
69487                 }
69488             }
69489             else if (node.parent.kind === 173 /* TypeLiteral */) {
69490                 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)) {
69491                     return true;
69492                 }
69493                 if (node.initializer) {
69494                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
69495                 }
69496             }
69497             if (node.flags & 8388608 /* Ambient */) {
69498                 checkAmbientInitializer(node);
69499             }
69500             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
69501                 node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
69502                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
69503             }
69504         }
69505         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
69506             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
69507             // interfaces and imports categories:
69508             //
69509             //  DeclarationElement:
69510             //     ExportAssignment
69511             //     export_opt   InterfaceDeclaration
69512             //     export_opt   TypeAliasDeclaration
69513             //     export_opt   ImportDeclaration
69514             //     export_opt   ExternalImportDeclaration
69515             //     export_opt   AmbientDeclaration
69516             //
69517             // TODO: The spec needs to be amended to reflect this grammar.
69518             if (node.kind === 246 /* InterfaceDeclaration */ ||
69519                 node.kind === 247 /* TypeAliasDeclaration */ ||
69520                 node.kind === 254 /* ImportDeclaration */ ||
69521                 node.kind === 253 /* ImportEqualsDeclaration */ ||
69522                 node.kind === 260 /* ExportDeclaration */ ||
69523                 node.kind === 259 /* ExportAssignment */ ||
69524                 node.kind === 252 /* NamespaceExportDeclaration */ ||
69525                 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
69526                 return false;
69527             }
69528             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
69529         }
69530         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
69531             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
69532                 var decl = _a[_i];
69533                 if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
69534                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
69535                         return true;
69536                     }
69537                 }
69538             }
69539             return false;
69540         }
69541         function checkGrammarSourceFile(node) {
69542             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
69543         }
69544         function checkGrammarStatementInAmbientContext(node) {
69545             if (node.flags & 8388608 /* Ambient */) {
69546                 // Find containing block which is either Block, ModuleBlock, SourceFile
69547                 var links = getNodeLinks(node);
69548                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
69549                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
69550                 }
69551                 // We are either parented by another statement, or some sort of block.
69552                 // If we're in a block, we only want to really report an error once
69553                 // to prevent noisiness.  So use a bit on the block to indicate if
69554                 // this has already been reported, and don't report if it has.
69555                 //
69556                 if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
69557                     var links_2 = getNodeLinks(node.parent);
69558                     // Check if the containing block ever report this error
69559                     if (!links_2.hasReportedStatementInAmbientContext) {
69560                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
69561                     }
69562                 }
69563                 else {
69564                     // We must be parented by a statement.  If so, there's no need
69565                     // to report the error as our parent will have already done it.
69566                     // Debug.assert(isStatement(node.parent));
69567                 }
69568             }
69569             return false;
69570         }
69571         function checkGrammarNumericLiteral(node) {
69572             // Grammar checking
69573             if (node.numericLiteralFlags & 32 /* Octal */) {
69574                 var diagnosticMessage = void 0;
69575                 if (languageVersion >= 1 /* ES5 */) {
69576                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
69577                 }
69578                 else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
69579                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
69580                 }
69581                 else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
69582                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
69583                 }
69584                 if (diagnosticMessage) {
69585                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
69586                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
69587                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
69588                 }
69589             }
69590             // Realism (size) checking
69591             checkNumericLiteralValueSize(node);
69592             return false;
69593         }
69594         function checkNumericLiteralValueSize(node) {
69595             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
69596             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
69597             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
69598             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
69599                 return;
69600             }
69601             // We can't rely on the runtime to accurately store and compare extremely large numeric values
69602             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
69603             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
69604             // it's likely addition operations on it will fail too
69605             var apparentValue = +ts.getTextOfNode(node);
69606             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
69607                 return;
69608             }
69609             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));
69610         }
69611         function checkGrammarBigIntLiteral(node) {
69612             var literalType = ts.isLiteralTypeNode(node.parent) ||
69613                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
69614             if (!literalType) {
69615                 if (languageVersion < 7 /* ES2020 */) {
69616                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
69617                         return true;
69618                     }
69619                 }
69620             }
69621             return false;
69622         }
69623         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
69624             var sourceFile = ts.getSourceFileOfNode(node);
69625             if (!hasParseDiagnostics(sourceFile)) {
69626                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69627                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
69628                 return true;
69629             }
69630             return false;
69631         }
69632         function getAmbientModules() {
69633             if (!ambientModulesCache) {
69634                 ambientModulesCache = [];
69635                 globals.forEach(function (global, sym) {
69636                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
69637                     if (ambientModuleSymbolRegex.test(sym)) {
69638                         ambientModulesCache.push(global);
69639                     }
69640                 });
69641             }
69642             return ambientModulesCache;
69643         }
69644         function checkGrammarImportClause(node) {
69645             if (node.isTypeOnly && node.name && node.namedBindings) {
69646                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
69647             }
69648             return false;
69649         }
69650         function checkGrammarImportCallExpression(node) {
69651             if (moduleKind === ts.ModuleKind.ES2015) {
69652                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
69653             }
69654             if (node.typeArguments) {
69655                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
69656             }
69657             var nodeArguments = node.arguments;
69658             if (nodeArguments.length !== 1) {
69659                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
69660             }
69661             checkGrammarForDisallowedTrailingComma(nodeArguments);
69662             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
69663             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
69664             if (ts.isSpreadElement(nodeArguments[0])) {
69665                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
69666             }
69667             return false;
69668         }
69669         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
69670             var sourceObjectFlags = ts.getObjectFlags(source);
69671             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
69672                 return ts.find(unionTarget.types, function (target) {
69673                     if (target.flags & 524288 /* Object */) {
69674                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
69675                         if (overlapObjFlags & 4 /* Reference */) {
69676                             return source.target === target.target;
69677                         }
69678                         if (overlapObjFlags & 16 /* Anonymous */) {
69679                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
69680                         }
69681                     }
69682                     return false;
69683                 });
69684             }
69685         }
69686         function findBestTypeForObjectLiteral(source, unionTarget) {
69687             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
69688                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
69689             }
69690         }
69691         function findBestTypeForInvokable(source, unionTarget) {
69692             var signatureKind = 0 /* Call */;
69693             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
69694                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
69695             if (hasSignatures) {
69696                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
69697             }
69698         }
69699         function findMostOverlappyType(source, unionTarget) {
69700             var bestMatch;
69701             var matchingCount = 0;
69702             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
69703                 var target = _a[_i];
69704                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
69705                 if (overlap.flags & 4194304 /* Index */) {
69706                     // perfect overlap of keys
69707                     bestMatch = target;
69708                     matchingCount = Infinity;
69709                 }
69710                 else if (overlap.flags & 1048576 /* Union */) {
69711                     // We only want to account for literal types otherwise.
69712                     // If we have a union of index types, it seems likely that we
69713                     // needed to elaborate between two generic mapped types anyway.
69714                     var len = ts.length(ts.filter(overlap.types, isUnitType));
69715                     if (len >= matchingCount) {
69716                         bestMatch = target;
69717                         matchingCount = len;
69718                     }
69719                 }
69720                 else if (isUnitType(overlap) && 1 >= matchingCount) {
69721                     bestMatch = target;
69722                     matchingCount = 1;
69723                 }
69724             }
69725             return bestMatch;
69726         }
69727         function filterPrimitivesIfContainsNonPrimitive(type) {
69728             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
69729                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
69730                 if (!(result.flags & 131072 /* Never */)) {
69731                     return result;
69732                 }
69733             }
69734             return type;
69735         }
69736         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
69737         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
69738             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
69739                 var sourceProperties = getPropertiesOfType(source);
69740                 if (sourceProperties) {
69741                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
69742                     if (sourcePropertiesFiltered) {
69743                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
69744                     }
69745                 }
69746             }
69747             return undefined;
69748         }
69749     }
69750     ts.createTypeChecker = createTypeChecker;
69751     function isNotAccessor(declaration) {
69752         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
69753         return !ts.isAccessor(declaration);
69754     }
69755     function isNotOverload(declaration) {
69756         return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
69757             !!declaration.body;
69758     }
69759     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
69760     function isDeclarationNameOrImportPropertyName(name) {
69761         switch (name.parent.kind) {
69762             case 258 /* ImportSpecifier */:
69763             case 263 /* ExportSpecifier */:
69764                 return ts.isIdentifier(name);
69765             default:
69766                 return ts.isDeclarationName(name);
69767         }
69768     }
69769     function isSomeImportDeclaration(decl) {
69770         switch (decl.kind) {
69771             case 255 /* ImportClause */: // For default import
69772             case 253 /* ImportEqualsDeclaration */:
69773             case 256 /* NamespaceImport */:
69774             case 258 /* ImportSpecifier */: // For rename import `x as y`
69775                 return true;
69776             case 75 /* Identifier */:
69777                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
69778                 return decl.parent.kind === 258 /* ImportSpecifier */;
69779             default:
69780                 return false;
69781         }
69782     }
69783     var JsxNames;
69784     (function (JsxNames) {
69785         JsxNames.JSX = "JSX";
69786         JsxNames.IntrinsicElements = "IntrinsicElements";
69787         JsxNames.ElementClass = "ElementClass";
69788         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
69789         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
69790         JsxNames.Element = "Element";
69791         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
69792         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
69793         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
69794     })(JsxNames || (JsxNames = {}));
69795     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
69796         switch (typeKind) {
69797             case 0 /* Yield */: return "yieldType";
69798             case 1 /* Return */: return "returnType";
69799             case 2 /* Next */: return "nextType";
69800         }
69801     }
69802     function signatureHasRestParameter(s) {
69803         return !!(s.flags & 1 /* HasRestParameter */);
69804     }
69805     ts.signatureHasRestParameter = signatureHasRestParameter;
69806     function signatureHasLiteralTypes(s) {
69807         return !!(s.flags & 2 /* HasLiteralTypes */);
69808     }
69809     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
69810 })(ts || (ts = {}));
69811 var ts;
69812 (function (ts) {
69813     function createSynthesizedNode(kind) {
69814         var node = ts.createNode(kind, -1, -1);
69815         node.flags |= 8 /* Synthesized */;
69816         return node;
69817     }
69818     /* @internal */
69819     function updateNode(updated, original) {
69820         if (updated !== original) {
69821             setOriginalNode(updated, original);
69822             setTextRange(updated, original);
69823             ts.aggregateTransformFlags(updated);
69824         }
69825         return updated;
69826     }
69827     ts.updateNode = updateNode;
69828     /**
69829      * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
69830      */
69831     function createNodeArray(elements, hasTrailingComma) {
69832         if (!elements || elements === ts.emptyArray) {
69833             elements = [];
69834         }
69835         else if (ts.isNodeArray(elements)) {
69836             return elements;
69837         }
69838         var array = elements;
69839         array.pos = -1;
69840         array.end = -1;
69841         array.hasTrailingComma = hasTrailingComma;
69842         return array;
69843     }
69844     ts.createNodeArray = createNodeArray;
69845     /**
69846      * Creates a shallow, memberwise clone of a node with no source map location.
69847      */
69848     /* @internal */
69849     function getSynthesizedClone(node) {
69850         // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
69851         // the original node. We also need to exclude specific properties and only include own-
69852         // properties (to skip members already defined on the shared prototype).
69853         if (node === undefined) {
69854             return node;
69855         }
69856         var clone = createSynthesizedNode(node.kind);
69857         clone.flags |= node.flags;
69858         setOriginalNode(clone, node);
69859         for (var key in node) {
69860             if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
69861                 continue;
69862             }
69863             clone[key] = node[key];
69864         }
69865         return clone;
69866     }
69867     ts.getSynthesizedClone = getSynthesizedClone;
69868     function createLiteral(value, isSingleQuote) {
69869         if (typeof value === "number") {
69870             return createNumericLiteral(value + "");
69871         }
69872         // eslint-disable-next-line no-in-operator
69873         if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
69874             return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
69875         }
69876         if (typeof value === "boolean") {
69877             return value ? createTrue() : createFalse();
69878         }
69879         if (ts.isString(value)) {
69880             var res = createStringLiteral(value);
69881             if (isSingleQuote)
69882                 res.singleQuote = true;
69883             return res;
69884         }
69885         return createLiteralFromNode(value);
69886     }
69887     ts.createLiteral = createLiteral;
69888     function createNumericLiteral(value, numericLiteralFlags) {
69889         if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
69890         var node = createSynthesizedNode(8 /* NumericLiteral */);
69891         node.text = value;
69892         node.numericLiteralFlags = numericLiteralFlags;
69893         return node;
69894     }
69895     ts.createNumericLiteral = createNumericLiteral;
69896     function createBigIntLiteral(value) {
69897         var node = createSynthesizedNode(9 /* BigIntLiteral */);
69898         node.text = value;
69899         return node;
69900     }
69901     ts.createBigIntLiteral = createBigIntLiteral;
69902     function createStringLiteral(text) {
69903         var node = createSynthesizedNode(10 /* StringLiteral */);
69904         node.text = text;
69905         return node;
69906     }
69907     ts.createStringLiteral = createStringLiteral;
69908     function createRegularExpressionLiteral(text) {
69909         var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
69910         node.text = text;
69911         return node;
69912     }
69913     ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
69914     function createLiteralFromNode(sourceNode) {
69915         var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
69916         node.textSourceNode = sourceNode;
69917         return node;
69918     }
69919     function createIdentifier(text, typeArguments) {
69920         var node = createSynthesizedNode(75 /* Identifier */);
69921         node.escapedText = ts.escapeLeadingUnderscores(text);
69922         node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
69923         node.autoGenerateFlags = 0 /* None */;
69924         node.autoGenerateId = 0;
69925         if (typeArguments) {
69926             node.typeArguments = createNodeArray(typeArguments);
69927         }
69928         return node;
69929     }
69930     ts.createIdentifier = createIdentifier;
69931     function updateIdentifier(node, typeArguments) {
69932         return node.typeArguments !== typeArguments
69933             ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
69934             : node;
69935     }
69936     ts.updateIdentifier = updateIdentifier;
69937     var nextAutoGenerateId = 0;
69938     function createTempVariable(recordTempVariable, reservedInNestedScopes) {
69939         var name = createIdentifier("");
69940         name.autoGenerateFlags = 1 /* Auto */;
69941         name.autoGenerateId = nextAutoGenerateId;
69942         nextAutoGenerateId++;
69943         if (recordTempVariable) {
69944             recordTempVariable(name);
69945         }
69946         if (reservedInNestedScopes) {
69947             name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
69948         }
69949         return name;
69950     }
69951     ts.createTempVariable = createTempVariable;
69952     /** Create a unique temporary variable for use in a loop. */
69953     function createLoopVariable() {
69954         var name = createIdentifier("");
69955         name.autoGenerateFlags = 2 /* Loop */;
69956         name.autoGenerateId = nextAutoGenerateId;
69957         nextAutoGenerateId++;
69958         return name;
69959     }
69960     ts.createLoopVariable = createLoopVariable;
69961     /** Create a unique name based on the supplied text. */
69962     function createUniqueName(text) {
69963         var name = createIdentifier(text);
69964         name.autoGenerateFlags = 3 /* Unique */;
69965         name.autoGenerateId = nextAutoGenerateId;
69966         nextAutoGenerateId++;
69967         return name;
69968     }
69969     ts.createUniqueName = createUniqueName;
69970     function createOptimisticUniqueName(text) {
69971         var name = createIdentifier(text);
69972         name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
69973         name.autoGenerateId = nextAutoGenerateId;
69974         nextAutoGenerateId++;
69975         return name;
69976     }
69977     ts.createOptimisticUniqueName = createOptimisticUniqueName;
69978     /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
69979     function createFileLevelUniqueName(text) {
69980         var name = createOptimisticUniqueName(text);
69981         name.autoGenerateFlags |= 32 /* FileLevel */;
69982         return name;
69983     }
69984     ts.createFileLevelUniqueName = createFileLevelUniqueName;
69985     function getGeneratedNameForNode(node, flags) {
69986         var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
69987         name.autoGenerateFlags = 4 /* Node */ | flags;
69988         name.autoGenerateId = nextAutoGenerateId;
69989         name.original = node;
69990         nextAutoGenerateId++;
69991         return name;
69992     }
69993     ts.getGeneratedNameForNode = getGeneratedNameForNode;
69994     // Private Identifiers
69995     function createPrivateIdentifier(text) {
69996         if (text[0] !== "#") {
69997             ts.Debug.fail("First character of private identifier must be #: " + text);
69998         }
69999         var node = createSynthesizedNode(76 /* PrivateIdentifier */);
70000         node.escapedText = ts.escapeLeadingUnderscores(text);
70001         return node;
70002     }
70003     ts.createPrivateIdentifier = createPrivateIdentifier;
70004     // Punctuation
70005     function createToken(token) {
70006         return createSynthesizedNode(token);
70007     }
70008     ts.createToken = createToken;
70009     // Reserved words
70010     function createSuper() {
70011         return createSynthesizedNode(102 /* SuperKeyword */);
70012     }
70013     ts.createSuper = createSuper;
70014     function createThis() {
70015         return createSynthesizedNode(104 /* ThisKeyword */);
70016     }
70017     ts.createThis = createThis;
70018     function createNull() {
70019         return createSynthesizedNode(100 /* NullKeyword */);
70020     }
70021     ts.createNull = createNull;
70022     function createTrue() {
70023         return createSynthesizedNode(106 /* TrueKeyword */);
70024     }
70025     ts.createTrue = createTrue;
70026     function createFalse() {
70027         return createSynthesizedNode(91 /* FalseKeyword */);
70028     }
70029     ts.createFalse = createFalse;
70030     // Modifiers
70031     function createModifier(kind) {
70032         return createToken(kind);
70033     }
70034     ts.createModifier = createModifier;
70035     function createModifiersFromModifierFlags(flags) {
70036         var result = [];
70037         if (flags & 1 /* Export */) {
70038             result.push(createModifier(89 /* ExportKeyword */));
70039         }
70040         if (flags & 2 /* Ambient */) {
70041             result.push(createModifier(130 /* DeclareKeyword */));
70042         }
70043         if (flags & 512 /* Default */) {
70044             result.push(createModifier(84 /* DefaultKeyword */));
70045         }
70046         if (flags & 2048 /* Const */) {
70047             result.push(createModifier(81 /* ConstKeyword */));
70048         }
70049         if (flags & 4 /* Public */) {
70050             result.push(createModifier(119 /* PublicKeyword */));
70051         }
70052         if (flags & 8 /* Private */) {
70053             result.push(createModifier(117 /* PrivateKeyword */));
70054         }
70055         if (flags & 16 /* Protected */) {
70056             result.push(createModifier(118 /* ProtectedKeyword */));
70057         }
70058         if (flags & 128 /* Abstract */) {
70059             result.push(createModifier(122 /* AbstractKeyword */));
70060         }
70061         if (flags & 32 /* Static */) {
70062             result.push(createModifier(120 /* StaticKeyword */));
70063         }
70064         if (flags & 64 /* Readonly */) {
70065             result.push(createModifier(138 /* ReadonlyKeyword */));
70066         }
70067         if (flags & 256 /* Async */) {
70068             result.push(createModifier(126 /* AsyncKeyword */));
70069         }
70070         return result;
70071     }
70072     ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
70073     // Names
70074     function createQualifiedName(left, right) {
70075         var node = createSynthesizedNode(153 /* QualifiedName */);
70076         node.left = left;
70077         node.right = asName(right);
70078         return node;
70079     }
70080     ts.createQualifiedName = createQualifiedName;
70081     function updateQualifiedName(node, left, right) {
70082         return node.left !== left
70083             || node.right !== right
70084             ? updateNode(createQualifiedName(left, right), node)
70085             : node;
70086     }
70087     ts.updateQualifiedName = updateQualifiedName;
70088     function parenthesizeForComputedName(expression) {
70089         return ts.isCommaSequence(expression)
70090             ? createParen(expression)
70091             : expression;
70092     }
70093     function createComputedPropertyName(expression) {
70094         var node = createSynthesizedNode(154 /* ComputedPropertyName */);
70095         node.expression = parenthesizeForComputedName(expression);
70096         return node;
70097     }
70098     ts.createComputedPropertyName = createComputedPropertyName;
70099     function updateComputedPropertyName(node, expression) {
70100         return node.expression !== expression
70101             ? updateNode(createComputedPropertyName(expression), node)
70102             : node;
70103     }
70104     ts.updateComputedPropertyName = updateComputedPropertyName;
70105     // Signature elements
70106     function createTypeParameterDeclaration(name, constraint, defaultType) {
70107         var node = createSynthesizedNode(155 /* TypeParameter */);
70108         node.name = asName(name);
70109         node.constraint = constraint;
70110         node.default = defaultType;
70111         return node;
70112     }
70113     ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
70114     function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
70115         return node.name !== name
70116             || node.constraint !== constraint
70117             || node.default !== defaultType
70118             ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
70119             : node;
70120     }
70121     ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
70122     function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
70123         var node = createSynthesizedNode(156 /* Parameter */);
70124         node.decorators = asNodeArray(decorators);
70125         node.modifiers = asNodeArray(modifiers);
70126         node.dotDotDotToken = dotDotDotToken;
70127         node.name = asName(name);
70128         node.questionToken = questionToken;
70129         node.type = type;
70130         node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
70131         return node;
70132     }
70133     ts.createParameter = createParameter;
70134     function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
70135         return node.decorators !== decorators
70136             || node.modifiers !== modifiers
70137             || node.dotDotDotToken !== dotDotDotToken
70138             || node.name !== name
70139             || node.questionToken !== questionToken
70140             || node.type !== type
70141             || node.initializer !== initializer
70142             ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
70143             : node;
70144     }
70145     ts.updateParameter = updateParameter;
70146     function createDecorator(expression) {
70147         var node = createSynthesizedNode(157 /* Decorator */);
70148         node.expression = ts.parenthesizeForAccess(expression);
70149         return node;
70150     }
70151     ts.createDecorator = createDecorator;
70152     function updateDecorator(node, expression) {
70153         return node.expression !== expression
70154             ? updateNode(createDecorator(expression), node)
70155             : node;
70156     }
70157     ts.updateDecorator = updateDecorator;
70158     // Type Elements
70159     function createPropertySignature(modifiers, name, questionToken, type, initializer) {
70160         var node = createSynthesizedNode(158 /* PropertySignature */);
70161         node.modifiers = asNodeArray(modifiers);
70162         node.name = asName(name);
70163         node.questionToken = questionToken;
70164         node.type = type;
70165         node.initializer = initializer;
70166         return node;
70167     }
70168     ts.createPropertySignature = createPropertySignature;
70169     function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
70170         return node.modifiers !== modifiers
70171             || node.name !== name
70172             || node.questionToken !== questionToken
70173             || node.type !== type
70174             || node.initializer !== initializer
70175             ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
70176             : node;
70177     }
70178     ts.updatePropertySignature = updatePropertySignature;
70179     function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70180         var node = createSynthesizedNode(159 /* PropertyDeclaration */);
70181         node.decorators = asNodeArray(decorators);
70182         node.modifiers = asNodeArray(modifiers);
70183         node.name = asName(name);
70184         node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
70185         node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
70186         node.type = type;
70187         node.initializer = initializer;
70188         return node;
70189     }
70190     ts.createProperty = createProperty;
70191     function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70192         return node.decorators !== decorators
70193             || node.modifiers !== modifiers
70194             || node.name !== name
70195             || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
70196             || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
70197             || node.type !== type
70198             || node.initializer !== initializer
70199             ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
70200             : node;
70201     }
70202     ts.updateProperty = updateProperty;
70203     function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
70204         var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
70205         node.name = asName(name);
70206         node.questionToken = questionToken;
70207         return node;
70208     }
70209     ts.createMethodSignature = createMethodSignature;
70210     function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
70211         return node.typeParameters !== typeParameters
70212             || node.parameters !== parameters
70213             || node.type !== type
70214             || node.name !== name
70215             || node.questionToken !== questionToken
70216             ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
70217             : node;
70218     }
70219     ts.updateMethodSignature = updateMethodSignature;
70220     function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70221         var node = createSynthesizedNode(161 /* MethodDeclaration */);
70222         node.decorators = asNodeArray(decorators);
70223         node.modifiers = asNodeArray(modifiers);
70224         node.asteriskToken = asteriskToken;
70225         node.name = asName(name);
70226         node.questionToken = questionToken;
70227         node.typeParameters = asNodeArray(typeParameters);
70228         node.parameters = createNodeArray(parameters);
70229         node.type = type;
70230         node.body = body;
70231         return node;
70232     }
70233     ts.createMethod = createMethod;
70234     function createMethodCall(object, methodName, argumentsList) {
70235         return createCall(createPropertyAccess(object, asName(methodName)), 
70236         /*typeArguments*/ undefined, argumentsList);
70237     }
70238     function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
70239         return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
70240     }
70241     /* @internal */
70242     function createObjectDefinePropertyCall(target, propertyName, attributes) {
70243         return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
70244     }
70245     ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
70246     function tryAddPropertyAssignment(properties, propertyName, expression) {
70247         if (expression) {
70248             properties.push(createPropertyAssignment(propertyName, expression));
70249             return true;
70250         }
70251         return false;
70252     }
70253     /* @internal */
70254     function createPropertyDescriptor(attributes, singleLine) {
70255         var properties = [];
70256         tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
70257         tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
70258         var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
70259         isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
70260         var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
70261         isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
70262         ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
70263         return createObjectLiteral(properties, !singleLine);
70264     }
70265     ts.createPropertyDescriptor = createPropertyDescriptor;
70266     function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70267         return node.decorators !== decorators
70268             || node.modifiers !== modifiers
70269             || node.asteriskToken !== asteriskToken
70270             || node.name !== name
70271             || node.questionToken !== questionToken
70272             || node.typeParameters !== typeParameters
70273             || node.parameters !== parameters
70274             || node.type !== type
70275             || node.body !== body
70276             ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
70277             : node;
70278     }
70279     ts.updateMethod = updateMethod;
70280     function createConstructor(decorators, modifiers, parameters, body) {
70281         var node = createSynthesizedNode(162 /* Constructor */);
70282         node.decorators = asNodeArray(decorators);
70283         node.modifiers = asNodeArray(modifiers);
70284         node.typeParameters = undefined;
70285         node.parameters = createNodeArray(parameters);
70286         node.type = undefined;
70287         node.body = body;
70288         return node;
70289     }
70290     ts.createConstructor = createConstructor;
70291     function updateConstructor(node, decorators, modifiers, parameters, body) {
70292         return node.decorators !== decorators
70293             || node.modifiers !== modifiers
70294             || node.parameters !== parameters
70295             || node.body !== body
70296             ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
70297             : node;
70298     }
70299     ts.updateConstructor = updateConstructor;
70300     function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
70301         var node = createSynthesizedNode(163 /* GetAccessor */);
70302         node.decorators = asNodeArray(decorators);
70303         node.modifiers = asNodeArray(modifiers);
70304         node.name = asName(name);
70305         node.typeParameters = undefined;
70306         node.parameters = createNodeArray(parameters);
70307         node.type = type;
70308         node.body = body;
70309         return node;
70310     }
70311     ts.createGetAccessor = createGetAccessor;
70312     function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
70313         return node.decorators !== decorators
70314             || node.modifiers !== modifiers
70315             || node.name !== name
70316             || node.parameters !== parameters
70317             || node.type !== type
70318             || node.body !== body
70319             ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
70320             : node;
70321     }
70322     ts.updateGetAccessor = updateGetAccessor;
70323     function createSetAccessor(decorators, modifiers, name, parameters, body) {
70324         var node = createSynthesizedNode(164 /* SetAccessor */);
70325         node.decorators = asNodeArray(decorators);
70326         node.modifiers = asNodeArray(modifiers);
70327         node.name = asName(name);
70328         node.typeParameters = undefined;
70329         node.parameters = createNodeArray(parameters);
70330         node.body = body;
70331         return node;
70332     }
70333     ts.createSetAccessor = createSetAccessor;
70334     function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
70335         return node.decorators !== decorators
70336             || node.modifiers !== modifiers
70337             || node.name !== name
70338             || node.parameters !== parameters
70339             || node.body !== body
70340             ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
70341             : node;
70342     }
70343     ts.updateSetAccessor = updateSetAccessor;
70344     function createCallSignature(typeParameters, parameters, type) {
70345         return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
70346     }
70347     ts.createCallSignature = createCallSignature;
70348     function updateCallSignature(node, typeParameters, parameters, type) {
70349         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70350     }
70351     ts.updateCallSignature = updateCallSignature;
70352     function createConstructSignature(typeParameters, parameters, type) {
70353         return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
70354     }
70355     ts.createConstructSignature = createConstructSignature;
70356     function updateConstructSignature(node, typeParameters, parameters, type) {
70357         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70358     }
70359     ts.updateConstructSignature = updateConstructSignature;
70360     function createIndexSignature(decorators, modifiers, parameters, type) {
70361         var node = createSynthesizedNode(167 /* IndexSignature */);
70362         node.decorators = asNodeArray(decorators);
70363         node.modifiers = asNodeArray(modifiers);
70364         node.parameters = createNodeArray(parameters);
70365         node.type = type;
70366         return node;
70367     }
70368     ts.createIndexSignature = createIndexSignature;
70369     function updateIndexSignature(node, decorators, modifiers, parameters, type) {
70370         return node.parameters !== parameters
70371             || node.type !== type
70372             || node.decorators !== decorators
70373             || node.modifiers !== modifiers
70374             ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
70375             : node;
70376     }
70377     ts.updateIndexSignature = updateIndexSignature;
70378     /* @internal */
70379     function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
70380         var node = createSynthesizedNode(kind);
70381         node.typeParameters = asNodeArray(typeParameters);
70382         node.parameters = asNodeArray(parameters);
70383         node.type = type;
70384         node.typeArguments = asNodeArray(typeArguments);
70385         return node;
70386     }
70387     ts.createSignatureDeclaration = createSignatureDeclaration;
70388     function updateSignatureDeclaration(node, typeParameters, parameters, type) {
70389         return node.typeParameters !== typeParameters
70390             || node.parameters !== parameters
70391             || node.type !== type
70392             ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
70393             : node;
70394     }
70395     // Types
70396     function createKeywordTypeNode(kind) {
70397         return createSynthesizedNode(kind);
70398     }
70399     ts.createKeywordTypeNode = createKeywordTypeNode;
70400     function createTypePredicateNode(parameterName, type) {
70401         return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
70402     }
70403     ts.createTypePredicateNode = createTypePredicateNode;
70404     function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
70405         var node = createSynthesizedNode(168 /* TypePredicate */);
70406         node.assertsModifier = assertsModifier;
70407         node.parameterName = asName(parameterName);
70408         node.type = type;
70409         return node;
70410     }
70411     ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
70412     function updateTypePredicateNode(node, parameterName, type) {
70413         return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
70414     }
70415     ts.updateTypePredicateNode = updateTypePredicateNode;
70416     function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
70417         return node.assertsModifier !== assertsModifier
70418             || node.parameterName !== parameterName
70419             || node.type !== type
70420             ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
70421             : node;
70422     }
70423     ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
70424     function createTypeReferenceNode(typeName, typeArguments) {
70425         var node = createSynthesizedNode(169 /* TypeReference */);
70426         node.typeName = asName(typeName);
70427         node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
70428         return node;
70429     }
70430     ts.createTypeReferenceNode = createTypeReferenceNode;
70431     function updateTypeReferenceNode(node, typeName, typeArguments) {
70432         return node.typeName !== typeName
70433             || node.typeArguments !== typeArguments
70434             ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
70435             : node;
70436     }
70437     ts.updateTypeReferenceNode = updateTypeReferenceNode;
70438     function createFunctionTypeNode(typeParameters, parameters, type) {
70439         return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
70440     }
70441     ts.createFunctionTypeNode = createFunctionTypeNode;
70442     function updateFunctionTypeNode(node, typeParameters, parameters, type) {
70443         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70444     }
70445     ts.updateFunctionTypeNode = updateFunctionTypeNode;
70446     function createConstructorTypeNode(typeParameters, parameters, type) {
70447         return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
70448     }
70449     ts.createConstructorTypeNode = createConstructorTypeNode;
70450     function updateConstructorTypeNode(node, typeParameters, parameters, type) {
70451         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70452     }
70453     ts.updateConstructorTypeNode = updateConstructorTypeNode;
70454     function createTypeQueryNode(exprName) {
70455         var node = createSynthesizedNode(172 /* TypeQuery */);
70456         node.exprName = exprName;
70457         return node;
70458     }
70459     ts.createTypeQueryNode = createTypeQueryNode;
70460     function updateTypeQueryNode(node, exprName) {
70461         return node.exprName !== exprName
70462             ? updateNode(createTypeQueryNode(exprName), node)
70463             : node;
70464     }
70465     ts.updateTypeQueryNode = updateTypeQueryNode;
70466     function createTypeLiteralNode(members) {
70467         var node = createSynthesizedNode(173 /* TypeLiteral */);
70468         node.members = createNodeArray(members);
70469         return node;
70470     }
70471     ts.createTypeLiteralNode = createTypeLiteralNode;
70472     function updateTypeLiteralNode(node, members) {
70473         return node.members !== members
70474             ? updateNode(createTypeLiteralNode(members), node)
70475             : node;
70476     }
70477     ts.updateTypeLiteralNode = updateTypeLiteralNode;
70478     function createArrayTypeNode(elementType) {
70479         var node = createSynthesizedNode(174 /* ArrayType */);
70480         node.elementType = ts.parenthesizeArrayTypeMember(elementType);
70481         return node;
70482     }
70483     ts.createArrayTypeNode = createArrayTypeNode;
70484     function updateArrayTypeNode(node, elementType) {
70485         return node.elementType !== elementType
70486             ? updateNode(createArrayTypeNode(elementType), node)
70487             : node;
70488     }
70489     ts.updateArrayTypeNode = updateArrayTypeNode;
70490     function createTupleTypeNode(elementTypes) {
70491         var node = createSynthesizedNode(175 /* TupleType */);
70492         node.elementTypes = createNodeArray(elementTypes);
70493         return node;
70494     }
70495     ts.createTupleTypeNode = createTupleTypeNode;
70496     function updateTupleTypeNode(node, elementTypes) {
70497         return node.elementTypes !== elementTypes
70498             ? updateNode(createTupleTypeNode(elementTypes), node)
70499             : node;
70500     }
70501     ts.updateTupleTypeNode = updateTupleTypeNode;
70502     function createOptionalTypeNode(type) {
70503         var node = createSynthesizedNode(176 /* OptionalType */);
70504         node.type = ts.parenthesizeArrayTypeMember(type);
70505         return node;
70506     }
70507     ts.createOptionalTypeNode = createOptionalTypeNode;
70508     function updateOptionalTypeNode(node, type) {
70509         return node.type !== type
70510             ? updateNode(createOptionalTypeNode(type), node)
70511             : node;
70512     }
70513     ts.updateOptionalTypeNode = updateOptionalTypeNode;
70514     function createRestTypeNode(type) {
70515         var node = createSynthesizedNode(177 /* RestType */);
70516         node.type = type;
70517         return node;
70518     }
70519     ts.createRestTypeNode = createRestTypeNode;
70520     function updateRestTypeNode(node, type) {
70521         return node.type !== type
70522             ? updateNode(createRestTypeNode(type), node)
70523             : node;
70524     }
70525     ts.updateRestTypeNode = updateRestTypeNode;
70526     function createUnionTypeNode(types) {
70527         return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
70528     }
70529     ts.createUnionTypeNode = createUnionTypeNode;
70530     function updateUnionTypeNode(node, types) {
70531         return updateUnionOrIntersectionTypeNode(node, types);
70532     }
70533     ts.updateUnionTypeNode = updateUnionTypeNode;
70534     function createIntersectionTypeNode(types) {
70535         return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
70536     }
70537     ts.createIntersectionTypeNode = createIntersectionTypeNode;
70538     function updateIntersectionTypeNode(node, types) {
70539         return updateUnionOrIntersectionTypeNode(node, types);
70540     }
70541     ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
70542     function createUnionOrIntersectionTypeNode(kind, types) {
70543         var node = createSynthesizedNode(kind);
70544         node.types = ts.parenthesizeElementTypeMembers(types);
70545         return node;
70546     }
70547     ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
70548     function updateUnionOrIntersectionTypeNode(node, types) {
70549         return node.types !== types
70550             ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
70551             : node;
70552     }
70553     function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
70554         var node = createSynthesizedNode(180 /* ConditionalType */);
70555         node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
70556         node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
70557         node.trueType = trueType;
70558         node.falseType = falseType;
70559         return node;
70560     }
70561     ts.createConditionalTypeNode = createConditionalTypeNode;
70562     function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
70563         return node.checkType !== checkType
70564             || node.extendsType !== extendsType
70565             || node.trueType !== trueType
70566             || node.falseType !== falseType
70567             ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
70568             : node;
70569     }
70570     ts.updateConditionalTypeNode = updateConditionalTypeNode;
70571     function createInferTypeNode(typeParameter) {
70572         var node = createSynthesizedNode(181 /* InferType */);
70573         node.typeParameter = typeParameter;
70574         return node;
70575     }
70576     ts.createInferTypeNode = createInferTypeNode;
70577     function updateInferTypeNode(node, typeParameter) {
70578         return node.typeParameter !== typeParameter
70579             ? updateNode(createInferTypeNode(typeParameter), node)
70580             : node;
70581     }
70582     ts.updateInferTypeNode = updateInferTypeNode;
70583     function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
70584         var node = createSynthesizedNode(188 /* ImportType */);
70585         node.argument = argument;
70586         node.qualifier = qualifier;
70587         node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
70588         node.isTypeOf = isTypeOf;
70589         return node;
70590     }
70591     ts.createImportTypeNode = createImportTypeNode;
70592     function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
70593         return node.argument !== argument
70594             || node.qualifier !== qualifier
70595             || node.typeArguments !== typeArguments
70596             || node.isTypeOf !== isTypeOf
70597             ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
70598             : node;
70599     }
70600     ts.updateImportTypeNode = updateImportTypeNode;
70601     function createParenthesizedType(type) {
70602         var node = createSynthesizedNode(182 /* ParenthesizedType */);
70603         node.type = type;
70604         return node;
70605     }
70606     ts.createParenthesizedType = createParenthesizedType;
70607     function updateParenthesizedType(node, type) {
70608         return node.type !== type
70609             ? updateNode(createParenthesizedType(type), node)
70610             : node;
70611     }
70612     ts.updateParenthesizedType = updateParenthesizedType;
70613     function createThisTypeNode() {
70614         return createSynthesizedNode(183 /* ThisType */);
70615     }
70616     ts.createThisTypeNode = createThisTypeNode;
70617     function createTypeOperatorNode(operatorOrType, type) {
70618         var node = createSynthesizedNode(184 /* TypeOperator */);
70619         node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
70620         node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
70621         return node;
70622     }
70623     ts.createTypeOperatorNode = createTypeOperatorNode;
70624     function updateTypeOperatorNode(node, type) {
70625         return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
70626     }
70627     ts.updateTypeOperatorNode = updateTypeOperatorNode;
70628     function createIndexedAccessTypeNode(objectType, indexType) {
70629         var node = createSynthesizedNode(185 /* IndexedAccessType */);
70630         node.objectType = ts.parenthesizeElementTypeMember(objectType);
70631         node.indexType = indexType;
70632         return node;
70633     }
70634     ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
70635     function updateIndexedAccessTypeNode(node, objectType, indexType) {
70636         return node.objectType !== objectType
70637             || node.indexType !== indexType
70638             ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
70639             : node;
70640     }
70641     ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
70642     function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
70643         var node = createSynthesizedNode(186 /* MappedType */);
70644         node.readonlyToken = readonlyToken;
70645         node.typeParameter = typeParameter;
70646         node.questionToken = questionToken;
70647         node.type = type;
70648         return node;
70649     }
70650     ts.createMappedTypeNode = createMappedTypeNode;
70651     function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
70652         return node.readonlyToken !== readonlyToken
70653             || node.typeParameter !== typeParameter
70654             || node.questionToken !== questionToken
70655             || node.type !== type
70656             ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
70657             : node;
70658     }
70659     ts.updateMappedTypeNode = updateMappedTypeNode;
70660     function createLiteralTypeNode(literal) {
70661         var node = createSynthesizedNode(187 /* LiteralType */);
70662         node.literal = literal;
70663         return node;
70664     }
70665     ts.createLiteralTypeNode = createLiteralTypeNode;
70666     function updateLiteralTypeNode(node, literal) {
70667         return node.literal !== literal
70668             ? updateNode(createLiteralTypeNode(literal), node)
70669             : node;
70670     }
70671     ts.updateLiteralTypeNode = updateLiteralTypeNode;
70672     // Binding Patterns
70673     function createObjectBindingPattern(elements) {
70674         var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
70675         node.elements = createNodeArray(elements);
70676         return node;
70677     }
70678     ts.createObjectBindingPattern = createObjectBindingPattern;
70679     function updateObjectBindingPattern(node, elements) {
70680         return node.elements !== elements
70681             ? updateNode(createObjectBindingPattern(elements), node)
70682             : node;
70683     }
70684     ts.updateObjectBindingPattern = updateObjectBindingPattern;
70685     function createArrayBindingPattern(elements) {
70686         var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
70687         node.elements = createNodeArray(elements);
70688         return node;
70689     }
70690     ts.createArrayBindingPattern = createArrayBindingPattern;
70691     function updateArrayBindingPattern(node, elements) {
70692         return node.elements !== elements
70693             ? updateNode(createArrayBindingPattern(elements), node)
70694             : node;
70695     }
70696     ts.updateArrayBindingPattern = updateArrayBindingPattern;
70697     function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
70698         var node = createSynthesizedNode(191 /* BindingElement */);
70699         node.dotDotDotToken = dotDotDotToken;
70700         node.propertyName = asName(propertyName);
70701         node.name = asName(name);
70702         node.initializer = initializer;
70703         return node;
70704     }
70705     ts.createBindingElement = createBindingElement;
70706     function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
70707         return node.propertyName !== propertyName
70708             || node.dotDotDotToken !== dotDotDotToken
70709             || node.name !== name
70710             || node.initializer !== initializer
70711             ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
70712             : node;
70713     }
70714     ts.updateBindingElement = updateBindingElement;
70715     // Expression
70716     function createArrayLiteral(elements, multiLine) {
70717         var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
70718         node.elements = ts.parenthesizeListElements(createNodeArray(elements));
70719         if (multiLine)
70720             node.multiLine = true;
70721         return node;
70722     }
70723     ts.createArrayLiteral = createArrayLiteral;
70724     function updateArrayLiteral(node, elements) {
70725         return node.elements !== elements
70726             ? updateNode(createArrayLiteral(elements, node.multiLine), node)
70727             : node;
70728     }
70729     ts.updateArrayLiteral = updateArrayLiteral;
70730     function createObjectLiteral(properties, multiLine) {
70731         var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
70732         node.properties = createNodeArray(properties);
70733         if (multiLine)
70734             node.multiLine = true;
70735         return node;
70736     }
70737     ts.createObjectLiteral = createObjectLiteral;
70738     function updateObjectLiteral(node, properties) {
70739         return node.properties !== properties
70740             ? updateNode(createObjectLiteral(properties, node.multiLine), node)
70741             : node;
70742     }
70743     ts.updateObjectLiteral = updateObjectLiteral;
70744     function createPropertyAccess(expression, name) {
70745         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70746         node.expression = ts.parenthesizeForAccess(expression);
70747         node.name = asName(name);
70748         setEmitFlags(node, 131072 /* NoIndentation */);
70749         return node;
70750     }
70751     ts.createPropertyAccess = createPropertyAccess;
70752     function updatePropertyAccess(node, expression, name) {
70753         if (ts.isPropertyAccessChain(node)) {
70754             return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
70755         }
70756         // Because we are updating existed propertyAccess we want to inherit its emitFlags
70757         // instead of using the default from createPropertyAccess
70758         return node.expression !== expression
70759             || node.name !== name
70760             ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
70761             : node;
70762     }
70763     ts.updatePropertyAccess = updatePropertyAccess;
70764     function createPropertyAccessChain(expression, questionDotToken, name) {
70765         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70766         node.flags |= 32 /* OptionalChain */;
70767         node.expression = ts.parenthesizeForAccess(expression);
70768         node.questionDotToken = questionDotToken;
70769         node.name = asName(name);
70770         setEmitFlags(node, 131072 /* NoIndentation */);
70771         return node;
70772     }
70773     ts.createPropertyAccessChain = createPropertyAccessChain;
70774     function updatePropertyAccessChain(node, expression, questionDotToken, name) {
70775         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
70776         // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
70777         // instead of using the default from createPropertyAccess
70778         return node.expression !== expression
70779             || node.questionDotToken !== questionDotToken
70780             || node.name !== name
70781             ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
70782             : node;
70783     }
70784     ts.updatePropertyAccessChain = updatePropertyAccessChain;
70785     function createElementAccess(expression, index) {
70786         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70787         node.expression = ts.parenthesizeForAccess(expression);
70788         node.argumentExpression = asExpression(index);
70789         return node;
70790     }
70791     ts.createElementAccess = createElementAccess;
70792     function updateElementAccess(node, expression, argumentExpression) {
70793         if (ts.isOptionalChain(node)) {
70794             return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
70795         }
70796         return node.expression !== expression
70797             || node.argumentExpression !== argumentExpression
70798             ? updateNode(createElementAccess(expression, argumentExpression), node)
70799             : node;
70800     }
70801     ts.updateElementAccess = updateElementAccess;
70802     function createElementAccessChain(expression, questionDotToken, index) {
70803         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70804         node.flags |= 32 /* OptionalChain */;
70805         node.expression = ts.parenthesizeForAccess(expression);
70806         node.questionDotToken = questionDotToken;
70807         node.argumentExpression = asExpression(index);
70808         return node;
70809     }
70810     ts.createElementAccessChain = createElementAccessChain;
70811     function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
70812         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
70813         return node.expression !== expression
70814             || node.questionDotToken !== questionDotToken
70815             || node.argumentExpression !== argumentExpression
70816             ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
70817             : node;
70818     }
70819     ts.updateElementAccessChain = updateElementAccessChain;
70820     function createCall(expression, typeArguments, argumentsArray) {
70821         var node = createSynthesizedNode(196 /* CallExpression */);
70822         node.expression = ts.parenthesizeForAccess(expression);
70823         node.typeArguments = asNodeArray(typeArguments);
70824         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70825         return node;
70826     }
70827     ts.createCall = createCall;
70828     function updateCall(node, expression, typeArguments, argumentsArray) {
70829         if (ts.isOptionalChain(node)) {
70830             return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
70831         }
70832         return node.expression !== expression
70833             || node.typeArguments !== typeArguments
70834             || node.arguments !== argumentsArray
70835             ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
70836             : node;
70837     }
70838     ts.updateCall = updateCall;
70839     function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
70840         var node = createSynthesizedNode(196 /* CallExpression */);
70841         node.flags |= 32 /* OptionalChain */;
70842         node.expression = ts.parenthesizeForAccess(expression);
70843         node.questionDotToken = questionDotToken;
70844         node.typeArguments = asNodeArray(typeArguments);
70845         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70846         return node;
70847     }
70848     ts.createCallChain = createCallChain;
70849     function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
70850         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
70851         return node.expression !== expression
70852             || node.questionDotToken !== questionDotToken
70853             || node.typeArguments !== typeArguments
70854             || node.arguments !== argumentsArray
70855             ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
70856             : node;
70857     }
70858     ts.updateCallChain = updateCallChain;
70859     function createNew(expression, typeArguments, argumentsArray) {
70860         var node = createSynthesizedNode(197 /* NewExpression */);
70861         node.expression = ts.parenthesizeForNew(expression);
70862         node.typeArguments = asNodeArray(typeArguments);
70863         node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
70864         return node;
70865     }
70866     ts.createNew = createNew;
70867     function updateNew(node, expression, typeArguments, argumentsArray) {
70868         return node.expression !== expression
70869             || node.typeArguments !== typeArguments
70870             || node.arguments !== argumentsArray
70871             ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
70872             : node;
70873     }
70874     ts.updateNew = updateNew;
70875     function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
70876         var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
70877         node.tag = ts.parenthesizeForAccess(tag);
70878         if (template) {
70879             node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
70880             node.template = template;
70881         }
70882         else {
70883             node.typeArguments = undefined;
70884             node.template = typeArgumentsOrTemplate;
70885         }
70886         return node;
70887     }
70888     ts.createTaggedTemplate = createTaggedTemplate;
70889     function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
70890         return node.tag !== tag
70891             || (template
70892                 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
70893                 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
70894             ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
70895             : node;
70896     }
70897     ts.updateTaggedTemplate = updateTaggedTemplate;
70898     function createTypeAssertion(type, expression) {
70899         var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
70900         node.type = type;
70901         node.expression = ts.parenthesizePrefixOperand(expression);
70902         return node;
70903     }
70904     ts.createTypeAssertion = createTypeAssertion;
70905     function updateTypeAssertion(node, type, expression) {
70906         return node.type !== type
70907             || node.expression !== expression
70908             ? updateNode(createTypeAssertion(type, expression), node)
70909             : node;
70910     }
70911     ts.updateTypeAssertion = updateTypeAssertion;
70912     function createParen(expression) {
70913         var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
70914         node.expression = expression;
70915         return node;
70916     }
70917     ts.createParen = createParen;
70918     function updateParen(node, expression) {
70919         return node.expression !== expression
70920             ? updateNode(createParen(expression), node)
70921             : node;
70922     }
70923     ts.updateParen = updateParen;
70924     function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70925         var node = createSynthesizedNode(201 /* FunctionExpression */);
70926         node.modifiers = asNodeArray(modifiers);
70927         node.asteriskToken = asteriskToken;
70928         node.name = asName(name);
70929         node.typeParameters = asNodeArray(typeParameters);
70930         node.parameters = createNodeArray(parameters);
70931         node.type = type;
70932         node.body = body;
70933         return node;
70934     }
70935     ts.createFunctionExpression = createFunctionExpression;
70936     function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70937         return node.name !== name
70938             || node.modifiers !== modifiers
70939             || node.asteriskToken !== asteriskToken
70940             || node.typeParameters !== typeParameters
70941             || node.parameters !== parameters
70942             || node.type !== type
70943             || node.body !== body
70944             ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
70945             : node;
70946     }
70947     ts.updateFunctionExpression = updateFunctionExpression;
70948     function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70949         var node = createSynthesizedNode(202 /* ArrowFunction */);
70950         node.modifiers = asNodeArray(modifiers);
70951         node.typeParameters = asNodeArray(typeParameters);
70952         node.parameters = createNodeArray(parameters);
70953         node.type = type;
70954         node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
70955         node.body = ts.parenthesizeConciseBody(body);
70956         return node;
70957     }
70958     ts.createArrowFunction = createArrowFunction;
70959     function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70960         return node.modifiers !== modifiers
70961             || node.typeParameters !== typeParameters
70962             || node.parameters !== parameters
70963             || node.type !== type
70964             || node.equalsGreaterThanToken !== equalsGreaterThanToken
70965             || node.body !== body
70966             ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
70967             : node;
70968     }
70969     ts.updateArrowFunction = updateArrowFunction;
70970     function createDelete(expression) {
70971         var node = createSynthesizedNode(203 /* DeleteExpression */);
70972         node.expression = ts.parenthesizePrefixOperand(expression);
70973         return node;
70974     }
70975     ts.createDelete = createDelete;
70976     function updateDelete(node, expression) {
70977         return node.expression !== expression
70978             ? updateNode(createDelete(expression), node)
70979             : node;
70980     }
70981     ts.updateDelete = updateDelete;
70982     function createTypeOf(expression) {
70983         var node = createSynthesizedNode(204 /* TypeOfExpression */);
70984         node.expression = ts.parenthesizePrefixOperand(expression);
70985         return node;
70986     }
70987     ts.createTypeOf = createTypeOf;
70988     function updateTypeOf(node, expression) {
70989         return node.expression !== expression
70990             ? updateNode(createTypeOf(expression), node)
70991             : node;
70992     }
70993     ts.updateTypeOf = updateTypeOf;
70994     function createVoid(expression) {
70995         var node = createSynthesizedNode(205 /* VoidExpression */);
70996         node.expression = ts.parenthesizePrefixOperand(expression);
70997         return node;
70998     }
70999     ts.createVoid = createVoid;
71000     function updateVoid(node, expression) {
71001         return node.expression !== expression
71002             ? updateNode(createVoid(expression), node)
71003             : node;
71004     }
71005     ts.updateVoid = updateVoid;
71006     function createAwait(expression) {
71007         var node = createSynthesizedNode(206 /* AwaitExpression */);
71008         node.expression = ts.parenthesizePrefixOperand(expression);
71009         return node;
71010     }
71011     ts.createAwait = createAwait;
71012     function updateAwait(node, expression) {
71013         return node.expression !== expression
71014             ? updateNode(createAwait(expression), node)
71015             : node;
71016     }
71017     ts.updateAwait = updateAwait;
71018     function createPrefix(operator, operand) {
71019         var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
71020         node.operator = operator;
71021         node.operand = ts.parenthesizePrefixOperand(operand);
71022         return node;
71023     }
71024     ts.createPrefix = createPrefix;
71025     function updatePrefix(node, operand) {
71026         return node.operand !== operand
71027             ? updateNode(createPrefix(node.operator, operand), node)
71028             : node;
71029     }
71030     ts.updatePrefix = updatePrefix;
71031     function createPostfix(operand, operator) {
71032         var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
71033         node.operand = ts.parenthesizePostfixOperand(operand);
71034         node.operator = operator;
71035         return node;
71036     }
71037     ts.createPostfix = createPostfix;
71038     function updatePostfix(node, operand) {
71039         return node.operand !== operand
71040             ? updateNode(createPostfix(operand, node.operator), node)
71041             : node;
71042     }
71043     ts.updatePostfix = updatePostfix;
71044     function createBinary(left, operator, right) {
71045         var node = createSynthesizedNode(209 /* BinaryExpression */);
71046         var operatorToken = asToken(operator);
71047         var operatorKind = operatorToken.kind;
71048         node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
71049         node.operatorToken = operatorToken;
71050         node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
71051         return node;
71052     }
71053     ts.createBinary = createBinary;
71054     function updateBinary(node, left, right, operator) {
71055         return node.left !== left
71056             || node.right !== right
71057             ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
71058             : node;
71059     }
71060     ts.updateBinary = updateBinary;
71061     function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
71062         var node = createSynthesizedNode(210 /* ConditionalExpression */);
71063         node.condition = ts.parenthesizeForConditionalHead(condition);
71064         node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
71065         node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
71066         node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
71067         node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
71068         return node;
71069     }
71070     ts.createConditional = createConditional;
71071     function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
71072         return node.condition !== condition
71073             || node.questionToken !== questionToken
71074             || node.whenTrue !== whenTrue
71075             || node.colonToken !== colonToken
71076             || node.whenFalse !== whenFalse
71077             ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
71078             : node;
71079     }
71080     ts.updateConditional = updateConditional;
71081     function createTemplateExpression(head, templateSpans) {
71082         var node = createSynthesizedNode(211 /* TemplateExpression */);
71083         node.head = head;
71084         node.templateSpans = createNodeArray(templateSpans);
71085         return node;
71086     }
71087     ts.createTemplateExpression = createTemplateExpression;
71088     function updateTemplateExpression(node, head, templateSpans) {
71089         return node.head !== head
71090             || node.templateSpans !== templateSpans
71091             ? updateNode(createTemplateExpression(head, templateSpans), node)
71092             : node;
71093     }
71094     ts.updateTemplateExpression = updateTemplateExpression;
71095     var rawTextScanner;
71096     var invalidValueSentinel = {};
71097     function getCookedText(kind, rawText) {
71098         if (!rawTextScanner) {
71099             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
71100         }
71101         switch (kind) {
71102             case 14 /* NoSubstitutionTemplateLiteral */:
71103                 rawTextScanner.setText("`" + rawText + "`");
71104                 break;
71105             case 15 /* TemplateHead */:
71106                 rawTextScanner.setText("`" + rawText + "${");
71107                 break;
71108             case 16 /* TemplateMiddle */:
71109                 rawTextScanner.setText("}" + rawText + "${");
71110                 break;
71111             case 17 /* TemplateTail */:
71112                 rawTextScanner.setText("}" + rawText + "`");
71113                 break;
71114         }
71115         var token = rawTextScanner.scan();
71116         if (token === 23 /* CloseBracketToken */) {
71117             token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
71118         }
71119         if (rawTextScanner.isUnterminated()) {
71120             rawTextScanner.setText(undefined);
71121             return invalidValueSentinel;
71122         }
71123         var tokenValue;
71124         switch (token) {
71125             case 14 /* NoSubstitutionTemplateLiteral */:
71126             case 15 /* TemplateHead */:
71127             case 16 /* TemplateMiddle */:
71128             case 17 /* TemplateTail */:
71129                 tokenValue = rawTextScanner.getTokenValue();
71130                 break;
71131         }
71132         if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
71133             rawTextScanner.setText(undefined);
71134             return invalidValueSentinel;
71135         }
71136         rawTextScanner.setText(undefined);
71137         return tokenValue;
71138     }
71139     function createTemplateLiteralLikeNode(kind, text, rawText) {
71140         var node = createSynthesizedNode(kind);
71141         node.text = text;
71142         if (rawText === undefined || text === rawText) {
71143             node.rawText = rawText;
71144         }
71145         else {
71146             var cooked = getCookedText(kind, rawText);
71147             if (typeof cooked === "object") {
71148                 return ts.Debug.fail("Invalid raw text");
71149             }
71150             ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
71151             node.rawText = rawText;
71152         }
71153         return node;
71154     }
71155     function createTemplateHead(text, rawText) {
71156         var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
71157         node.text = text;
71158         return node;
71159     }
71160     ts.createTemplateHead = createTemplateHead;
71161     function createTemplateMiddle(text, rawText) {
71162         var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
71163         node.text = text;
71164         return node;
71165     }
71166     ts.createTemplateMiddle = createTemplateMiddle;
71167     function createTemplateTail(text, rawText) {
71168         var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
71169         node.text = text;
71170         return node;
71171     }
71172     ts.createTemplateTail = createTemplateTail;
71173     function createNoSubstitutionTemplateLiteral(text, rawText) {
71174         var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
71175         return node;
71176     }
71177     ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
71178     function createYield(asteriskTokenOrExpression, expression) {
71179         var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
71180         expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
71181         var node = createSynthesizedNode(212 /* YieldExpression */);
71182         node.asteriskToken = asteriskToken;
71183         node.expression = expression && ts.parenthesizeExpressionForList(expression);
71184         return node;
71185     }
71186     ts.createYield = createYield;
71187     function updateYield(node, asteriskToken, expression) {
71188         return node.expression !== expression
71189             || node.asteriskToken !== asteriskToken
71190             ? updateNode(createYield(asteriskToken, expression), node)
71191             : node;
71192     }
71193     ts.updateYield = updateYield;
71194     function createSpread(expression) {
71195         var node = createSynthesizedNode(213 /* SpreadElement */);
71196         node.expression = ts.parenthesizeExpressionForList(expression);
71197         return node;
71198     }
71199     ts.createSpread = createSpread;
71200     function updateSpread(node, expression) {
71201         return node.expression !== expression
71202             ? updateNode(createSpread(expression), node)
71203             : node;
71204     }
71205     ts.updateSpread = updateSpread;
71206     function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
71207         var node = createSynthesizedNode(214 /* ClassExpression */);
71208         node.decorators = undefined;
71209         node.modifiers = asNodeArray(modifiers);
71210         node.name = asName(name);
71211         node.typeParameters = asNodeArray(typeParameters);
71212         node.heritageClauses = asNodeArray(heritageClauses);
71213         node.members = createNodeArray(members);
71214         return node;
71215     }
71216     ts.createClassExpression = createClassExpression;
71217     function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
71218         return node.modifiers !== modifiers
71219             || node.name !== name
71220             || node.typeParameters !== typeParameters
71221             || node.heritageClauses !== heritageClauses
71222             || node.members !== members
71223             ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
71224             : node;
71225     }
71226     ts.updateClassExpression = updateClassExpression;
71227     function createOmittedExpression() {
71228         return createSynthesizedNode(215 /* OmittedExpression */);
71229     }
71230     ts.createOmittedExpression = createOmittedExpression;
71231     function createExpressionWithTypeArguments(typeArguments, expression) {
71232         var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
71233         node.expression = ts.parenthesizeForAccess(expression);
71234         node.typeArguments = asNodeArray(typeArguments);
71235         return node;
71236     }
71237     ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
71238     function updateExpressionWithTypeArguments(node, typeArguments, expression) {
71239         return node.typeArguments !== typeArguments
71240             || node.expression !== expression
71241             ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
71242             : node;
71243     }
71244     ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
71245     function createAsExpression(expression, type) {
71246         var node = createSynthesizedNode(217 /* AsExpression */);
71247         node.expression = expression;
71248         node.type = type;
71249         return node;
71250     }
71251     ts.createAsExpression = createAsExpression;
71252     function updateAsExpression(node, expression, type) {
71253         return node.expression !== expression
71254             || node.type !== type
71255             ? updateNode(createAsExpression(expression, type), node)
71256             : node;
71257     }
71258     ts.updateAsExpression = updateAsExpression;
71259     function createNonNullExpression(expression) {
71260         var node = createSynthesizedNode(218 /* NonNullExpression */);
71261         node.expression = ts.parenthesizeForAccess(expression);
71262         return node;
71263     }
71264     ts.createNonNullExpression = createNonNullExpression;
71265     function updateNonNullExpression(node, expression) {
71266         if (ts.isNonNullChain(node)) {
71267             return updateNonNullChain(node, expression);
71268         }
71269         return node.expression !== expression
71270             ? updateNode(createNonNullExpression(expression), node)
71271             : node;
71272     }
71273     ts.updateNonNullExpression = updateNonNullExpression;
71274     function createNonNullChain(expression) {
71275         var node = createSynthesizedNode(218 /* NonNullExpression */);
71276         node.flags |= 32 /* OptionalChain */;
71277         node.expression = ts.parenthesizeForAccess(expression);
71278         return node;
71279     }
71280     ts.createNonNullChain = createNonNullChain;
71281     function updateNonNullChain(node, expression) {
71282         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
71283         return node.expression !== expression
71284             ? updateNode(createNonNullChain(expression), node)
71285             : node;
71286     }
71287     ts.updateNonNullChain = updateNonNullChain;
71288     function createMetaProperty(keywordToken, name) {
71289         var node = createSynthesizedNode(219 /* MetaProperty */);
71290         node.keywordToken = keywordToken;
71291         node.name = name;
71292         return node;
71293     }
71294     ts.createMetaProperty = createMetaProperty;
71295     function updateMetaProperty(node, name) {
71296         return node.name !== name
71297             ? updateNode(createMetaProperty(node.keywordToken, name), node)
71298             : node;
71299     }
71300     ts.updateMetaProperty = updateMetaProperty;
71301     // Misc
71302     function createTemplateSpan(expression, literal) {
71303         var node = createSynthesizedNode(221 /* TemplateSpan */);
71304         node.expression = expression;
71305         node.literal = literal;
71306         return node;
71307     }
71308     ts.createTemplateSpan = createTemplateSpan;
71309     function updateTemplateSpan(node, expression, literal) {
71310         return node.expression !== expression
71311             || node.literal !== literal
71312             ? updateNode(createTemplateSpan(expression, literal), node)
71313             : node;
71314     }
71315     ts.updateTemplateSpan = updateTemplateSpan;
71316     function createSemicolonClassElement() {
71317         return createSynthesizedNode(222 /* SemicolonClassElement */);
71318     }
71319     ts.createSemicolonClassElement = createSemicolonClassElement;
71320     // Element
71321     function createBlock(statements, multiLine) {
71322         var block = createSynthesizedNode(223 /* Block */);
71323         block.statements = createNodeArray(statements);
71324         if (multiLine)
71325             block.multiLine = multiLine;
71326         return block;
71327     }
71328     ts.createBlock = createBlock;
71329     function updateBlock(node, statements) {
71330         return node.statements !== statements
71331             ? updateNode(createBlock(statements, node.multiLine), node)
71332             : node;
71333     }
71334     ts.updateBlock = updateBlock;
71335     function createVariableStatement(modifiers, declarationList) {
71336         var node = createSynthesizedNode(225 /* VariableStatement */);
71337         node.decorators = undefined;
71338         node.modifiers = asNodeArray(modifiers);
71339         node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
71340         return node;
71341     }
71342     ts.createVariableStatement = createVariableStatement;
71343     function updateVariableStatement(node, modifiers, declarationList) {
71344         return node.modifiers !== modifiers
71345             || node.declarationList !== declarationList
71346             ? updateNode(createVariableStatement(modifiers, declarationList), node)
71347             : node;
71348     }
71349     ts.updateVariableStatement = updateVariableStatement;
71350     function createEmptyStatement() {
71351         return createSynthesizedNode(224 /* EmptyStatement */);
71352     }
71353     ts.createEmptyStatement = createEmptyStatement;
71354     function createExpressionStatement(expression) {
71355         var node = createSynthesizedNode(226 /* ExpressionStatement */);
71356         node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
71357         return node;
71358     }
71359     ts.createExpressionStatement = createExpressionStatement;
71360     function updateExpressionStatement(node, expression) {
71361         return node.expression !== expression
71362             ? updateNode(createExpressionStatement(expression), node)
71363             : node;
71364     }
71365     ts.updateExpressionStatement = updateExpressionStatement;
71366     /** @deprecated Use `createExpressionStatement` instead.  */
71367     ts.createStatement = createExpressionStatement;
71368     /** @deprecated Use `updateExpressionStatement` instead.  */
71369     ts.updateStatement = updateExpressionStatement;
71370     function createIf(expression, thenStatement, elseStatement) {
71371         var node = createSynthesizedNode(227 /* IfStatement */);
71372         node.expression = expression;
71373         node.thenStatement = asEmbeddedStatement(thenStatement);
71374         node.elseStatement = asEmbeddedStatement(elseStatement);
71375         return node;
71376     }
71377     ts.createIf = createIf;
71378     function updateIf(node, expression, thenStatement, elseStatement) {
71379         return node.expression !== expression
71380             || node.thenStatement !== thenStatement
71381             || node.elseStatement !== elseStatement
71382             ? updateNode(createIf(expression, thenStatement, elseStatement), node)
71383             : node;
71384     }
71385     ts.updateIf = updateIf;
71386     function createDo(statement, expression) {
71387         var node = createSynthesizedNode(228 /* DoStatement */);
71388         node.statement = asEmbeddedStatement(statement);
71389         node.expression = expression;
71390         return node;
71391     }
71392     ts.createDo = createDo;
71393     function updateDo(node, statement, expression) {
71394         return node.statement !== statement
71395             || node.expression !== expression
71396             ? updateNode(createDo(statement, expression), node)
71397             : node;
71398     }
71399     ts.updateDo = updateDo;
71400     function createWhile(expression, statement) {
71401         var node = createSynthesizedNode(229 /* WhileStatement */);
71402         node.expression = expression;
71403         node.statement = asEmbeddedStatement(statement);
71404         return node;
71405     }
71406     ts.createWhile = createWhile;
71407     function updateWhile(node, expression, statement) {
71408         return node.expression !== expression
71409             || node.statement !== statement
71410             ? updateNode(createWhile(expression, statement), node)
71411             : node;
71412     }
71413     ts.updateWhile = updateWhile;
71414     function createFor(initializer, condition, incrementor, statement) {
71415         var node = createSynthesizedNode(230 /* ForStatement */);
71416         node.initializer = initializer;
71417         node.condition = condition;
71418         node.incrementor = incrementor;
71419         node.statement = asEmbeddedStatement(statement);
71420         return node;
71421     }
71422     ts.createFor = createFor;
71423     function updateFor(node, initializer, condition, incrementor, statement) {
71424         return node.initializer !== initializer
71425             || node.condition !== condition
71426             || node.incrementor !== incrementor
71427             || node.statement !== statement
71428             ? updateNode(createFor(initializer, condition, incrementor, statement), node)
71429             : node;
71430     }
71431     ts.updateFor = updateFor;
71432     function createForIn(initializer, expression, statement) {
71433         var node = createSynthesizedNode(231 /* ForInStatement */);
71434         node.initializer = initializer;
71435         node.expression = expression;
71436         node.statement = asEmbeddedStatement(statement);
71437         return node;
71438     }
71439     ts.createForIn = createForIn;
71440     function updateForIn(node, initializer, expression, statement) {
71441         return node.initializer !== initializer
71442             || node.expression !== expression
71443             || node.statement !== statement
71444             ? updateNode(createForIn(initializer, expression, statement), node)
71445             : node;
71446     }
71447     ts.updateForIn = updateForIn;
71448     function createForOf(awaitModifier, initializer, expression, statement) {
71449         var node = createSynthesizedNode(232 /* ForOfStatement */);
71450         node.awaitModifier = awaitModifier;
71451         node.initializer = initializer;
71452         node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
71453         node.statement = asEmbeddedStatement(statement);
71454         return node;
71455     }
71456     ts.createForOf = createForOf;
71457     function updateForOf(node, awaitModifier, initializer, expression, statement) {
71458         return node.awaitModifier !== awaitModifier
71459             || node.initializer !== initializer
71460             || node.expression !== expression
71461             || node.statement !== statement
71462             ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
71463             : node;
71464     }
71465     ts.updateForOf = updateForOf;
71466     function createContinue(label) {
71467         var node = createSynthesizedNode(233 /* ContinueStatement */);
71468         node.label = asName(label);
71469         return node;
71470     }
71471     ts.createContinue = createContinue;
71472     function updateContinue(node, label) {
71473         return node.label !== label
71474             ? updateNode(createContinue(label), node)
71475             : node;
71476     }
71477     ts.updateContinue = updateContinue;
71478     function createBreak(label) {
71479         var node = createSynthesizedNode(234 /* BreakStatement */);
71480         node.label = asName(label);
71481         return node;
71482     }
71483     ts.createBreak = createBreak;
71484     function updateBreak(node, label) {
71485         return node.label !== label
71486             ? updateNode(createBreak(label), node)
71487             : node;
71488     }
71489     ts.updateBreak = updateBreak;
71490     function createReturn(expression) {
71491         var node = createSynthesizedNode(235 /* ReturnStatement */);
71492         node.expression = expression;
71493         return node;
71494     }
71495     ts.createReturn = createReturn;
71496     function updateReturn(node, expression) {
71497         return node.expression !== expression
71498             ? updateNode(createReturn(expression), node)
71499             : node;
71500     }
71501     ts.updateReturn = updateReturn;
71502     function createWith(expression, statement) {
71503         var node = createSynthesizedNode(236 /* WithStatement */);
71504         node.expression = expression;
71505         node.statement = asEmbeddedStatement(statement);
71506         return node;
71507     }
71508     ts.createWith = createWith;
71509     function updateWith(node, expression, statement) {
71510         return node.expression !== expression
71511             || node.statement !== statement
71512             ? updateNode(createWith(expression, statement), node)
71513             : node;
71514     }
71515     ts.updateWith = updateWith;
71516     function createSwitch(expression, caseBlock) {
71517         var node = createSynthesizedNode(237 /* SwitchStatement */);
71518         node.expression = ts.parenthesizeExpressionForList(expression);
71519         node.caseBlock = caseBlock;
71520         return node;
71521     }
71522     ts.createSwitch = createSwitch;
71523     function updateSwitch(node, expression, caseBlock) {
71524         return node.expression !== expression
71525             || node.caseBlock !== caseBlock
71526             ? updateNode(createSwitch(expression, caseBlock), node)
71527             : node;
71528     }
71529     ts.updateSwitch = updateSwitch;
71530     function createLabel(label, statement) {
71531         var node = createSynthesizedNode(238 /* LabeledStatement */);
71532         node.label = asName(label);
71533         node.statement = asEmbeddedStatement(statement);
71534         return node;
71535     }
71536     ts.createLabel = createLabel;
71537     function updateLabel(node, label, statement) {
71538         return node.label !== label
71539             || node.statement !== statement
71540             ? updateNode(createLabel(label, statement), node)
71541             : node;
71542     }
71543     ts.updateLabel = updateLabel;
71544     function createThrow(expression) {
71545         var node = createSynthesizedNode(239 /* ThrowStatement */);
71546         node.expression = expression;
71547         return node;
71548     }
71549     ts.createThrow = createThrow;
71550     function updateThrow(node, expression) {
71551         return node.expression !== expression
71552             ? updateNode(createThrow(expression), node)
71553             : node;
71554     }
71555     ts.updateThrow = updateThrow;
71556     function createTry(tryBlock, catchClause, finallyBlock) {
71557         var node = createSynthesizedNode(240 /* TryStatement */);
71558         node.tryBlock = tryBlock;
71559         node.catchClause = catchClause;
71560         node.finallyBlock = finallyBlock;
71561         return node;
71562     }
71563     ts.createTry = createTry;
71564     function updateTry(node, tryBlock, catchClause, finallyBlock) {
71565         return node.tryBlock !== tryBlock
71566             || node.catchClause !== catchClause
71567             || node.finallyBlock !== finallyBlock
71568             ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
71569             : node;
71570     }
71571     ts.updateTry = updateTry;
71572     function createDebuggerStatement() {
71573         return createSynthesizedNode(241 /* DebuggerStatement */);
71574     }
71575     ts.createDebuggerStatement = createDebuggerStatement;
71576     function createVariableDeclaration(name, type, initializer) {
71577         /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71578         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71579         node.name = asName(name);
71580         node.type = type;
71581         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71582         return node;
71583     }
71584     ts.createVariableDeclaration = createVariableDeclaration;
71585     function updateVariableDeclaration(node, name, type, initializer) {
71586         /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71587         return node.name !== name
71588             || node.type !== type
71589             || node.initializer !== initializer
71590             ? updateNode(createVariableDeclaration(name, type, initializer), node)
71591             : node;
71592     }
71593     ts.updateVariableDeclaration = updateVariableDeclaration;
71594     /* @internal */
71595     function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
71596         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71597         node.name = asName(name);
71598         node.type = type;
71599         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71600         node.exclamationToken = exclaimationToken;
71601         return node;
71602     }
71603     ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
71604     /* @internal */
71605     function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
71606         return node.name !== name
71607             || node.type !== type
71608             || node.initializer !== initializer
71609             || node.exclamationToken !== exclaimationToken
71610             ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
71611             : node;
71612     }
71613     ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
71614     function createVariableDeclarationList(declarations, flags) {
71615         if (flags === void 0) { flags = 0 /* None */; }
71616         var node = createSynthesizedNode(243 /* VariableDeclarationList */);
71617         node.flags |= flags & 3 /* BlockScoped */;
71618         node.declarations = createNodeArray(declarations);
71619         return node;
71620     }
71621     ts.createVariableDeclarationList = createVariableDeclarationList;
71622     function updateVariableDeclarationList(node, declarations) {
71623         return node.declarations !== declarations
71624             ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
71625             : node;
71626     }
71627     ts.updateVariableDeclarationList = updateVariableDeclarationList;
71628     function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71629         var node = createSynthesizedNode(244 /* FunctionDeclaration */);
71630         node.decorators = asNodeArray(decorators);
71631         node.modifiers = asNodeArray(modifiers);
71632         node.asteriskToken = asteriskToken;
71633         node.name = asName(name);
71634         node.typeParameters = asNodeArray(typeParameters);
71635         node.parameters = createNodeArray(parameters);
71636         node.type = type;
71637         node.body = body;
71638         return node;
71639     }
71640     ts.createFunctionDeclaration = createFunctionDeclaration;
71641     function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71642         return node.decorators !== decorators
71643             || node.modifiers !== modifiers
71644             || node.asteriskToken !== asteriskToken
71645             || node.name !== name
71646             || node.typeParameters !== typeParameters
71647             || node.parameters !== parameters
71648             || node.type !== type
71649             || node.body !== body
71650             ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
71651             : node;
71652     }
71653     ts.updateFunctionDeclaration = updateFunctionDeclaration;
71654     /* @internal */
71655     function updateFunctionLikeBody(declaration, body) {
71656         switch (declaration.kind) {
71657             case 244 /* FunctionDeclaration */:
71658                 return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71659             case 161 /* MethodDeclaration */:
71660                 return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body);
71661             case 163 /* GetAccessor */:
71662                 return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body);
71663             case 164 /* SetAccessor */:
71664                 return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body);
71665             case 162 /* Constructor */:
71666                 return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body);
71667             case 201 /* FunctionExpression */:
71668                 return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71669             case 202 /* ArrowFunction */:
71670                 return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body);
71671         }
71672     }
71673     ts.updateFunctionLikeBody = updateFunctionLikeBody;
71674     function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71675         var node = createSynthesizedNode(245 /* ClassDeclaration */);
71676         node.decorators = asNodeArray(decorators);
71677         node.modifiers = asNodeArray(modifiers);
71678         node.name = asName(name);
71679         node.typeParameters = asNodeArray(typeParameters);
71680         node.heritageClauses = asNodeArray(heritageClauses);
71681         node.members = createNodeArray(members);
71682         return node;
71683     }
71684     ts.createClassDeclaration = createClassDeclaration;
71685     function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71686         return node.decorators !== decorators
71687             || node.modifiers !== modifiers
71688             || node.name !== name
71689             || node.typeParameters !== typeParameters
71690             || node.heritageClauses !== heritageClauses
71691             || node.members !== members
71692             ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71693             : node;
71694     }
71695     ts.updateClassDeclaration = updateClassDeclaration;
71696     function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71697         var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
71698         node.decorators = asNodeArray(decorators);
71699         node.modifiers = asNodeArray(modifiers);
71700         node.name = asName(name);
71701         node.typeParameters = asNodeArray(typeParameters);
71702         node.heritageClauses = asNodeArray(heritageClauses);
71703         node.members = createNodeArray(members);
71704         return node;
71705     }
71706     ts.createInterfaceDeclaration = createInterfaceDeclaration;
71707     function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71708         return node.decorators !== decorators
71709             || node.modifiers !== modifiers
71710             || node.name !== name
71711             || node.typeParameters !== typeParameters
71712             || node.heritageClauses !== heritageClauses
71713             || node.members !== members
71714             ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71715             : node;
71716     }
71717     ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
71718     function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
71719         var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
71720         node.decorators = asNodeArray(decorators);
71721         node.modifiers = asNodeArray(modifiers);
71722         node.name = asName(name);
71723         node.typeParameters = asNodeArray(typeParameters);
71724         node.type = type;
71725         return node;
71726     }
71727     ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
71728     function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
71729         return node.decorators !== decorators
71730             || node.modifiers !== modifiers
71731             || node.name !== name
71732             || node.typeParameters !== typeParameters
71733             || node.type !== type
71734             ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
71735             : node;
71736     }
71737     ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
71738     function createEnumDeclaration(decorators, modifiers, name, members) {
71739         var node = createSynthesizedNode(248 /* EnumDeclaration */);
71740         node.decorators = asNodeArray(decorators);
71741         node.modifiers = asNodeArray(modifiers);
71742         node.name = asName(name);
71743         node.members = createNodeArray(members);
71744         return node;
71745     }
71746     ts.createEnumDeclaration = createEnumDeclaration;
71747     function updateEnumDeclaration(node, decorators, modifiers, name, members) {
71748         return node.decorators !== decorators
71749             || node.modifiers !== modifiers
71750             || node.name !== name
71751             || node.members !== members
71752             ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
71753             : node;
71754     }
71755     ts.updateEnumDeclaration = updateEnumDeclaration;
71756     function createModuleDeclaration(decorators, modifiers, name, body, flags) {
71757         if (flags === void 0) { flags = 0 /* None */; }
71758         var node = createSynthesizedNode(249 /* ModuleDeclaration */);
71759         node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
71760         node.decorators = asNodeArray(decorators);
71761         node.modifiers = asNodeArray(modifiers);
71762         node.name = name;
71763         node.body = body;
71764         return node;
71765     }
71766     ts.createModuleDeclaration = createModuleDeclaration;
71767     function updateModuleDeclaration(node, decorators, modifiers, name, body) {
71768         return node.decorators !== decorators
71769             || node.modifiers !== modifiers
71770             || node.name !== name
71771             || node.body !== body
71772             ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
71773             : node;
71774     }
71775     ts.updateModuleDeclaration = updateModuleDeclaration;
71776     function createModuleBlock(statements) {
71777         var node = createSynthesizedNode(250 /* ModuleBlock */);
71778         node.statements = createNodeArray(statements);
71779         return node;
71780     }
71781     ts.createModuleBlock = createModuleBlock;
71782     function updateModuleBlock(node, statements) {
71783         return node.statements !== statements
71784             ? updateNode(createModuleBlock(statements), node)
71785             : node;
71786     }
71787     ts.updateModuleBlock = updateModuleBlock;
71788     function createCaseBlock(clauses) {
71789         var node = createSynthesizedNode(251 /* CaseBlock */);
71790         node.clauses = createNodeArray(clauses);
71791         return node;
71792     }
71793     ts.createCaseBlock = createCaseBlock;
71794     function updateCaseBlock(node, clauses) {
71795         return node.clauses !== clauses
71796             ? updateNode(createCaseBlock(clauses), node)
71797             : node;
71798     }
71799     ts.updateCaseBlock = updateCaseBlock;
71800     function createNamespaceExportDeclaration(name) {
71801         var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
71802         node.name = asName(name);
71803         return node;
71804     }
71805     ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
71806     function updateNamespaceExportDeclaration(node, name) {
71807         return node.name !== name
71808             ? updateNode(createNamespaceExportDeclaration(name), node)
71809             : node;
71810     }
71811     ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
71812     function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
71813         var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
71814         node.decorators = asNodeArray(decorators);
71815         node.modifiers = asNodeArray(modifiers);
71816         node.name = asName(name);
71817         node.moduleReference = moduleReference;
71818         return node;
71819     }
71820     ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
71821     function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
71822         return node.decorators !== decorators
71823             || node.modifiers !== modifiers
71824             || node.name !== name
71825             || node.moduleReference !== moduleReference
71826             ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
71827             : node;
71828     }
71829     ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
71830     function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
71831         var node = createSynthesizedNode(254 /* ImportDeclaration */);
71832         node.decorators = asNodeArray(decorators);
71833         node.modifiers = asNodeArray(modifiers);
71834         node.importClause = importClause;
71835         node.moduleSpecifier = moduleSpecifier;
71836         return node;
71837     }
71838     ts.createImportDeclaration = createImportDeclaration;
71839     function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
71840         return node.decorators !== decorators
71841             || node.modifiers !== modifiers
71842             || node.importClause !== importClause
71843             || node.moduleSpecifier !== moduleSpecifier
71844             ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
71845             : node;
71846     }
71847     ts.updateImportDeclaration = updateImportDeclaration;
71848     function createImportClause(name, namedBindings, isTypeOnly) {
71849         if (isTypeOnly === void 0) { isTypeOnly = false; }
71850         var node = createSynthesizedNode(255 /* ImportClause */);
71851         node.name = name;
71852         node.namedBindings = namedBindings;
71853         node.isTypeOnly = isTypeOnly;
71854         return node;
71855     }
71856     ts.createImportClause = createImportClause;
71857     function updateImportClause(node, name, namedBindings, isTypeOnly) {
71858         return node.name !== name
71859             || node.namedBindings !== namedBindings
71860             || node.isTypeOnly !== isTypeOnly
71861             ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
71862             : node;
71863     }
71864     ts.updateImportClause = updateImportClause;
71865     function createNamespaceImport(name) {
71866         var node = createSynthesizedNode(256 /* NamespaceImport */);
71867         node.name = name;
71868         return node;
71869     }
71870     ts.createNamespaceImport = createNamespaceImport;
71871     function createNamespaceExport(name) {
71872         var node = createSynthesizedNode(262 /* NamespaceExport */);
71873         node.name = name;
71874         return node;
71875     }
71876     ts.createNamespaceExport = createNamespaceExport;
71877     function updateNamespaceImport(node, name) {
71878         return node.name !== name
71879             ? updateNode(createNamespaceImport(name), node)
71880             : node;
71881     }
71882     ts.updateNamespaceImport = updateNamespaceImport;
71883     function updateNamespaceExport(node, name) {
71884         return node.name !== name
71885             ? updateNode(createNamespaceExport(name), node)
71886             : node;
71887     }
71888     ts.updateNamespaceExport = updateNamespaceExport;
71889     function createNamedImports(elements) {
71890         var node = createSynthesizedNode(257 /* NamedImports */);
71891         node.elements = createNodeArray(elements);
71892         return node;
71893     }
71894     ts.createNamedImports = createNamedImports;
71895     function updateNamedImports(node, elements) {
71896         return node.elements !== elements
71897             ? updateNode(createNamedImports(elements), node)
71898             : node;
71899     }
71900     ts.updateNamedImports = updateNamedImports;
71901     function createImportSpecifier(propertyName, name) {
71902         var node = createSynthesizedNode(258 /* ImportSpecifier */);
71903         node.propertyName = propertyName;
71904         node.name = name;
71905         return node;
71906     }
71907     ts.createImportSpecifier = createImportSpecifier;
71908     function updateImportSpecifier(node, propertyName, name) {
71909         return node.propertyName !== propertyName
71910             || node.name !== name
71911             ? updateNode(createImportSpecifier(propertyName, name), node)
71912             : node;
71913     }
71914     ts.updateImportSpecifier = updateImportSpecifier;
71915     function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
71916         var node = createSynthesizedNode(259 /* ExportAssignment */);
71917         node.decorators = asNodeArray(decorators);
71918         node.modifiers = asNodeArray(modifiers);
71919         node.isExportEquals = isExportEquals;
71920         node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
71921         return node;
71922     }
71923     ts.createExportAssignment = createExportAssignment;
71924     function updateExportAssignment(node, decorators, modifiers, expression) {
71925         return node.decorators !== decorators
71926             || node.modifiers !== modifiers
71927             || node.expression !== expression
71928             ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
71929             : node;
71930     }
71931     ts.updateExportAssignment = updateExportAssignment;
71932     function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71933         if (isTypeOnly === void 0) { isTypeOnly = false; }
71934         var node = createSynthesizedNode(260 /* ExportDeclaration */);
71935         node.decorators = asNodeArray(decorators);
71936         node.modifiers = asNodeArray(modifiers);
71937         node.isTypeOnly = isTypeOnly;
71938         node.exportClause = exportClause;
71939         node.moduleSpecifier = moduleSpecifier;
71940         return node;
71941     }
71942     ts.createExportDeclaration = createExportDeclaration;
71943     function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71944         return node.decorators !== decorators
71945             || node.modifiers !== modifiers
71946             || node.isTypeOnly !== isTypeOnly
71947             || node.exportClause !== exportClause
71948             || node.moduleSpecifier !== moduleSpecifier
71949             ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
71950             : node;
71951     }
71952     ts.updateExportDeclaration = updateExportDeclaration;
71953     /* @internal */
71954     function createEmptyExports() {
71955         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
71956     }
71957     ts.createEmptyExports = createEmptyExports;
71958     function createNamedExports(elements) {
71959         var node = createSynthesizedNode(261 /* NamedExports */);
71960         node.elements = createNodeArray(elements);
71961         return node;
71962     }
71963     ts.createNamedExports = createNamedExports;
71964     function updateNamedExports(node, elements) {
71965         return node.elements !== elements
71966             ? updateNode(createNamedExports(elements), node)
71967             : node;
71968     }
71969     ts.updateNamedExports = updateNamedExports;
71970     function createExportSpecifier(propertyName, name) {
71971         var node = createSynthesizedNode(263 /* ExportSpecifier */);
71972         node.propertyName = asName(propertyName);
71973         node.name = asName(name);
71974         return node;
71975     }
71976     ts.createExportSpecifier = createExportSpecifier;
71977     function updateExportSpecifier(node, propertyName, name) {
71978         return node.propertyName !== propertyName
71979             || node.name !== name
71980             ? updateNode(createExportSpecifier(propertyName, name), node)
71981             : node;
71982     }
71983     ts.updateExportSpecifier = updateExportSpecifier;
71984     // Module references
71985     function createExternalModuleReference(expression) {
71986         var node = createSynthesizedNode(265 /* ExternalModuleReference */);
71987         node.expression = expression;
71988         return node;
71989     }
71990     ts.createExternalModuleReference = createExternalModuleReference;
71991     function updateExternalModuleReference(node, expression) {
71992         return node.expression !== expression
71993             ? updateNode(createExternalModuleReference(expression), node)
71994             : node;
71995     }
71996     ts.updateExternalModuleReference = updateExternalModuleReference;
71997     // JSDoc
71998     /* @internal */
71999     function createJSDocTypeExpression(type) {
72000         var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
72001         node.type = type;
72002         return node;
72003     }
72004     ts.createJSDocTypeExpression = createJSDocTypeExpression;
72005     /* @internal */
72006     function createJSDocTypeTag(typeExpression, comment) {
72007         var tag = createJSDocTag(320 /* JSDocTypeTag */, "type");
72008         tag.typeExpression = typeExpression;
72009         tag.comment = comment;
72010         return tag;
72011     }
72012     ts.createJSDocTypeTag = createJSDocTypeTag;
72013     /* @internal */
72014     function createJSDocReturnTag(typeExpression, comment) {
72015         var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns");
72016         tag.typeExpression = typeExpression;
72017         tag.comment = comment;
72018         return tag;
72019     }
72020     ts.createJSDocReturnTag = createJSDocReturnTag;
72021     /** @internal */
72022     function createJSDocThisTag(typeExpression) {
72023         var tag = createJSDocTag(319 /* JSDocThisTag */, "this");
72024         tag.typeExpression = typeExpression;
72025         return tag;
72026     }
72027     ts.createJSDocThisTag = createJSDocThisTag;
72028     /* @internal */
72029     function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
72030         var tag = createJSDocTag(317 /* JSDocParameterTag */, "param");
72031         tag.typeExpression = typeExpression;
72032         tag.name = name;
72033         tag.isBracketed = isBracketed;
72034         tag.comment = comment;
72035         return tag;
72036     }
72037     ts.createJSDocParamTag = createJSDocParamTag;
72038     /* @internal */
72039     function createJSDocClassTag() {
72040         return createJSDocTag(310 /* JSDocClassTag */, "class");
72041     }
72042     ts.createJSDocClassTag = createJSDocClassTag;
72043     /* @internal */
72044     function createJSDocComment(comment, tags) {
72045         var node = createSynthesizedNode(303 /* JSDocComment */);
72046         node.comment = comment;
72047         node.tags = tags;
72048         return node;
72049     }
72050     ts.createJSDocComment = createJSDocComment;
72051     /* @internal */
72052     function createJSDocTag(kind, tagName) {
72053         var node = createSynthesizedNode(kind);
72054         node.tagName = createIdentifier(tagName);
72055         return node;
72056     }
72057     // JSX
72058     function createJsxElement(openingElement, children, closingElement) {
72059         var node = createSynthesizedNode(266 /* JsxElement */);
72060         node.openingElement = openingElement;
72061         node.children = createNodeArray(children);
72062         node.closingElement = closingElement;
72063         return node;
72064     }
72065     ts.createJsxElement = createJsxElement;
72066     function updateJsxElement(node, openingElement, children, closingElement) {
72067         return node.openingElement !== openingElement
72068             || node.children !== children
72069             || node.closingElement !== closingElement
72070             ? updateNode(createJsxElement(openingElement, children, closingElement), node)
72071             : node;
72072     }
72073     ts.updateJsxElement = updateJsxElement;
72074     function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
72075         var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
72076         node.tagName = tagName;
72077         node.typeArguments = asNodeArray(typeArguments);
72078         node.attributes = attributes;
72079         return node;
72080     }
72081     ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
72082     function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
72083         return node.tagName !== tagName
72084             || node.typeArguments !== typeArguments
72085             || node.attributes !== attributes
72086             ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
72087             : node;
72088     }
72089     ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
72090     function createJsxOpeningElement(tagName, typeArguments, attributes) {
72091         var node = createSynthesizedNode(268 /* JsxOpeningElement */);
72092         node.tagName = tagName;
72093         node.typeArguments = asNodeArray(typeArguments);
72094         node.attributes = attributes;
72095         return node;
72096     }
72097     ts.createJsxOpeningElement = createJsxOpeningElement;
72098     function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
72099         return node.tagName !== tagName
72100             || node.typeArguments !== typeArguments
72101             || node.attributes !== attributes
72102             ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
72103             : node;
72104     }
72105     ts.updateJsxOpeningElement = updateJsxOpeningElement;
72106     function createJsxClosingElement(tagName) {
72107         var node = createSynthesizedNode(269 /* JsxClosingElement */);
72108         node.tagName = tagName;
72109         return node;
72110     }
72111     ts.createJsxClosingElement = createJsxClosingElement;
72112     function updateJsxClosingElement(node, tagName) {
72113         return node.tagName !== tagName
72114             ? updateNode(createJsxClosingElement(tagName), node)
72115             : node;
72116     }
72117     ts.updateJsxClosingElement = updateJsxClosingElement;
72118     function createJsxFragment(openingFragment, children, closingFragment) {
72119         var node = createSynthesizedNode(270 /* JsxFragment */);
72120         node.openingFragment = openingFragment;
72121         node.children = createNodeArray(children);
72122         node.closingFragment = closingFragment;
72123         return node;
72124     }
72125     ts.createJsxFragment = createJsxFragment;
72126     function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
72127         var node = createSynthesizedNode(11 /* JsxText */);
72128         node.text = text;
72129         node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
72130         return node;
72131     }
72132     ts.createJsxText = createJsxText;
72133     function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
72134         return node.text !== text
72135             || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
72136             ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
72137             : node;
72138     }
72139     ts.updateJsxText = updateJsxText;
72140     function createJsxOpeningFragment() {
72141         return createSynthesizedNode(271 /* JsxOpeningFragment */);
72142     }
72143     ts.createJsxOpeningFragment = createJsxOpeningFragment;
72144     function createJsxJsxClosingFragment() {
72145         return createSynthesizedNode(272 /* JsxClosingFragment */);
72146     }
72147     ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
72148     function updateJsxFragment(node, openingFragment, children, closingFragment) {
72149         return node.openingFragment !== openingFragment
72150             || node.children !== children
72151             || node.closingFragment !== closingFragment
72152             ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
72153             : node;
72154     }
72155     ts.updateJsxFragment = updateJsxFragment;
72156     function createJsxAttribute(name, initializer) {
72157         var node = createSynthesizedNode(273 /* JsxAttribute */);
72158         node.name = name;
72159         node.initializer = initializer;
72160         return node;
72161     }
72162     ts.createJsxAttribute = createJsxAttribute;
72163     function updateJsxAttribute(node, name, initializer) {
72164         return node.name !== name
72165             || node.initializer !== initializer
72166             ? updateNode(createJsxAttribute(name, initializer), node)
72167             : node;
72168     }
72169     ts.updateJsxAttribute = updateJsxAttribute;
72170     function createJsxAttributes(properties) {
72171         var node = createSynthesizedNode(274 /* JsxAttributes */);
72172         node.properties = createNodeArray(properties);
72173         return node;
72174     }
72175     ts.createJsxAttributes = createJsxAttributes;
72176     function updateJsxAttributes(node, properties) {
72177         return node.properties !== properties
72178             ? updateNode(createJsxAttributes(properties), node)
72179             : node;
72180     }
72181     ts.updateJsxAttributes = updateJsxAttributes;
72182     function createJsxSpreadAttribute(expression) {
72183         var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
72184         node.expression = expression;
72185         return node;
72186     }
72187     ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
72188     function updateJsxSpreadAttribute(node, expression) {
72189         return node.expression !== expression
72190             ? updateNode(createJsxSpreadAttribute(expression), node)
72191             : node;
72192     }
72193     ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
72194     function createJsxExpression(dotDotDotToken, expression) {
72195         var node = createSynthesizedNode(276 /* JsxExpression */);
72196         node.dotDotDotToken = dotDotDotToken;
72197         node.expression = expression;
72198         return node;
72199     }
72200     ts.createJsxExpression = createJsxExpression;
72201     function updateJsxExpression(node, expression) {
72202         return node.expression !== expression
72203             ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
72204             : node;
72205     }
72206     ts.updateJsxExpression = updateJsxExpression;
72207     // Clauses
72208     function createCaseClause(expression, statements) {
72209         var node = createSynthesizedNode(277 /* CaseClause */);
72210         node.expression = ts.parenthesizeExpressionForList(expression);
72211         node.statements = createNodeArray(statements);
72212         return node;
72213     }
72214     ts.createCaseClause = createCaseClause;
72215     function updateCaseClause(node, expression, statements) {
72216         return node.expression !== expression
72217             || node.statements !== statements
72218             ? updateNode(createCaseClause(expression, statements), node)
72219             : node;
72220     }
72221     ts.updateCaseClause = updateCaseClause;
72222     function createDefaultClause(statements) {
72223         var node = createSynthesizedNode(278 /* DefaultClause */);
72224         node.statements = createNodeArray(statements);
72225         return node;
72226     }
72227     ts.createDefaultClause = createDefaultClause;
72228     function updateDefaultClause(node, statements) {
72229         return node.statements !== statements
72230             ? updateNode(createDefaultClause(statements), node)
72231             : node;
72232     }
72233     ts.updateDefaultClause = updateDefaultClause;
72234     function createHeritageClause(token, types) {
72235         var node = createSynthesizedNode(279 /* HeritageClause */);
72236         node.token = token;
72237         node.types = createNodeArray(types);
72238         return node;
72239     }
72240     ts.createHeritageClause = createHeritageClause;
72241     function updateHeritageClause(node, types) {
72242         return node.types !== types
72243             ? updateNode(createHeritageClause(node.token, types), node)
72244             : node;
72245     }
72246     ts.updateHeritageClause = updateHeritageClause;
72247     function createCatchClause(variableDeclaration, block) {
72248         var node = createSynthesizedNode(280 /* CatchClause */);
72249         node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
72250         node.block = block;
72251         return node;
72252     }
72253     ts.createCatchClause = createCatchClause;
72254     function updateCatchClause(node, variableDeclaration, block) {
72255         return node.variableDeclaration !== variableDeclaration
72256             || node.block !== block
72257             ? updateNode(createCatchClause(variableDeclaration, block), node)
72258             : node;
72259     }
72260     ts.updateCatchClause = updateCatchClause;
72261     // Property assignments
72262     function createPropertyAssignment(name, initializer) {
72263         var node = createSynthesizedNode(281 /* PropertyAssignment */);
72264         node.name = asName(name);
72265         node.questionToken = undefined;
72266         node.initializer = ts.parenthesizeExpressionForList(initializer);
72267         return node;
72268     }
72269     ts.createPropertyAssignment = createPropertyAssignment;
72270     function updatePropertyAssignment(node, name, initializer) {
72271         return node.name !== name
72272             || node.initializer !== initializer
72273             ? updateNode(createPropertyAssignment(name, initializer), node)
72274             : node;
72275     }
72276     ts.updatePropertyAssignment = updatePropertyAssignment;
72277     function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
72278         var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
72279         node.name = asName(name);
72280         node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
72281         return node;
72282     }
72283     ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
72284     function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
72285         return node.name !== name
72286             || node.objectAssignmentInitializer !== objectAssignmentInitializer
72287             ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
72288             : node;
72289     }
72290     ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
72291     function createSpreadAssignment(expression) {
72292         var node = createSynthesizedNode(283 /* SpreadAssignment */);
72293         node.expression = ts.parenthesizeExpressionForList(expression);
72294         return node;
72295     }
72296     ts.createSpreadAssignment = createSpreadAssignment;
72297     function updateSpreadAssignment(node, expression) {
72298         return node.expression !== expression
72299             ? updateNode(createSpreadAssignment(expression), node)
72300             : node;
72301     }
72302     ts.updateSpreadAssignment = updateSpreadAssignment;
72303     // Enum
72304     function createEnumMember(name, initializer) {
72305         var node = createSynthesizedNode(284 /* EnumMember */);
72306         node.name = asName(name);
72307         node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
72308         return node;
72309     }
72310     ts.createEnumMember = createEnumMember;
72311     function updateEnumMember(node, name, initializer) {
72312         return node.name !== name
72313             || node.initializer !== initializer
72314             ? updateNode(createEnumMember(name, initializer), node)
72315             : node;
72316     }
72317     ts.updateEnumMember = updateEnumMember;
72318     // Top-level nodes
72319     function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
72320         if (node.statements !== statements ||
72321             (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
72322             (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
72323             (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
72324             (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
72325             (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
72326             var updated = createSynthesizedNode(290 /* SourceFile */);
72327             updated.flags |= node.flags;
72328             updated.statements = createNodeArray(statements);
72329             updated.endOfFileToken = node.endOfFileToken;
72330             updated.fileName = node.fileName;
72331             updated.path = node.path;
72332             updated.text = node.text;
72333             updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
72334             updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
72335             updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
72336             updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
72337             updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
72338             if (node.amdDependencies !== undefined)
72339                 updated.amdDependencies = node.amdDependencies;
72340             if (node.moduleName !== undefined)
72341                 updated.moduleName = node.moduleName;
72342             if (node.languageVariant !== undefined)
72343                 updated.languageVariant = node.languageVariant;
72344             if (node.renamedDependencies !== undefined)
72345                 updated.renamedDependencies = node.renamedDependencies;
72346             if (node.languageVersion !== undefined)
72347                 updated.languageVersion = node.languageVersion;
72348             if (node.scriptKind !== undefined)
72349                 updated.scriptKind = node.scriptKind;
72350             if (node.externalModuleIndicator !== undefined)
72351                 updated.externalModuleIndicator = node.externalModuleIndicator;
72352             if (node.commonJsModuleIndicator !== undefined)
72353                 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
72354             if (node.identifiers !== undefined)
72355                 updated.identifiers = node.identifiers;
72356             if (node.nodeCount !== undefined)
72357                 updated.nodeCount = node.nodeCount;
72358             if (node.identifierCount !== undefined)
72359                 updated.identifierCount = node.identifierCount;
72360             if (node.symbolCount !== undefined)
72361                 updated.symbolCount = node.symbolCount;
72362             if (node.parseDiagnostics !== undefined)
72363                 updated.parseDiagnostics = node.parseDiagnostics;
72364             if (node.bindDiagnostics !== undefined)
72365                 updated.bindDiagnostics = node.bindDiagnostics;
72366             if (node.bindSuggestionDiagnostics !== undefined)
72367                 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
72368             if (node.lineMap !== undefined)
72369                 updated.lineMap = node.lineMap;
72370             if (node.classifiableNames !== undefined)
72371                 updated.classifiableNames = node.classifiableNames;
72372             if (node.resolvedModules !== undefined)
72373                 updated.resolvedModules = node.resolvedModules;
72374             if (node.resolvedTypeReferenceDirectiveNames !== undefined)
72375                 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
72376             if (node.imports !== undefined)
72377                 updated.imports = node.imports;
72378             if (node.moduleAugmentations !== undefined)
72379                 updated.moduleAugmentations = node.moduleAugmentations;
72380             if (node.pragmas !== undefined)
72381                 updated.pragmas = node.pragmas;
72382             if (node.localJsxFactory !== undefined)
72383                 updated.localJsxFactory = node.localJsxFactory;
72384             if (node.localJsxNamespace !== undefined)
72385                 updated.localJsxNamespace = node.localJsxNamespace;
72386             return updateNode(updated, node);
72387         }
72388         return node;
72389     }
72390     ts.updateSourceFileNode = updateSourceFileNode;
72391     /**
72392      * Creates a shallow, memberwise clone of a node for mutation.
72393      */
72394     function getMutableClone(node) {
72395         var clone = getSynthesizedClone(node);
72396         clone.pos = node.pos;
72397         clone.end = node.end;
72398         clone.parent = node.parent;
72399         return clone;
72400     }
72401     ts.getMutableClone = getMutableClone;
72402     // Transformation nodes
72403     /**
72404      * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
72405      * order to preserve comments.
72406      *
72407      * @param original The original statement.
72408      */
72409     function createNotEmittedStatement(original) {
72410         var node = createSynthesizedNode(325 /* NotEmittedStatement */);
72411         node.original = original;
72412         setTextRange(node, original);
72413         return node;
72414     }
72415     ts.createNotEmittedStatement = createNotEmittedStatement;
72416     /**
72417      * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
72418      * order to properly emit exports.
72419      */
72420     /* @internal */
72421     function createEndOfDeclarationMarker(original) {
72422         var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */);
72423         node.emitNode = {};
72424         node.original = original;
72425         return node;
72426     }
72427     ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
72428     /**
72429      * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
72430      * order to properly emit exports.
72431      */
72432     /* @internal */
72433     function createMergeDeclarationMarker(original) {
72434         var node = createSynthesizedNode(328 /* MergeDeclarationMarker */);
72435         node.emitNode = {};
72436         node.original = original;
72437         return node;
72438     }
72439     ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
72440     /**
72441      * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
72442      * order to preserve comments or sourcemap positions.
72443      *
72444      * @param expression The inner expression to emit.
72445      * @param original The original outer expression.
72446      * @param location The location for the expression. Defaults to the positions from "original" if provided.
72447      */
72448     function createPartiallyEmittedExpression(expression, original) {
72449         var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */);
72450         node.expression = expression;
72451         node.original = original;
72452         setTextRange(node, original);
72453         return node;
72454     }
72455     ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
72456     function updatePartiallyEmittedExpression(node, expression) {
72457         if (node.expression !== expression) {
72458             return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
72459         }
72460         return node;
72461     }
72462     ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
72463     function flattenCommaElements(node) {
72464         if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
72465             if (node.kind === 327 /* CommaListExpression */) {
72466                 return node.elements;
72467             }
72468             if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
72469                 return [node.left, node.right];
72470             }
72471         }
72472         return node;
72473     }
72474     function createCommaList(elements) {
72475         var node = createSynthesizedNode(327 /* CommaListExpression */);
72476         node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
72477         return node;
72478     }
72479     ts.createCommaList = createCommaList;
72480     function updateCommaList(node, elements) {
72481         return node.elements !== elements
72482             ? updateNode(createCommaList(elements), node)
72483             : node;
72484     }
72485     ts.updateCommaList = updateCommaList;
72486     /* @internal */
72487     function createSyntheticReferenceExpression(expression, thisArg) {
72488         var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */);
72489         node.expression = expression;
72490         node.thisArg = thisArg;
72491         return node;
72492     }
72493     ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
72494     /* @internal */
72495     function updateSyntheticReferenceExpression(node, expression, thisArg) {
72496         return node.expression !== expression
72497             || node.thisArg !== thisArg
72498             ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
72499             : node;
72500     }
72501     ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
72502     function createBundle(sourceFiles, prepends) {
72503         if (prepends === void 0) { prepends = ts.emptyArray; }
72504         var node = ts.createNode(291 /* Bundle */);
72505         node.prepends = prepends;
72506         node.sourceFiles = sourceFiles;
72507         return node;
72508     }
72509     ts.createBundle = createBundle;
72510     var allUnscopedEmitHelpers;
72511     function getAllUnscopedEmitHelpers() {
72512         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
72513             ts.valuesHelper,
72514             ts.readHelper,
72515             ts.spreadHelper,
72516             ts.spreadArraysHelper,
72517             ts.restHelper,
72518             ts.decorateHelper,
72519             ts.metadataHelper,
72520             ts.paramHelper,
72521             ts.awaiterHelper,
72522             ts.assignHelper,
72523             ts.awaitHelper,
72524             ts.asyncGeneratorHelper,
72525             ts.asyncDelegator,
72526             ts.asyncValues,
72527             ts.extendsHelper,
72528             ts.templateObjectHelper,
72529             ts.generatorHelper,
72530             ts.importStarHelper,
72531             ts.importDefaultHelper,
72532             ts.classPrivateFieldGetHelper,
72533             ts.classPrivateFieldSetHelper,
72534             ts.createBindingHelper,
72535             ts.setModuleDefaultHelper
72536         ], function (helper) { return helper.name; }));
72537     }
72538     function createUnparsedSource() {
72539         var node = ts.createNode(292 /* UnparsedSource */);
72540         node.prologues = ts.emptyArray;
72541         node.referencedFiles = ts.emptyArray;
72542         node.libReferenceDirectives = ts.emptyArray;
72543         node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
72544         return node;
72545     }
72546     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
72547         var node = createUnparsedSource();
72548         var stripInternal;
72549         var bundleFileInfo;
72550         if (!ts.isString(textOrInputFiles)) {
72551             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
72552             node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
72553             node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
72554             Object.defineProperties(node, {
72555                 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
72556                 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
72557             });
72558             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
72559                 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
72560                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
72561                 stripInternal = mapTextOrStripInternal;
72562                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
72563                 if (node.oldFileOfCurrentEmit) {
72564                     parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo));
72565                     return node;
72566                 }
72567             }
72568         }
72569         else {
72570             node.fileName = "";
72571             node.text = textOrInputFiles;
72572             node.sourceMapPath = mapPathOrType;
72573             node.sourceMapText = mapTextOrStripInternal;
72574         }
72575         ts.Debug.assert(!node.oldFileOfCurrentEmit);
72576         parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
72577         return node;
72578     }
72579     ts.createUnparsedSourceFile = createUnparsedSourceFile;
72580     function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
72581         var prologues;
72582         var helpers;
72583         var referencedFiles;
72584         var typeReferenceDirectives;
72585         var libReferenceDirectives;
72586         var texts;
72587         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
72588             var section = _a[_i];
72589             switch (section.kind) {
72590                 case "prologue" /* Prologue */:
72591                     (prologues || (prologues = [])).push(createUnparsedNode(section, node));
72592                     break;
72593                 case "emitHelpers" /* EmitHelpers */:
72594                     (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
72595                     break;
72596                 case "no-default-lib" /* NoDefaultLib */:
72597                     node.hasNoDefaultLib = true;
72598                     break;
72599                 case "reference" /* Reference */:
72600                     (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
72601                     break;
72602                 case "type" /* Type */:
72603                     (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
72604                     break;
72605                 case "lib" /* Lib */:
72606                     (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
72607                     break;
72608                 case "prepend" /* Prepend */:
72609                     var prependNode = createUnparsedNode(section, node);
72610                     var prependTexts = void 0;
72611                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
72612                         var text = _c[_b];
72613                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
72614                             (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
72615                         }
72616                     }
72617                     prependNode.texts = prependTexts || ts.emptyArray;
72618                     (texts || (texts = [])).push(prependNode);
72619                     break;
72620                 case "internal" /* Internal */:
72621                     if (stripInternal) {
72622                         if (!texts)
72623                             texts = [];
72624                         break;
72625                     }
72626                 // falls through
72627                 case "text" /* Text */:
72628                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72629                     break;
72630                 default:
72631                     ts.Debug.assertNever(section);
72632             }
72633         }
72634         node.prologues = prologues || ts.emptyArray;
72635         node.helpers = helpers;
72636         node.referencedFiles = referencedFiles || ts.emptyArray;
72637         node.typeReferenceDirectives = typeReferenceDirectives;
72638         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
72639         node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
72640     }
72641     function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
72642         ts.Debug.assert(!!node.oldFileOfCurrentEmit);
72643         var texts;
72644         var syntheticReferences;
72645         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
72646             var section = _a[_i];
72647             switch (section.kind) {
72648                 case "internal" /* Internal */:
72649                 case "text" /* Text */:
72650                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72651                     break;
72652                 case "no-default-lib" /* NoDefaultLib */:
72653                 case "reference" /* Reference */:
72654                 case "type" /* Type */:
72655                 case "lib" /* Lib */:
72656                     (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
72657                     break;
72658                 // Ignore
72659                 case "prologue" /* Prologue */:
72660                 case "emitHelpers" /* EmitHelpers */:
72661                 case "prepend" /* Prepend */:
72662                     break;
72663                 default:
72664                     ts.Debug.assertNever(section);
72665             }
72666         }
72667         node.texts = texts || ts.emptyArray;
72668         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
72669         node.syntheticReferences = syntheticReferences;
72670         return node;
72671     }
72672     function mapBundleFileSectionKindToSyntaxKind(kind) {
72673         switch (kind) {
72674             case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
72675             case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
72676             case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
72677             case "text" /* Text */: return 287 /* UnparsedText */;
72678             case "emitHelpers" /* EmitHelpers */:
72679             case "no-default-lib" /* NoDefaultLib */:
72680             case "reference" /* Reference */:
72681             case "type" /* Type */:
72682             case "lib" /* Lib */:
72683                 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
72684             default:
72685                 return ts.Debug.assertNever(kind);
72686         }
72687     }
72688     function createUnparsedNode(section, parent) {
72689         var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
72690         node.parent = parent;
72691         node.data = section.data;
72692         return node;
72693     }
72694     function createUnparsedSyntheticReference(section, parent) {
72695         var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
72696         node.parent = parent;
72697         node.data = section.data;
72698         node.section = section;
72699         return node;
72700     }
72701     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
72702         var node = ts.createNode(293 /* InputFiles */);
72703         if (!ts.isString(javascriptTextOrReadFileText)) {
72704             var cache_1 = ts.createMap();
72705             var textGetter_1 = function (path) {
72706                 if (path === undefined)
72707                     return undefined;
72708                 var value = cache_1.get(path);
72709                 if (value === undefined) {
72710                     value = javascriptTextOrReadFileText(path);
72711                     cache_1.set(path, value !== undefined ? value : false);
72712                 }
72713                 return value !== false ? value : undefined;
72714             };
72715             var definedTextGetter_1 = function (path) {
72716                 var result = textGetter_1(path);
72717                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
72718             };
72719             var buildInfo_1;
72720             var getAndCacheBuildInfo_1 = function (getText) {
72721                 if (buildInfo_1 === undefined) {
72722                     var result = getText();
72723                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
72724                 }
72725                 return buildInfo_1 || undefined;
72726             };
72727             node.javascriptPath = declarationTextOrJavascriptPath;
72728             node.javascriptMapPath = javascriptMapPath;
72729             node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath);
72730             node.declarationMapPath = declarationMapPath;
72731             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
72732             Object.defineProperties(node, {
72733                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
72734                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
72735                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
72736                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
72737                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
72738             });
72739         }
72740         else {
72741             node.javascriptText = javascriptTextOrReadFileText;
72742             node.javascriptMapPath = javascriptMapPath;
72743             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
72744             node.declarationText = declarationTextOrJavascriptPath;
72745             node.declarationMapPath = declarationMapPath;
72746             node.declarationMapText = declarationMapTextOrBuildInfoPath;
72747             node.javascriptPath = javascriptPath;
72748             node.declarationPath = declarationPath;
72749             node.buildInfoPath = buildInfoPath;
72750             node.buildInfo = buildInfo;
72751             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
72752         }
72753         return node;
72754     }
72755     ts.createInputFiles = createInputFiles;
72756     function updateBundle(node, sourceFiles, prepends) {
72757         if (prepends === void 0) { prepends = ts.emptyArray; }
72758         if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
72759             return createBundle(sourceFiles, prepends);
72760         }
72761         return node;
72762     }
72763     ts.updateBundle = updateBundle;
72764     function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
72765         return createCall(createFunctionExpression(
72766         /*modifiers*/ undefined, 
72767         /*asteriskToken*/ undefined, 
72768         /*name*/ undefined, 
72769         /*typeParameters*/ undefined, 
72770         /*parameters*/ param ? [param] : [], 
72771         /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72772         /*typeArguments*/ undefined, 
72773         /*argumentsArray*/ paramValue ? [paramValue] : []);
72774     }
72775     ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
72776     function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
72777         return createCall(createArrowFunction(
72778         /*modifiers*/ undefined, 
72779         /*typeParameters*/ undefined, 
72780         /*parameters*/ param ? [param] : [], 
72781         /*type*/ undefined, 
72782         /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72783         /*typeArguments*/ undefined, 
72784         /*argumentsArray*/ paramValue ? [paramValue] : []);
72785     }
72786     ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
72787     function createComma(left, right) {
72788         return createBinary(left, 27 /* CommaToken */, right);
72789     }
72790     ts.createComma = createComma;
72791     function createLessThan(left, right) {
72792         return createBinary(left, 29 /* LessThanToken */, right);
72793     }
72794     ts.createLessThan = createLessThan;
72795     function createAssignment(left, right) {
72796         return createBinary(left, 62 /* EqualsToken */, right);
72797     }
72798     ts.createAssignment = createAssignment;
72799     function createStrictEquality(left, right) {
72800         return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
72801     }
72802     ts.createStrictEquality = createStrictEquality;
72803     function createStrictInequality(left, right) {
72804         return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
72805     }
72806     ts.createStrictInequality = createStrictInequality;
72807     function createAdd(left, right) {
72808         return createBinary(left, 39 /* PlusToken */, right);
72809     }
72810     ts.createAdd = createAdd;
72811     function createSubtract(left, right) {
72812         return createBinary(left, 40 /* MinusToken */, right);
72813     }
72814     ts.createSubtract = createSubtract;
72815     function createPostfixIncrement(operand) {
72816         return createPostfix(operand, 45 /* PlusPlusToken */);
72817     }
72818     ts.createPostfixIncrement = createPostfixIncrement;
72819     function createLogicalAnd(left, right) {
72820         return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
72821     }
72822     ts.createLogicalAnd = createLogicalAnd;
72823     function createLogicalOr(left, right) {
72824         return createBinary(left, 56 /* BarBarToken */, right);
72825     }
72826     ts.createLogicalOr = createLogicalOr;
72827     function createNullishCoalesce(left, right) {
72828         return createBinary(left, 60 /* QuestionQuestionToken */, right);
72829     }
72830     ts.createNullishCoalesce = createNullishCoalesce;
72831     function createLogicalNot(operand) {
72832         return createPrefix(53 /* ExclamationToken */, operand);
72833     }
72834     ts.createLogicalNot = createLogicalNot;
72835     function createVoidZero() {
72836         return createVoid(createLiteral(0));
72837     }
72838     ts.createVoidZero = createVoidZero;
72839     function createExportDefault(expression) {
72840         return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
72841     }
72842     ts.createExportDefault = createExportDefault;
72843     function createExternalModuleExport(exportName) {
72844         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
72845     }
72846     ts.createExternalModuleExport = createExternalModuleExport;
72847     // Utilities
72848     function asName(name) {
72849         return ts.isString(name) ? createIdentifier(name) : name;
72850     }
72851     function asExpression(value) {
72852         return typeof value === "string" ? createStringLiteral(value) :
72853             typeof value === "number" ? createNumericLiteral("" + value) :
72854                 typeof value === "boolean" ? value ? createTrue() : createFalse() :
72855                     value;
72856     }
72857     function asNodeArray(array) {
72858         return array ? createNodeArray(array) : undefined;
72859     }
72860     function asToken(value) {
72861         return typeof value === "number" ? createToken(value) : value;
72862     }
72863     function asEmbeddedStatement(statement) {
72864         return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
72865     }
72866     /**
72867      * Clears any EmitNode entries from parse-tree nodes.
72868      * @param sourceFile A source file.
72869      */
72870     function disposeEmitNodes(sourceFile) {
72871         // During transformation we may need to annotate a parse tree node with transient
72872         // transformation properties. As parse tree nodes live longer than transformation
72873         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
72874         // from these nodes to ensure we do not hold onto entire subtrees just for position
72875         // information. We also need to reset these nodes to a pre-transformation state
72876         // for incremental parsing scenarios so that we do not impact later emit.
72877         sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
72878         var emitNode = sourceFile && sourceFile.emitNode;
72879         var annotatedNodes = emitNode && emitNode.annotatedNodes;
72880         if (annotatedNodes) {
72881             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
72882                 var node = annotatedNodes_1[_i];
72883                 node.emitNode = undefined;
72884             }
72885         }
72886     }
72887     ts.disposeEmitNodes = disposeEmitNodes;
72888     /**
72889      * Associates a node with the current transformation, initializing
72890      * various transient transformation properties.
72891      */
72892     /* @internal */
72893     function getOrCreateEmitNode(node) {
72894         if (!node.emitNode) {
72895             if (ts.isParseTreeNode(node)) {
72896                 // To avoid holding onto transformation artifacts, we keep track of any
72897                 // parse tree node we are annotating. This allows us to clean them up after
72898                 // all transformations have completed.
72899                 if (node.kind === 290 /* SourceFile */) {
72900                     return node.emitNode = { annotatedNodes: [node] };
72901                 }
72902                 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
72903                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
72904             }
72905             node.emitNode = {};
72906         }
72907         return node.emitNode;
72908     }
72909     ts.getOrCreateEmitNode = getOrCreateEmitNode;
72910     /**
72911      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
72912      * @internal
72913      */
72914     function removeAllComments(node) {
72915         var emitNode = getOrCreateEmitNode(node);
72916         emitNode.flags |= 1536 /* NoComments */;
72917         emitNode.leadingComments = undefined;
72918         emitNode.trailingComments = undefined;
72919         return node;
72920     }
72921     ts.removeAllComments = removeAllComments;
72922     function setTextRange(range, location) {
72923         if (location) {
72924             range.pos = location.pos;
72925             range.end = location.end;
72926         }
72927         return range;
72928     }
72929     ts.setTextRange = setTextRange;
72930     /**
72931      * Sets flags that control emit behavior of a node.
72932      */
72933     function setEmitFlags(node, emitFlags) {
72934         getOrCreateEmitNode(node).flags = emitFlags;
72935         return node;
72936     }
72937     ts.setEmitFlags = setEmitFlags;
72938     /**
72939      * Sets flags that control emit behavior of a node.
72940      */
72941     /* @internal */
72942     function addEmitFlags(node, emitFlags) {
72943         var emitNode = getOrCreateEmitNode(node);
72944         emitNode.flags = emitNode.flags | emitFlags;
72945         return node;
72946     }
72947     ts.addEmitFlags = addEmitFlags;
72948     /**
72949      * Gets a custom text range to use when emitting source maps.
72950      */
72951     function getSourceMapRange(node) {
72952         var emitNode = node.emitNode;
72953         return (emitNode && emitNode.sourceMapRange) || node;
72954     }
72955     ts.getSourceMapRange = getSourceMapRange;
72956     /**
72957      * Sets a custom text range to use when emitting source maps.
72958      */
72959     function setSourceMapRange(node, range) {
72960         getOrCreateEmitNode(node).sourceMapRange = range;
72961         return node;
72962     }
72963     ts.setSourceMapRange = setSourceMapRange;
72964     var SourceMapSource;
72965     /**
72966      * Create an external source map source file reference
72967      */
72968     function createSourceMapSource(fileName, text, skipTrivia) {
72969         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
72970     }
72971     ts.createSourceMapSource = createSourceMapSource;
72972     /**
72973      * Gets the TextRange to use for source maps for a token of a node.
72974      */
72975     function getTokenSourceMapRange(node, token) {
72976         var emitNode = node.emitNode;
72977         var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
72978         return tokenSourceMapRanges && tokenSourceMapRanges[token];
72979     }
72980     ts.getTokenSourceMapRange = getTokenSourceMapRange;
72981     /**
72982      * Sets the TextRange to use for source maps for a token of a node.
72983      */
72984     function setTokenSourceMapRange(node, token, range) {
72985         var emitNode = getOrCreateEmitNode(node);
72986         var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
72987         tokenSourceMapRanges[token] = range;
72988         return node;
72989     }
72990     ts.setTokenSourceMapRange = setTokenSourceMapRange;
72991     /**
72992      * Gets a custom text range to use when emitting comments.
72993      */
72994     /*@internal*/
72995     function getStartsOnNewLine(node) {
72996         var emitNode = node.emitNode;
72997         return emitNode && emitNode.startsOnNewLine;
72998     }
72999     ts.getStartsOnNewLine = getStartsOnNewLine;
73000     /**
73001      * Sets a custom text range to use when emitting comments.
73002      */
73003     /*@internal*/
73004     function setStartsOnNewLine(node, newLine) {
73005         getOrCreateEmitNode(node).startsOnNewLine = newLine;
73006         return node;
73007     }
73008     ts.setStartsOnNewLine = setStartsOnNewLine;
73009     /**
73010      * Gets a custom text range to use when emitting comments.
73011      */
73012     function getCommentRange(node) {
73013         var emitNode = node.emitNode;
73014         return (emitNode && emitNode.commentRange) || node;
73015     }
73016     ts.getCommentRange = getCommentRange;
73017     /**
73018      * Sets a custom text range to use when emitting comments.
73019      */
73020     function setCommentRange(node, range) {
73021         getOrCreateEmitNode(node).commentRange = range;
73022         return node;
73023     }
73024     ts.setCommentRange = setCommentRange;
73025     function getSyntheticLeadingComments(node) {
73026         var emitNode = node.emitNode;
73027         return emitNode && emitNode.leadingComments;
73028     }
73029     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
73030     function setSyntheticLeadingComments(node, comments) {
73031         getOrCreateEmitNode(node).leadingComments = comments;
73032         return node;
73033     }
73034     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
73035     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
73036         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
73037     }
73038     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
73039     function getSyntheticTrailingComments(node) {
73040         var emitNode = node.emitNode;
73041         return emitNode && emitNode.trailingComments;
73042     }
73043     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
73044     function setSyntheticTrailingComments(node, comments) {
73045         getOrCreateEmitNode(node).trailingComments = comments;
73046         return node;
73047     }
73048     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
73049     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
73050         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
73051     }
73052     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
73053     function moveSyntheticComments(node, original) {
73054         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
73055         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
73056         var emit = getOrCreateEmitNode(original);
73057         emit.leadingComments = undefined;
73058         emit.trailingComments = undefined;
73059         return node;
73060     }
73061     ts.moveSyntheticComments = moveSyntheticComments;
73062     /** @internal */
73063     function ignoreSourceNewlines(node) {
73064         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
73065         return node;
73066     }
73067     ts.ignoreSourceNewlines = ignoreSourceNewlines;
73068     /**
73069      * Gets the constant value to emit for an expression.
73070      */
73071     function getConstantValue(node) {
73072         var emitNode = node.emitNode;
73073         return emitNode && emitNode.constantValue;
73074     }
73075     ts.getConstantValue = getConstantValue;
73076     /**
73077      * Sets the constant value to emit for an expression.
73078      */
73079     function setConstantValue(node, value) {
73080         var emitNode = getOrCreateEmitNode(node);
73081         emitNode.constantValue = value;
73082         return node;
73083     }
73084     ts.setConstantValue = setConstantValue;
73085     /**
73086      * Adds an EmitHelper to a node.
73087      */
73088     function addEmitHelper(node, helper) {
73089         var emitNode = getOrCreateEmitNode(node);
73090         emitNode.helpers = ts.append(emitNode.helpers, helper);
73091         return node;
73092     }
73093     ts.addEmitHelper = addEmitHelper;
73094     /**
73095      * Add EmitHelpers to a node.
73096      */
73097     function addEmitHelpers(node, helpers) {
73098         if (ts.some(helpers)) {
73099             var emitNode = getOrCreateEmitNode(node);
73100             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
73101                 var helper = helpers_1[_i];
73102                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
73103             }
73104         }
73105         return node;
73106     }
73107     ts.addEmitHelpers = addEmitHelpers;
73108     /**
73109      * Removes an EmitHelper from a node.
73110      */
73111     function removeEmitHelper(node, helper) {
73112         var emitNode = node.emitNode;
73113         if (emitNode) {
73114             var helpers = emitNode.helpers;
73115             if (helpers) {
73116                 return ts.orderedRemoveItem(helpers, helper);
73117             }
73118         }
73119         return false;
73120     }
73121     ts.removeEmitHelper = removeEmitHelper;
73122     /**
73123      * Gets the EmitHelpers of a node.
73124      */
73125     function getEmitHelpers(node) {
73126         var emitNode = node.emitNode;
73127         return emitNode && emitNode.helpers;
73128     }
73129     ts.getEmitHelpers = getEmitHelpers;
73130     /**
73131      * Moves matching emit helpers from a source node to a target node.
73132      */
73133     function moveEmitHelpers(source, target, predicate) {
73134         var sourceEmitNode = source.emitNode;
73135         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
73136         if (!ts.some(sourceEmitHelpers))
73137             return;
73138         var targetEmitNode = getOrCreateEmitNode(target);
73139         var helpersRemoved = 0;
73140         for (var i = 0; i < sourceEmitHelpers.length; i++) {
73141             var helper = sourceEmitHelpers[i];
73142             if (predicate(helper)) {
73143                 helpersRemoved++;
73144                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
73145             }
73146             else if (helpersRemoved > 0) {
73147                 sourceEmitHelpers[i - helpersRemoved] = helper;
73148             }
73149         }
73150         if (helpersRemoved > 0) {
73151             sourceEmitHelpers.length -= helpersRemoved;
73152         }
73153     }
73154     ts.moveEmitHelpers = moveEmitHelpers;
73155     /* @internal */
73156     function compareEmitHelpers(x, y) {
73157         if (x === y)
73158             return 0 /* EqualTo */;
73159         if (x.priority === y.priority)
73160             return 0 /* EqualTo */;
73161         if (x.priority === undefined)
73162             return 1 /* GreaterThan */;
73163         if (y.priority === undefined)
73164             return -1 /* LessThan */;
73165         return ts.compareValues(x.priority, y.priority);
73166     }
73167     ts.compareEmitHelpers = compareEmitHelpers;
73168     function setOriginalNode(node, original) {
73169         node.original = original;
73170         if (original) {
73171             var emitNode = original.emitNode;
73172             if (emitNode)
73173                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
73174         }
73175         return node;
73176     }
73177     ts.setOriginalNode = setOriginalNode;
73178     function mergeEmitNode(sourceEmitNode, destEmitNode) {
73179         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;
73180         if (!destEmitNode)
73181             destEmitNode = {};
73182         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
73183         if (leadingComments)
73184             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
73185         if (trailingComments)
73186             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
73187         if (flags)
73188             destEmitNode.flags = flags;
73189         if (commentRange)
73190             destEmitNode.commentRange = commentRange;
73191         if (sourceMapRange)
73192             destEmitNode.sourceMapRange = sourceMapRange;
73193         if (tokenSourceMapRanges)
73194             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
73195         if (constantValue !== undefined)
73196             destEmitNode.constantValue = constantValue;
73197         if (helpers)
73198             destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
73199         if (startsOnNewLine !== undefined)
73200             destEmitNode.startsOnNewLine = startsOnNewLine;
73201         return destEmitNode;
73202     }
73203     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
73204         if (!destRanges)
73205             destRanges = [];
73206         for (var key in sourceRanges) {
73207             destRanges[key] = sourceRanges[key];
73208         }
73209         return destRanges;
73210     }
73211 })(ts || (ts = {}));
73212 /* @internal */
73213 var ts;
73214 (function (ts) {
73215     ts.nullTransformationContext = {
73216         enableEmitNotification: ts.noop,
73217         enableSubstitution: ts.noop,
73218         endLexicalEnvironment: ts.returnUndefined,
73219         getCompilerOptions: function () { return ({}); },
73220         getEmitHost: ts.notImplemented,
73221         getEmitResolver: ts.notImplemented,
73222         setLexicalEnvironmentFlags: ts.noop,
73223         getLexicalEnvironmentFlags: function () { return 0; },
73224         hoistFunctionDeclaration: ts.noop,
73225         hoistVariableDeclaration: ts.noop,
73226         addInitializationStatement: ts.noop,
73227         isEmitNotificationEnabled: ts.notImplemented,
73228         isSubstitutionEnabled: ts.notImplemented,
73229         onEmitNode: ts.noop,
73230         onSubstituteNode: ts.notImplemented,
73231         readEmitHelpers: ts.notImplemented,
73232         requestEmitHelper: ts.noop,
73233         resumeLexicalEnvironment: ts.noop,
73234         startLexicalEnvironment: ts.noop,
73235         suspendLexicalEnvironment: ts.noop,
73236         addDiagnostic: ts.noop,
73237     };
73238     function createTypeCheck(value, tag) {
73239         return tag === "undefined"
73240             ? ts.createStrictEquality(value, ts.createVoidZero())
73241             : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
73242     }
73243     ts.createTypeCheck = createTypeCheck;
73244     function createMemberAccessForPropertyName(target, memberName, location) {
73245         if (ts.isComputedPropertyName(memberName)) {
73246             return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
73247         }
73248         else {
73249             var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
73250                 ? ts.createPropertyAccess(target, memberName)
73251                 : ts.createElementAccess(target, memberName), memberName);
73252             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
73253             return expression;
73254         }
73255     }
73256     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
73257     function createFunctionCall(func, thisArg, argumentsList, location) {
73258         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
73259         /*typeArguments*/ undefined, __spreadArrays([
73260             thisArg
73261         ], argumentsList)), location);
73262     }
73263     ts.createFunctionCall = createFunctionCall;
73264     function createFunctionApply(func, thisArg, argumentsExpression, location) {
73265         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
73266         /*typeArguments*/ undefined, [
73267             thisArg,
73268             argumentsExpression
73269         ]), location);
73270     }
73271     ts.createFunctionApply = createFunctionApply;
73272     function createArraySlice(array, start) {
73273         var argumentsList = [];
73274         if (start !== undefined) {
73275             argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
73276         }
73277         return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
73278     }
73279     ts.createArraySlice = createArraySlice;
73280     function createArrayConcat(array, values) {
73281         return ts.createCall(ts.createPropertyAccess(array, "concat"), 
73282         /*typeArguments*/ undefined, values);
73283     }
73284     ts.createArrayConcat = createArrayConcat;
73285     function createMathPow(left, right, location) {
73286         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
73287         /*typeArguments*/ undefined, [left, right]), location);
73288     }
73289     ts.createMathPow = createMathPow;
73290     function createReactNamespace(reactNamespace, parent) {
73291         // To ensure the emit resolver can properly resolve the namespace, we need to
73292         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
73293         // flag and setting a parent node.
73294         var react = ts.createIdentifier(reactNamespace || "React");
73295         react.flags &= ~8 /* Synthesized */;
73296         // Set the parent that is in parse tree
73297         // this makes sure that parent chain is intact for checker to traverse complete scope tree
73298         react.parent = ts.getParseTreeNode(parent);
73299         return react;
73300     }
73301     function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
73302         if (ts.isQualifiedName(jsxFactory)) {
73303             var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
73304             var right = ts.createIdentifier(ts.idText(jsxFactory.right));
73305             right.escapedText = jsxFactory.right.escapedText;
73306             return ts.createPropertyAccess(left, right);
73307         }
73308         else {
73309             return createReactNamespace(ts.idText(jsxFactory), parent);
73310         }
73311     }
73312     function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
73313         return jsxFactoryEntity ?
73314             createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
73315             ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
73316     }
73317     function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
73318         var argumentsList = [tagName];
73319         if (props) {
73320             argumentsList.push(props);
73321         }
73322         if (children && children.length > 0) {
73323             if (!props) {
73324                 argumentsList.push(ts.createNull());
73325             }
73326             if (children.length > 1) {
73327                 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
73328                     var child = children_2[_i];
73329                     startOnNewLine(child);
73330                     argumentsList.push(child);
73331                 }
73332             }
73333             else {
73334                 argumentsList.push(children[0]);
73335             }
73336         }
73337         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73338         /*typeArguments*/ undefined, argumentsList), location);
73339     }
73340     ts.createExpressionForJsxElement = createExpressionForJsxElement;
73341     function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
73342         var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
73343         var argumentsList = [tagName];
73344         argumentsList.push(ts.createNull());
73345         if (children && children.length > 0) {
73346             if (children.length > 1) {
73347                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
73348                     var child = children_3[_i];
73349                     startOnNewLine(child);
73350                     argumentsList.push(child);
73351                 }
73352             }
73353             else {
73354                 argumentsList.push(children[0]);
73355             }
73356         }
73357         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73358         /*typeArguments*/ undefined, argumentsList), location);
73359     }
73360     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
73361     // Helpers
73362     /**
73363      * Gets an identifier for the name of an *unscoped* emit helper.
73364      */
73365     function getUnscopedHelperName(name) {
73366         return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
73367     }
73368     ts.getUnscopedHelperName = getUnscopedHelperName;
73369     ts.valuesHelper = {
73370         name: "typescript:values",
73371         importName: "__values",
73372         scoped: false,
73373         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            };"
73374     };
73375     function createValuesHelper(context, expression, location) {
73376         context.requestEmitHelper(ts.valuesHelper);
73377         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"), 
73378         /*typeArguments*/ undefined, [expression]), location);
73379     }
73380     ts.createValuesHelper = createValuesHelper;
73381     ts.readHelper = {
73382         name: "typescript:read",
73383         importName: "__read",
73384         scoped: false,
73385         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            };"
73386     };
73387     function createReadHelper(context, iteratorRecord, count, location) {
73388         context.requestEmitHelper(ts.readHelper);
73389         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"), 
73390         /*typeArguments*/ undefined, count !== undefined
73391             ? [iteratorRecord, ts.createLiteral(count)]
73392             : [iteratorRecord]), location);
73393     }
73394     ts.createReadHelper = createReadHelper;
73395     ts.spreadHelper = {
73396         name: "typescript:spread",
73397         importName: "__spread",
73398         scoped: false,
73399         dependencies: [ts.readHelper],
73400         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            };"
73401     };
73402     function createSpreadHelper(context, argumentList, location) {
73403         context.requestEmitHelper(ts.spreadHelper);
73404         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), 
73405         /*typeArguments*/ undefined, argumentList), location);
73406     }
73407     ts.createSpreadHelper = createSpreadHelper;
73408     ts.spreadArraysHelper = {
73409         name: "typescript:spreadArrays",
73410         importName: "__spreadArrays",
73411         scoped: false,
73412         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            };"
73413     };
73414     function createSpreadArraysHelper(context, argumentList, location) {
73415         context.requestEmitHelper(ts.spreadArraysHelper);
73416         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"), 
73417         /*typeArguments*/ undefined, argumentList), location);
73418     }
73419     ts.createSpreadArraysHelper = createSpreadArraysHelper;
73420     // Utilities
73421     function createForOfBindingStatement(node, boundValue) {
73422         if (ts.isVariableDeclarationList(node)) {
73423             var firstDeclaration = ts.first(node.declarations);
73424             var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
73425             /*typeNode*/ undefined, boundValue);
73426             return ts.setTextRange(ts.createVariableStatement(
73427             /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
73428             /*location*/ node);
73429         }
73430         else {
73431             var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
73432             return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
73433         }
73434     }
73435     ts.createForOfBindingStatement = createForOfBindingStatement;
73436     function insertLeadingStatement(dest, source) {
73437         if (ts.isBlock(dest)) {
73438             return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
73439         }
73440         else {
73441             return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
73442         }
73443     }
73444     ts.insertLeadingStatement = insertLeadingStatement;
73445     function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
73446         if (!outermostLabeledStatement) {
73447             return node;
73448         }
73449         var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
73450             ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
73451             : node);
73452         if (afterRestoreLabelCallback) {
73453             afterRestoreLabelCallback(outermostLabeledStatement);
73454         }
73455         return updated;
73456     }
73457     ts.restoreEnclosingLabel = restoreEnclosingLabel;
73458     function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
73459         var target = ts.skipParentheses(node);
73460         switch (target.kind) {
73461             case 75 /* Identifier */:
73462                 return cacheIdentifiers;
73463             case 104 /* ThisKeyword */:
73464             case 8 /* NumericLiteral */:
73465             case 9 /* BigIntLiteral */:
73466             case 10 /* StringLiteral */:
73467                 return false;
73468             case 192 /* ArrayLiteralExpression */:
73469                 var elements = target.elements;
73470                 if (elements.length === 0) {
73471                     return false;
73472                 }
73473                 return true;
73474             case 193 /* ObjectLiteralExpression */:
73475                 return target.properties.length > 0;
73476             default:
73477                 return true;
73478         }
73479     }
73480     function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
73481         if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
73482         var callee = skipOuterExpressions(expression, 15 /* All */);
73483         var thisArg;
73484         var target;
73485         if (ts.isSuperProperty(callee)) {
73486             thisArg = ts.createThis();
73487             target = callee;
73488         }
73489         else if (callee.kind === 102 /* SuperKeyword */) {
73490             thisArg = ts.createThis();
73491             target = languageVersion < 2 /* ES2015 */
73492                 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
73493                 : callee;
73494         }
73495         else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
73496             thisArg = ts.createVoidZero();
73497             target = parenthesizeForAccess(callee);
73498         }
73499         else {
73500             switch (callee.kind) {
73501                 case 194 /* PropertyAccessExpression */: {
73502                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73503                         // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
73504                         thisArg = ts.createTempVariable(recordTempVariable);
73505                         target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
73506                         ts.setTextRange(target, callee);
73507                     }
73508                     else {
73509                         thisArg = callee.expression;
73510                         target = callee;
73511                     }
73512                     break;
73513                 }
73514                 case 195 /* ElementAccessExpression */: {
73515                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73516                         // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
73517                         thisArg = ts.createTempVariable(recordTempVariable);
73518                         target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
73519                         ts.setTextRange(target, callee);
73520                     }
73521                     else {
73522                         thisArg = callee.expression;
73523                         target = callee;
73524                     }
73525                     break;
73526                 }
73527                 default: {
73528                     // for `a()` target is `a` and thisArg is `void 0`
73529                     thisArg = ts.createVoidZero();
73530                     target = parenthesizeForAccess(expression);
73531                     break;
73532                 }
73533             }
73534         }
73535         return { target: target, thisArg: thisArg };
73536     }
73537     ts.createCallBinding = createCallBinding;
73538     function inlineExpressions(expressions) {
73539         // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
73540         // stack size exceeded" errors.
73541         return expressions.length > 10
73542             ? ts.createCommaList(expressions)
73543             : ts.reduceLeft(expressions, ts.createComma);
73544     }
73545     ts.inlineExpressions = inlineExpressions;
73546     function createExpressionFromEntityName(node) {
73547         if (ts.isQualifiedName(node)) {
73548             var left = createExpressionFromEntityName(node.left);
73549             var right = ts.getMutableClone(node.right);
73550             return ts.setTextRange(ts.createPropertyAccess(left, right), node);
73551         }
73552         else {
73553             return ts.getMutableClone(node);
73554         }
73555     }
73556     ts.createExpressionFromEntityName = createExpressionFromEntityName;
73557     function createExpressionForPropertyName(memberName) {
73558         if (ts.isIdentifier(memberName)) {
73559             return ts.createLiteral(memberName);
73560         }
73561         else if (ts.isComputedPropertyName(memberName)) {
73562             return ts.getMutableClone(memberName.expression);
73563         }
73564         else {
73565             return ts.getMutableClone(memberName);
73566         }
73567     }
73568     ts.createExpressionForPropertyName = createExpressionForPropertyName;
73569     function createExpressionForObjectLiteralElementLike(node, property, receiver) {
73570         if (property.name && ts.isPrivateIdentifier(property.name)) {
73571             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
73572         }
73573         switch (property.kind) {
73574             case 163 /* GetAccessor */:
73575             case 164 /* SetAccessor */:
73576                 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
73577             case 281 /* PropertyAssignment */:
73578                 return createExpressionForPropertyAssignment(property, receiver);
73579             case 282 /* ShorthandPropertyAssignment */:
73580                 return createExpressionForShorthandPropertyAssignment(property, receiver);
73581             case 161 /* MethodDeclaration */:
73582                 return createExpressionForMethodDeclaration(property, receiver);
73583         }
73584     }
73585     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
73586     function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
73587         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73588         if (property === firstAccessor) {
73589             var properties_7 = [];
73590             if (getAccessor) {
73591                 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
73592                 /*asteriskToken*/ undefined, 
73593                 /*name*/ undefined, 
73594                 /*typeParameters*/ undefined, getAccessor.parameters, 
73595                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
73596                 );
73597                 ts.setTextRange(getterFunction, getAccessor);
73598                 ts.setOriginalNode(getterFunction, getAccessor);
73599                 var getter = ts.createPropertyAssignment("get", getterFunction);
73600                 properties_7.push(getter);
73601             }
73602             if (setAccessor) {
73603                 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
73604                 /*asteriskToken*/ undefined, 
73605                 /*name*/ undefined, 
73606                 /*typeParameters*/ undefined, setAccessor.parameters, 
73607                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
73608                 );
73609                 ts.setTextRange(setterFunction, setAccessor);
73610                 ts.setOriginalNode(setterFunction, setAccessor);
73611                 var setter = ts.createPropertyAssignment("set", setterFunction);
73612                 properties_7.push(setter);
73613             }
73614             properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()));
73615             properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
73616             var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
73617             /*typeArguments*/ undefined, [
73618                 receiver,
73619                 createExpressionForPropertyName(property.name),
73620                 ts.createObjectLiteral(properties_7, multiLine)
73621             ]), 
73622             /*location*/ firstAccessor);
73623             return ts.aggregateTransformFlags(expression);
73624         }
73625         return undefined;
73626     }
73627     function createExpressionForPropertyAssignment(property, receiver) {
73628         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
73629     }
73630     function createExpressionForShorthandPropertyAssignment(property, receiver) {
73631         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
73632         /*location*/ property), 
73633         /*original*/ property));
73634     }
73635     function createExpressionForMethodDeclaration(method, receiver) {
73636         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, 
73637         /*name*/ undefined, 
73638         /*typeParameters*/ undefined, method.parameters, 
73639         /*type*/ undefined, method.body // TODO: GH#18217
73640         ), 
73641         /*location*/ method), 
73642         /*original*/ method)), 
73643         /*location*/ method), 
73644         /*original*/ method));
73645     }
73646     /**
73647      * Gets the internal name of a declaration. This is primarily used for declarations that can be
73648      * referred to by name in the body of an ES5 class function body. An internal name will *never*
73649      * be prefixed with an module or namespace export modifier like "exports." when emitted as an
73650      * expression. An internal name will also *never* be renamed due to a collision with a block
73651      * scoped variable.
73652      *
73653      * @param node The declaration.
73654      * @param allowComments A value indicating whether comments may be emitted for the name.
73655      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73656      */
73657     function getInternalName(node, allowComments, allowSourceMaps) {
73658         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
73659     }
73660     ts.getInternalName = getInternalName;
73661     /**
73662      * Gets whether an identifier should only be referred to by its internal name.
73663      */
73664     function isInternalName(node) {
73665         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
73666     }
73667     ts.isInternalName = isInternalName;
73668     /**
73669      * Gets the local name of a declaration. This is primarily used for declarations that can be
73670      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
73671      * local name will *never* be prefixed with an module or namespace export modifier like
73672      * "exports." when emitted as an expression.
73673      *
73674      * @param node The declaration.
73675      * @param allowComments A value indicating whether comments may be emitted for the name.
73676      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73677      */
73678     function getLocalName(node, allowComments, allowSourceMaps) {
73679         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
73680     }
73681     ts.getLocalName = getLocalName;
73682     /**
73683      * Gets whether an identifier should only be referred to by its local name.
73684      */
73685     function isLocalName(node) {
73686         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
73687     }
73688     ts.isLocalName = isLocalName;
73689     /**
73690      * Gets the export name of a declaration. This is primarily used for declarations that can be
73691      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
73692      * export name will *always* be prefixed with an module or namespace export modifier like
73693      * `"exports."` when emitted as an expression if the name points to an exported symbol.
73694      *
73695      * @param node The declaration.
73696      * @param allowComments A value indicating whether comments may be emitted for the name.
73697      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73698      */
73699     function getExportName(node, allowComments, allowSourceMaps) {
73700         return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
73701     }
73702     ts.getExportName = getExportName;
73703     /**
73704      * Gets whether an identifier should only be referred to by its export representation if the
73705      * name points to an exported symbol.
73706      */
73707     function isExportName(node) {
73708         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
73709     }
73710     ts.isExportName = isExportName;
73711     /**
73712      * Gets the name of a declaration for use in declarations.
73713      *
73714      * @param node The declaration.
73715      * @param allowComments A value indicating whether comments may be emitted for the name.
73716      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73717      */
73718     function getDeclarationName(node, allowComments, allowSourceMaps) {
73719         return getName(node, allowComments, allowSourceMaps);
73720     }
73721     ts.getDeclarationName = getDeclarationName;
73722     function getName(node, allowComments, allowSourceMaps, emitFlags) {
73723         if (emitFlags === void 0) { emitFlags = 0; }
73724         var nodeName = ts.getNameOfDeclaration(node);
73725         if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
73726             var name = ts.getMutableClone(nodeName);
73727             emitFlags |= ts.getEmitFlags(nodeName);
73728             if (!allowSourceMaps)
73729                 emitFlags |= 48 /* NoSourceMap */;
73730             if (!allowComments)
73731                 emitFlags |= 1536 /* NoComments */;
73732             if (emitFlags)
73733                 ts.setEmitFlags(name, emitFlags);
73734             return name;
73735         }
73736         return ts.getGeneratedNameForNode(node);
73737     }
73738     /**
73739      * Gets the exported name of a declaration for use in expressions.
73740      *
73741      * An exported name will *always* be prefixed with an module or namespace export modifier like
73742      * "exports." if the name points to an exported symbol.
73743      *
73744      * @param ns The namespace identifier.
73745      * @param node The declaration.
73746      * @param allowComments A value indicating whether comments may be emitted for the name.
73747      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73748      */
73749     function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
73750         if (ns && ts.hasModifier(node, 1 /* Export */)) {
73751             return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
73752         }
73753         return getExportName(node, allowComments, allowSourceMaps);
73754     }
73755     ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
73756     /**
73757      * Gets a namespace-qualified name for use in expressions.
73758      *
73759      * @param ns The namespace identifier.
73760      * @param name The name.
73761      * @param allowComments A value indicating whether comments may be emitted for the name.
73762      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73763      */
73764     function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
73765         var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
73766         ts.setTextRange(qualifiedName, name);
73767         var emitFlags = 0;
73768         if (!allowSourceMaps)
73769             emitFlags |= 48 /* NoSourceMap */;
73770         if (!allowComments)
73771             emitFlags |= 1536 /* NoComments */;
73772         if (emitFlags)
73773             ts.setEmitFlags(qualifiedName, emitFlags);
73774         return qualifiedName;
73775     }
73776     ts.getNamespaceMemberName = getNamespaceMemberName;
73777     function convertToFunctionBody(node, multiLine) {
73778         return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
73779     }
73780     ts.convertToFunctionBody = convertToFunctionBody;
73781     function convertFunctionDeclarationToExpression(node) {
73782         if (!node.body)
73783             return ts.Debug.fail();
73784         var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
73785         ts.setOriginalNode(updated, node);
73786         ts.setTextRange(updated, node);
73787         if (ts.getStartsOnNewLine(node)) {
73788             ts.setStartsOnNewLine(updated, /*newLine*/ true);
73789         }
73790         ts.aggregateTransformFlags(updated);
73791         return updated;
73792     }
73793     ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
73794     function isUseStrictPrologue(node) {
73795         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
73796     }
73797     /**
73798      * Add any necessary prologue-directives into target statement-array.
73799      * The function needs to be called during each transformation step.
73800      * This function needs to be called whenever we transform the statement
73801      * list of a source file, namespace, or function-like body.
73802      *
73803      * @param target: result statements array
73804      * @param source: origin statements array
73805      * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
73806      * @param visitor: Optional callback used to visit any custom prologue directives.
73807      */
73808     function addPrologue(target, source, ensureUseStrict, visitor) {
73809         var offset = addStandardPrologue(target, source, ensureUseStrict);
73810         return addCustomPrologue(target, source, offset, visitor);
73811     }
73812     ts.addPrologue = addPrologue;
73813     /**
73814      * Add just the standard (string-expression) prologue-directives into target statement-array.
73815      * The function needs to be called during each transformation step.
73816      * This function needs to be called whenever we transform the statement
73817      * list of a source file, namespace, or function-like body.
73818      */
73819     function addStandardPrologue(target, source, ensureUseStrict) {
73820         ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
73821         var foundUseStrict = false;
73822         var statementOffset = 0;
73823         var numStatements = source.length;
73824         while (statementOffset < numStatements) {
73825             var statement = source[statementOffset];
73826             if (ts.isPrologueDirective(statement)) {
73827                 if (isUseStrictPrologue(statement)) {
73828                     foundUseStrict = true;
73829                 }
73830                 target.push(statement);
73831             }
73832             else {
73833                 break;
73834             }
73835             statementOffset++;
73836         }
73837         if (ensureUseStrict && !foundUseStrict) {
73838             target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
73839         }
73840         return statementOffset;
73841     }
73842     ts.addStandardPrologue = addStandardPrologue;
73843     function addCustomPrologue(target, source, statementOffset, visitor, filter) {
73844         if (filter === void 0) { filter = ts.returnTrue; }
73845         var numStatements = source.length;
73846         while (statementOffset !== undefined && statementOffset < numStatements) {
73847             var statement = source[statementOffset];
73848             if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
73849                 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
73850             }
73851             else {
73852                 break;
73853             }
73854             statementOffset++;
73855         }
73856         return statementOffset;
73857     }
73858     ts.addCustomPrologue = addCustomPrologue;
73859     function findUseStrictPrologue(statements) {
73860         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73861             var statement = statements_4[_i];
73862             if (ts.isPrologueDirective(statement)) {
73863                 if (isUseStrictPrologue(statement)) {
73864                     return statement;
73865                 }
73866             }
73867             else {
73868                 break;
73869             }
73870         }
73871         return undefined;
73872     }
73873     ts.findUseStrictPrologue = findUseStrictPrologue;
73874     function startsWithUseStrict(statements) {
73875         var firstStatement = ts.firstOrUndefined(statements);
73876         return firstStatement !== undefined
73877             && ts.isPrologueDirective(firstStatement)
73878             && isUseStrictPrologue(firstStatement);
73879     }
73880     ts.startsWithUseStrict = startsWithUseStrict;
73881     /**
73882      * Ensures "use strict" directive is added
73883      *
73884      * @param statements An array of statements
73885      */
73886     function ensureUseStrict(statements) {
73887         var foundUseStrict = findUseStrictPrologue(statements);
73888         if (!foundUseStrict) {
73889             return ts.setTextRange(ts.createNodeArray(__spreadArrays([
73890                 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
73891             ], statements)), statements);
73892         }
73893         return statements;
73894     }
73895     ts.ensureUseStrict = ensureUseStrict;
73896     /**
73897      * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
73898      * order of operations.
73899      *
73900      * @param binaryOperator The operator for the BinaryExpression.
73901      * @param operand The operand for the BinaryExpression.
73902      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73903      *                           BinaryExpression.
73904      */
73905     function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73906         var skipped = ts.skipPartiallyEmittedExpressions(operand);
73907         // If the resulting expression is already parenthesized, we do not need to do any further processing.
73908         if (skipped.kind === 200 /* ParenthesizedExpression */) {
73909             return operand;
73910         }
73911         return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
73912             ? ts.createParen(operand)
73913             : operand;
73914     }
73915     ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
73916     /**
73917      * Determines whether the operand to a BinaryExpression needs to be parenthesized.
73918      *
73919      * @param binaryOperator The operator for the BinaryExpression.
73920      * @param operand The operand for the BinaryExpression.
73921      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73922      *                           BinaryExpression.
73923      */
73924     function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73925         // If the operand has lower precedence, then it needs to be parenthesized to preserve the
73926         // intent of the expression. For example, if the operand is `a + b` and the operator is
73927         // `*`, then we need to parenthesize the operand to preserve the intended order of
73928         // operations: `(a + b) * x`.
73929         //
73930         // If the operand has higher precedence, then it does not need to be parenthesized. For
73931         // example, if the operand is `a * b` and the operator is `+`, then we do not need to
73932         // parenthesize to preserve the intended order of operations: `a * b + x`.
73933         //
73934         // If the operand has the same precedence, then we need to check the associativity of
73935         // the operator based on whether this is the left or right operand of the expression.
73936         //
73937         // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
73938         // to preserve the intended order of operations: `x * (a / d)`
73939         //
73940         // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
73941         // the intended order of operations: `(a ** b) ** c`
73942         var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
73943         var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
73944         var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
73945         if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
73946             // We need to parenthesize arrow functions on the right side to avoid it being
73947             // parsed as parenthesized expression: `a && (() => {})`
73948             return true;
73949         }
73950         var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
73951         switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
73952             case -1 /* LessThan */:
73953                 // If the operand is the right side of a right-associative binary operation
73954                 // and is a yield expression, then we do not need parentheses.
73955                 if (!isLeftSideOfBinary
73956                     && binaryOperatorAssociativity === 1 /* Right */
73957                     && operand.kind === 212 /* YieldExpression */) {
73958                     return false;
73959                 }
73960                 return true;
73961             case 1 /* GreaterThan */:
73962                 return false;
73963             case 0 /* EqualTo */:
73964                 if (isLeftSideOfBinary) {
73965                     // No need to parenthesize the left operand when the binary operator is
73966                     // left associative:
73967                     //  (a*b)/x    -> a*b/x
73968                     //  (a**b)/x   -> a**b/x
73969                     //
73970                     // Parentheses are needed for the left operand when the binary operator is
73971                     // right associative:
73972                     //  (a/b)**x   -> (a/b)**x
73973                     //  (a**b)**x  -> (a**b)**x
73974                     return binaryOperatorAssociativity === 1 /* Right */;
73975                 }
73976                 else {
73977                     if (ts.isBinaryExpression(emittedOperand)
73978                         && emittedOperand.operatorToken.kind === binaryOperator) {
73979                         // No need to parenthesize the right operand when the binary operator and
73980                         // operand are the same and one of the following:
73981                         //  x*(a*b)     => x*a*b
73982                         //  x|(a|b)     => x|a|b
73983                         //  x&(a&b)     => x&a&b
73984                         //  x^(a^b)     => x^a^b
73985                         if (operatorHasAssociativeProperty(binaryOperator)) {
73986                             return false;
73987                         }
73988                         // No need to parenthesize the right operand when the binary operator
73989                         // is plus (+) if both the left and right operands consist solely of either
73990                         // literals of the same kind or binary plus (+) expressions for literals of
73991                         // the same kind (recursively).
73992                         //  "a"+(1+2)       => "a"+(1+2)
73993                         //  "a"+("b"+"c")   => "a"+"b"+"c"
73994                         if (binaryOperator === 39 /* PlusToken */) {
73995                             var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
73996                             if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
73997                                 return false;
73998                             }
73999                         }
74000                     }
74001                     // No need to parenthesize the right operand when the operand is right
74002                     // associative:
74003                     //  x/(a**b)    -> x/a**b
74004                     //  x**(a**b)   -> x**a**b
74005                     //
74006                     // Parentheses are needed for the right operand when the operand is left
74007                     // associative:
74008                     //  x/(a*b)     -> x/(a*b)
74009                     //  x**(a/b)    -> x**(a/b)
74010                     var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
74011                     return operandAssociativity === 0 /* Left */;
74012                 }
74013         }
74014     }
74015     /**
74016      * Determines whether a binary operator is mathematically associative.
74017      *
74018      * @param binaryOperator The binary operator.
74019      */
74020     function operatorHasAssociativeProperty(binaryOperator) {
74021         // The following operators are associative in JavaScript:
74022         //  (a*b)*c     -> a*(b*c)  -> a*b*c
74023         //  (a|b)|c     -> a|(b|c)  -> a|b|c
74024         //  (a&b)&c     -> a&(b&c)  -> a&b&c
74025         //  (a^b)^c     -> a^(b^c)  -> a^b^c
74026         //
74027         // While addition is associative in mathematics, JavaScript's `+` is not
74028         // guaranteed to be associative as it is overloaded with string concatenation.
74029         return binaryOperator === 41 /* AsteriskToken */
74030             || binaryOperator === 51 /* BarToken */
74031             || binaryOperator === 50 /* AmpersandToken */
74032             || binaryOperator === 52 /* CaretToken */;
74033     }
74034     /**
74035      * This function determines whether an expression consists of a homogeneous set of
74036      * literal expressions or binary plus expressions that all share the same literal kind.
74037      * It is used to determine whether the right-hand operand of a binary plus expression can be
74038      * emitted without parentheses.
74039      */
74040     function getLiteralKindOfBinaryPlusOperand(node) {
74041         node = ts.skipPartiallyEmittedExpressions(node);
74042         if (ts.isLiteralKind(node.kind)) {
74043             return node.kind;
74044         }
74045         if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
74046             if (node.cachedLiteralKind !== undefined) {
74047                 return node.cachedLiteralKind;
74048             }
74049             var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
74050             var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
74051                 0 /* Unknown */;
74052             node.cachedLiteralKind = literalKind;
74053             return literalKind;
74054         }
74055         return 0 /* Unknown */;
74056     }
74057     function parenthesizeForConditionalHead(condition) {
74058         var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
74059         var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
74060         var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
74061         if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
74062             return ts.createParen(condition);
74063         }
74064         return condition;
74065     }
74066     ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
74067     function parenthesizeSubexpressionOfConditionalExpression(e) {
74068         // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
74069         // so in case when comma expression is introduced as a part of previous transformations
74070         // if should be wrapped in parens since comma operator has the lowest precedence
74071         var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
74072         return isCommaSequence(emittedExpression)
74073             ? ts.createParen(e)
74074             : e;
74075     }
74076     ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
74077     /**
74078      *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
74079      *  has a lookahead restriction for `function`, `async function`, and `class`.
74080      *
74081      * Basically, that means we need to parenthesize in the following cases:
74082      *
74083      * - BinaryExpression of CommaToken
74084      * - CommaList (synthetic list of multiple comma expressions)
74085      * - FunctionExpression
74086      * - ClassExpression
74087      */
74088     function parenthesizeDefaultExpression(e) {
74089         var check = ts.skipPartiallyEmittedExpressions(e);
74090         var needsParens = isCommaSequence(check);
74091         if (!needsParens) {
74092             switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
74093                 case 214 /* ClassExpression */:
74094                 case 201 /* FunctionExpression */:
74095                     needsParens = true;
74096             }
74097         }
74098         return needsParens ? ts.createParen(e) : e;
74099     }
74100     ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
74101     /**
74102      * Wraps an expression in parentheses if it is needed in order to use the expression
74103      * as the expression of a NewExpression node.
74104      *
74105      * @param expression The Expression node.
74106      */
74107     function parenthesizeForNew(expression) {
74108         var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
74109         switch (leftmostExpr.kind) {
74110             case 196 /* CallExpression */:
74111                 return ts.createParen(expression);
74112             case 197 /* NewExpression */:
74113                 return !leftmostExpr.arguments
74114                     ? ts.createParen(expression)
74115                     : expression;
74116         }
74117         return parenthesizeForAccess(expression);
74118     }
74119     ts.parenthesizeForNew = parenthesizeForNew;
74120     /**
74121      * Wraps an expression in parentheses if it is needed in order to use the expression for
74122      * property or element access.
74123      *
74124      * @param expr The expression node.
74125      */
74126     function parenthesizeForAccess(expression) {
74127         // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
74128         // to parenthesize the expression before a dot. The known exception is:
74129         //
74130         //    NewExpression:
74131         //       new C.x        -> not the same as (new C).x
74132         //
74133         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74134         if (ts.isLeftHandSideExpression(emittedExpression)
74135             && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
74136             return expression;
74137         }
74138         return ts.setTextRange(ts.createParen(expression), expression);
74139     }
74140     ts.parenthesizeForAccess = parenthesizeForAccess;
74141     function parenthesizePostfixOperand(operand) {
74142         return ts.isLeftHandSideExpression(operand)
74143             ? operand
74144             : ts.setTextRange(ts.createParen(operand), operand);
74145     }
74146     ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
74147     function parenthesizePrefixOperand(operand) {
74148         return ts.isUnaryExpression(operand)
74149             ? operand
74150             : ts.setTextRange(ts.createParen(operand), operand);
74151     }
74152     ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
74153     function parenthesizeListElements(elements) {
74154         var result;
74155         for (var i = 0; i < elements.length; i++) {
74156             var element = parenthesizeExpressionForList(elements[i]);
74157             if (result !== undefined || element !== elements[i]) {
74158                 if (result === undefined) {
74159                     result = elements.slice(0, i);
74160                 }
74161                 result.push(element);
74162             }
74163         }
74164         if (result !== undefined) {
74165             return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
74166         }
74167         return elements;
74168     }
74169     ts.parenthesizeListElements = parenthesizeListElements;
74170     function parenthesizeExpressionForList(expression) {
74171         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74172         var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
74173         var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
74174         return expressionPrecedence > commaPrecedence
74175             ? expression
74176             : ts.setTextRange(ts.createParen(expression), expression);
74177     }
74178     ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
74179     function parenthesizeExpressionForExpressionStatement(expression) {
74180         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74181         if (ts.isCallExpression(emittedExpression)) {
74182             var callee = emittedExpression.expression;
74183             var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
74184             if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
74185                 var mutableCall = ts.getMutableClone(emittedExpression);
74186                 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
74187                 return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */);
74188             }
74189         }
74190         var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
74191         if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
74192             return ts.setTextRange(ts.createParen(expression), expression);
74193         }
74194         return expression;
74195     }
74196     ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
74197     function parenthesizeConditionalTypeMember(member) {
74198         return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
74199     }
74200     ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
74201     function parenthesizeElementTypeMember(member) {
74202         switch (member.kind) {
74203             case 178 /* UnionType */:
74204             case 179 /* IntersectionType */:
74205             case 170 /* FunctionType */:
74206             case 171 /* ConstructorType */:
74207                 return ts.createParenthesizedType(member);
74208         }
74209         return parenthesizeConditionalTypeMember(member);
74210     }
74211     ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
74212     function parenthesizeArrayTypeMember(member) {
74213         switch (member.kind) {
74214             case 172 /* TypeQuery */:
74215             case 184 /* TypeOperator */:
74216             case 181 /* InferType */:
74217                 return ts.createParenthesizedType(member);
74218         }
74219         return parenthesizeElementTypeMember(member);
74220     }
74221     ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
74222     function parenthesizeElementTypeMembers(members) {
74223         return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
74224     }
74225     ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
74226     function parenthesizeTypeParameters(typeParameters) {
74227         if (ts.some(typeParameters)) {
74228             var params = [];
74229             for (var i = 0; i < typeParameters.length; ++i) {
74230                 var entry = typeParameters[i];
74231                 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
74232                     ts.createParenthesizedType(entry) :
74233                     entry);
74234             }
74235             return ts.createNodeArray(params);
74236         }
74237     }
74238     ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
74239     function getLeftmostExpression(node, stopAtCallExpressions) {
74240         while (true) {
74241             switch (node.kind) {
74242                 case 208 /* PostfixUnaryExpression */:
74243                     node = node.operand;
74244                     continue;
74245                 case 209 /* BinaryExpression */:
74246                     node = node.left;
74247                     continue;
74248                 case 210 /* ConditionalExpression */:
74249                     node = node.condition;
74250                     continue;
74251                 case 198 /* TaggedTemplateExpression */:
74252                     node = node.tag;
74253                     continue;
74254                 case 196 /* CallExpression */:
74255                     if (stopAtCallExpressions) {
74256                         return node;
74257                     }
74258                 // falls through
74259                 case 217 /* AsExpression */:
74260                 case 195 /* ElementAccessExpression */:
74261                 case 194 /* PropertyAccessExpression */:
74262                 case 218 /* NonNullExpression */:
74263                 case 326 /* PartiallyEmittedExpression */:
74264                     node = node.expression;
74265                     continue;
74266             }
74267             return node;
74268         }
74269     }
74270     ts.getLeftmostExpression = getLeftmostExpression;
74271     function parenthesizeConciseBody(body) {
74272         if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
74273             return ts.setTextRange(ts.createParen(body), body);
74274         }
74275         return body;
74276     }
74277     ts.parenthesizeConciseBody = parenthesizeConciseBody;
74278     function isCommaSequence(node) {
74279         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
74280             node.kind === 327 /* CommaListExpression */;
74281     }
74282     ts.isCommaSequence = isCommaSequence;
74283     var OuterExpressionKinds;
74284     (function (OuterExpressionKinds) {
74285         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
74286         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
74287         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
74288         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
74289         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
74290         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
74291     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
74292     function isOuterExpression(node, kinds) {
74293         if (kinds === void 0) { kinds = 15 /* All */; }
74294         switch (node.kind) {
74295             case 200 /* ParenthesizedExpression */:
74296                 return (kinds & 1 /* Parentheses */) !== 0;
74297             case 199 /* TypeAssertionExpression */:
74298             case 217 /* AsExpression */:
74299                 return (kinds & 2 /* TypeAssertions */) !== 0;
74300             case 218 /* NonNullExpression */:
74301                 return (kinds & 4 /* NonNullAssertions */) !== 0;
74302             case 326 /* PartiallyEmittedExpression */:
74303                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
74304         }
74305         return false;
74306     }
74307     ts.isOuterExpression = isOuterExpression;
74308     function skipOuterExpressions(node, kinds) {
74309         if (kinds === void 0) { kinds = 15 /* All */; }
74310         while (isOuterExpression(node, kinds)) {
74311             node = node.expression;
74312         }
74313         return node;
74314     }
74315     ts.skipOuterExpressions = skipOuterExpressions;
74316     function skipAssertions(node) {
74317         return skipOuterExpressions(node, 6 /* Assertions */);
74318     }
74319     ts.skipAssertions = skipAssertions;
74320     function updateOuterExpression(outerExpression, expression) {
74321         switch (outerExpression.kind) {
74322             case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
74323             case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
74324             case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
74325             case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
74326             case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
74327         }
74328     }
74329     /**
74330      * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
74331      *
74332      * A parenthesized expression can be ignored when all of the following are true:
74333      *
74334      * - It's `pos` and `end` are not -1
74335      * - It does not have a custom source map range
74336      * - It does not have a custom comment range
74337      * - It does not have synthetic leading or trailing comments
74338      *
74339      * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
74340      * the expression to maintain precedence, a new parenthesized expression should be created automatically when
74341      * the containing expression is created/updated.
74342      */
74343     function isIgnorableParen(node) {
74344         return node.kind === 200 /* ParenthesizedExpression */
74345             && ts.nodeIsSynthesized(node)
74346             && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
74347             && ts.nodeIsSynthesized(ts.getCommentRange(node))
74348             && !ts.some(ts.getSyntheticLeadingComments(node))
74349             && !ts.some(ts.getSyntheticTrailingComments(node));
74350     }
74351     function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
74352         if (kinds === void 0) { kinds = 15 /* All */; }
74353         if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
74354             return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
74355         }
74356         return innerExpression;
74357     }
74358     ts.recreateOuterExpressions = recreateOuterExpressions;
74359     function startOnNewLine(node) {
74360         return ts.setStartsOnNewLine(node, /*newLine*/ true);
74361     }
74362     ts.startOnNewLine = startOnNewLine;
74363     function getExternalHelpersModuleName(node) {
74364         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74365         var emitNode = parseNode && parseNode.emitNode;
74366         return emitNode && emitNode.externalHelpersModuleName;
74367     }
74368     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
74369     function hasRecordedExternalHelpers(sourceFile) {
74370         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74371         var emitNode = parseNode && parseNode.emitNode;
74372         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
74373     }
74374     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
74375     function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
74376         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
74377             var namedBindings = void 0;
74378             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74379             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
74380                 // use named imports
74381                 var helpers = ts.getEmitHelpers(sourceFile);
74382                 if (helpers) {
74383                     var helperNames = [];
74384                     for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
74385                         var helper = helpers_2[_i];
74386                         if (!helper.scoped) {
74387                             var importName = helper.importName;
74388                             if (importName) {
74389                                 ts.pushIfUnique(helperNames, importName);
74390                             }
74391                         }
74392                     }
74393                     if (ts.some(helperNames)) {
74394                         helperNames.sort(ts.compareStringsCaseSensitive);
74395                         // Alias the imports if the names are used somewhere in the file.
74396                         // NOTE: We don't need to care about global import collisions as this is a module.
74397                         namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
74398                             ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
74399                             : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
74400                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74401                         var emitNode = ts.getOrCreateEmitNode(parseNode);
74402                         emitNode.externalHelpers = true;
74403                     }
74404                 }
74405             }
74406             else {
74407                 // use a namespace import
74408                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
74409                 if (externalHelpersModuleName) {
74410                     namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
74411                 }
74412             }
74413             if (namedBindings) {
74414                 var externalHelpersImportDeclaration = ts.createImportDeclaration(
74415                 /*decorators*/ undefined, 
74416                 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
74417                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
74418                 return externalHelpersImportDeclaration;
74419             }
74420         }
74421     }
74422     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
74423     function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
74424         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
74425             var externalHelpersModuleName = getExternalHelpersModuleName(node);
74426             if (externalHelpersModuleName) {
74427                 return externalHelpersModuleName;
74428             }
74429             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74430             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
74431                 && moduleKind !== ts.ModuleKind.System
74432                 && moduleKind < ts.ModuleKind.ES2015;
74433             if (!create) {
74434                 var helpers = ts.getEmitHelpers(node);
74435                 if (helpers) {
74436                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
74437                         var helper = helpers_3[_i];
74438                         if (!helper.scoped) {
74439                             create = true;
74440                             break;
74441                         }
74442                     }
74443                 }
74444             }
74445             if (create) {
74446                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74447                 var emitNode = ts.getOrCreateEmitNode(parseNode);
74448                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
74449             }
74450         }
74451     }
74452     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
74453     /**
74454      * Get the name of that target module from an import or export declaration
74455      */
74456     function getLocalNameForExternalImport(node, sourceFile) {
74457         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
74458         if (namespaceDeclaration && !ts.isDefaultImport(node)) {
74459             var name = namespaceDeclaration.name;
74460             return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
74461         }
74462         if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
74463             return ts.getGeneratedNameForNode(node);
74464         }
74465         if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
74466             return ts.getGeneratedNameForNode(node);
74467         }
74468         return undefined;
74469     }
74470     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
74471     /**
74472      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
74473      * The emitted output name can be different from the input if:
74474      *  1. The module has a /// <amd-module name="<new name>" />
74475      *  2. --out or --outFile is used, making the name relative to the rootDir
74476      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
74477      * Otherwise, a new StringLiteral node representing the module name will be returned.
74478      */
74479     function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
74480         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
74481         if (moduleName.kind === 10 /* StringLiteral */) {
74482             return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
74483                 || tryRenameExternalModule(moduleName, sourceFile)
74484                 || ts.getSynthesizedClone(moduleName);
74485         }
74486         return undefined;
74487     }
74488     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
74489     /**
74490      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
74491      * Here we check if alternative name was provided for a given moduleName and return it if possible.
74492      */
74493     function tryRenameExternalModule(moduleName, sourceFile) {
74494         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
74495         return rename && ts.createLiteral(rename);
74496     }
74497     /**
74498      * Get the name of a module as should be written in the emitted output.
74499      * The emitted output name can be different from the input if:
74500      *  1. The module has a /// <amd-module name="<new name>" />
74501      *  2. --out or --outFile is used, making the name relative to the rootDir
74502      * Otherwise, a new StringLiteral node representing the module name will be returned.
74503      */
74504     function tryGetModuleNameFromFile(file, host, options) {
74505         if (!file) {
74506             return undefined;
74507         }
74508         if (file.moduleName) {
74509             return ts.createLiteral(file.moduleName);
74510         }
74511         if (!file.isDeclarationFile && (options.out || options.outFile)) {
74512             return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
74513         }
74514         return undefined;
74515     }
74516     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
74517     function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
74518         return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
74519     }
74520     /**
74521      * Gets the initializer of an BindingOrAssignmentElement.
74522      */
74523     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
74524         if (ts.isDeclarationBindingElement(bindingElement)) {
74525             // `1` in `let { a = 1 } = ...`
74526             // `1` in `let { a: b = 1 } = ...`
74527             // `1` in `let { a: {b} = 1 } = ...`
74528             // `1` in `let { a: [b] = 1 } = ...`
74529             // `1` in `let [a = 1] = ...`
74530             // `1` in `let [{a} = 1] = ...`
74531             // `1` in `let [[a] = 1] = ...`
74532             return bindingElement.initializer;
74533         }
74534         if (ts.isPropertyAssignment(bindingElement)) {
74535             // `1` in `({ a: b = 1 } = ...)`
74536             // `1` in `({ a: {b} = 1 } = ...)`
74537             // `1` in `({ a: [b] = 1 } = ...)`
74538             var initializer = bindingElement.initializer;
74539             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
74540                 ? initializer.right
74541                 : undefined;
74542         }
74543         if (ts.isShorthandPropertyAssignment(bindingElement)) {
74544             // `1` in `({ a = 1 } = ...)`
74545             return bindingElement.objectAssignmentInitializer;
74546         }
74547         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74548             // `1` in `[a = 1] = ...`
74549             // `1` in `[{a} = 1] = ...`
74550             // `1` in `[[a] = 1] = ...`
74551             return bindingElement.right;
74552         }
74553         if (ts.isSpreadElement(bindingElement)) {
74554             // Recovery consistent with existing emit.
74555             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
74556         }
74557     }
74558     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
74559     /**
74560      * Gets the name of an BindingOrAssignmentElement.
74561      */
74562     function getTargetOfBindingOrAssignmentElement(bindingElement) {
74563         if (ts.isDeclarationBindingElement(bindingElement)) {
74564             // `a` in `let { a } = ...`
74565             // `a` in `let { a = 1 } = ...`
74566             // `b` in `let { a: b } = ...`
74567             // `b` in `let { a: b = 1 } = ...`
74568             // `a` in `let { ...a } = ...`
74569             // `{b}` in `let { a: {b} } = ...`
74570             // `{b}` in `let { a: {b} = 1 } = ...`
74571             // `[b]` in `let { a: [b] } = ...`
74572             // `[b]` in `let { a: [b] = 1 } = ...`
74573             // `a` in `let [a] = ...`
74574             // `a` in `let [a = 1] = ...`
74575             // `a` in `let [...a] = ...`
74576             // `{a}` in `let [{a}] = ...`
74577             // `{a}` in `let [{a} = 1] = ...`
74578             // `[a]` in `let [[a]] = ...`
74579             // `[a]` in `let [[a] = 1] = ...`
74580             return bindingElement.name;
74581         }
74582         if (ts.isObjectLiteralElementLike(bindingElement)) {
74583             switch (bindingElement.kind) {
74584                 case 281 /* PropertyAssignment */:
74585                     // `b` in `({ a: b } = ...)`
74586                     // `b` in `({ a: b = 1 } = ...)`
74587                     // `{b}` in `({ a: {b} } = ...)`
74588                     // `{b}` in `({ a: {b} = 1 } = ...)`
74589                     // `[b]` in `({ a: [b] } = ...)`
74590                     // `[b]` in `({ a: [b] = 1 } = ...)`
74591                     // `b.c` in `({ a: b.c } = ...)`
74592                     // `b.c` in `({ a: b.c = 1 } = ...)`
74593                     // `b[0]` in `({ a: b[0] } = ...)`
74594                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
74595                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
74596                 case 282 /* ShorthandPropertyAssignment */:
74597                     // `a` in `({ a } = ...)`
74598                     // `a` in `({ a = 1 } = ...)`
74599                     return bindingElement.name;
74600                 case 283 /* SpreadAssignment */:
74601                     // `a` in `({ ...a } = ...)`
74602                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74603             }
74604             // no target
74605             return undefined;
74606         }
74607         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74608             // `a` in `[a = 1] = ...`
74609             // `{a}` in `[{a} = 1] = ...`
74610             // `[a]` in `[[a] = 1] = ...`
74611             // `a.b` in `[a.b = 1] = ...`
74612             // `a[0]` in `[a[0] = 1] = ...`
74613             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
74614         }
74615         if (ts.isSpreadElement(bindingElement)) {
74616             // `a` in `[...a] = ...`
74617             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74618         }
74619         // `a` in `[a] = ...`
74620         // `{a}` in `[{a}] = ...`
74621         // `[a]` in `[[a]] = ...`
74622         // `a.b` in `[a.b] = ...`
74623         // `a[0]` in `[a[0]] = ...`
74624         return bindingElement;
74625     }
74626     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
74627     /**
74628      * Determines whether an BindingOrAssignmentElement is a rest element.
74629      */
74630     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
74631         switch (bindingElement.kind) {
74632             case 156 /* Parameter */:
74633             case 191 /* BindingElement */:
74634                 // `...` in `let [...a] = ...`
74635                 return bindingElement.dotDotDotToken;
74636             case 213 /* SpreadElement */:
74637             case 283 /* SpreadAssignment */:
74638                 // `...` in `[...a] = ...`
74639                 return bindingElement;
74640         }
74641         return undefined;
74642     }
74643     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
74644     /**
74645      * Gets the property name of a BindingOrAssignmentElement
74646      */
74647     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74648         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
74649         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
74650         return propertyName;
74651     }
74652     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
74653     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74654         switch (bindingElement.kind) {
74655             case 191 /* BindingElement */:
74656                 // `a` in `let { a: b } = ...`
74657                 // `[a]` in `let { [a]: b } = ...`
74658                 // `"a"` in `let { "a": b } = ...`
74659                 // `1` in `let { 1: b } = ...`
74660                 if (bindingElement.propertyName) {
74661                     var propertyName = bindingElement.propertyName;
74662                     if (ts.isPrivateIdentifier(propertyName)) {
74663                         return ts.Debug.failBadSyntaxKind(propertyName);
74664                     }
74665                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74666                         ? propertyName.expression
74667                         : propertyName;
74668                 }
74669                 break;
74670             case 281 /* PropertyAssignment */:
74671                 // `a` in `({ a: b } = ...)`
74672                 // `[a]` in `({ [a]: b } = ...)`
74673                 // `"a"` in `({ "a": b } = ...)`
74674                 // `1` in `({ 1: b } = ...)`
74675                 if (bindingElement.name) {
74676                     var propertyName = bindingElement.name;
74677                     if (ts.isPrivateIdentifier(propertyName)) {
74678                         return ts.Debug.failBadSyntaxKind(propertyName);
74679                     }
74680                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74681                         ? propertyName.expression
74682                         : propertyName;
74683                 }
74684                 break;
74685             case 283 /* SpreadAssignment */:
74686                 // `a` in `({ ...a } = ...)`
74687                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
74688                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
74689                 }
74690                 return bindingElement.name;
74691         }
74692         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
74693         if (target && ts.isPropertyName(target)) {
74694             return target;
74695         }
74696     }
74697     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
74698     function isStringOrNumericLiteral(node) {
74699         var kind = node.kind;
74700         return kind === 10 /* StringLiteral */
74701             || kind === 8 /* NumericLiteral */;
74702     }
74703     /**
74704      * Gets the elements of a BindingOrAssignmentPattern
74705      */
74706     function getElementsOfBindingOrAssignmentPattern(name) {
74707         switch (name.kind) {
74708             case 189 /* ObjectBindingPattern */:
74709             case 190 /* ArrayBindingPattern */:
74710             case 192 /* ArrayLiteralExpression */:
74711                 // `a` in `{a}`
74712                 // `a` in `[a]`
74713                 return name.elements;
74714             case 193 /* ObjectLiteralExpression */:
74715                 // `a` in `{a}`
74716                 return name.properties;
74717         }
74718     }
74719     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
74720     function convertToArrayAssignmentElement(element) {
74721         if (ts.isBindingElement(element)) {
74722             if (element.dotDotDotToken) {
74723                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74724                 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
74725             }
74726             var expression = convertToAssignmentElementTarget(element.name);
74727             return element.initializer
74728                 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
74729                 : expression;
74730         }
74731         ts.Debug.assertNode(element, ts.isExpression);
74732         return element;
74733     }
74734     ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
74735     function convertToObjectAssignmentElement(element) {
74736         if (ts.isBindingElement(element)) {
74737             if (element.dotDotDotToken) {
74738                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74739                 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
74740             }
74741             if (element.propertyName) {
74742                 var expression = convertToAssignmentElementTarget(element.name);
74743                 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
74744             }
74745             ts.Debug.assertNode(element.name, ts.isIdentifier);
74746             return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
74747         }
74748         ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
74749         return element;
74750     }
74751     ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
74752     function convertToAssignmentPattern(node) {
74753         switch (node.kind) {
74754             case 190 /* ArrayBindingPattern */:
74755             case 192 /* ArrayLiteralExpression */:
74756                 return convertToArrayAssignmentPattern(node);
74757             case 189 /* ObjectBindingPattern */:
74758             case 193 /* ObjectLiteralExpression */:
74759                 return convertToObjectAssignmentPattern(node);
74760         }
74761     }
74762     ts.convertToAssignmentPattern = convertToAssignmentPattern;
74763     function convertToObjectAssignmentPattern(node) {
74764         if (ts.isObjectBindingPattern(node)) {
74765             return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
74766         }
74767         ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
74768         return node;
74769     }
74770     ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
74771     function convertToArrayAssignmentPattern(node) {
74772         if (ts.isArrayBindingPattern(node)) {
74773             return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
74774         }
74775         ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
74776         return node;
74777     }
74778     ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
74779     function convertToAssignmentElementTarget(node) {
74780         if (ts.isBindingPattern(node)) {
74781             return convertToAssignmentPattern(node);
74782         }
74783         ts.Debug.assertNode(node, ts.isExpression);
74784         return node;
74785     }
74786     ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
74787 })(ts || (ts = {}));
74788 var ts;
74789 (function (ts) {
74790     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
74791     function visitNode(node, visitor, test, lift) {
74792         if (node === undefined || visitor === undefined) {
74793             return node;
74794         }
74795         ts.aggregateTransformFlags(node);
74796         var visited = visitor(node);
74797         if (visited === node) {
74798             return node;
74799         }
74800         var visitedNode;
74801         if (visited === undefined) {
74802             return undefined;
74803         }
74804         else if (ts.isArray(visited)) {
74805             visitedNode = (lift || extractSingleNode)(visited);
74806         }
74807         else {
74808             visitedNode = visited;
74809         }
74810         ts.Debug.assertNode(visitedNode, test);
74811         ts.aggregateTransformFlags(visitedNode);
74812         return visitedNode;
74813     }
74814     ts.visitNode = visitNode;
74815     /**
74816      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
74817      *
74818      * @param nodes The NodeArray to visit.
74819      * @param visitor The callback used to visit a Node.
74820      * @param test A node test to execute for each node.
74821      * @param start An optional value indicating the starting offset at which to start visiting.
74822      * @param count An optional value indicating the maximum number of nodes to visit.
74823      */
74824     function visitNodes(nodes, visitor, test, start, count) {
74825         if (nodes === undefined || visitor === undefined) {
74826             return nodes;
74827         }
74828         var updated;
74829         // Ensure start and count have valid values
74830         var length = nodes.length;
74831         if (start === undefined || start < 0) {
74832             start = 0;
74833         }
74834         if (count === undefined || count > length - start) {
74835             count = length - start;
74836         }
74837         if (start > 0 || count < length) {
74838             // If we are not visiting all of the original nodes, we must always create a new array.
74839             // Since this is a fragment of a node array, we do not copy over the previous location
74840             // and will only copy over `hasTrailingComma` if we are including the last element.
74841             updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
74842         }
74843         // Visit each original node.
74844         for (var i = 0; i < count; i++) {
74845             var node = nodes[i + start];
74846             ts.aggregateTransformFlags(node);
74847             var visited = node !== undefined ? visitor(node) : undefined;
74848             if (updated !== undefined || visited === undefined || visited !== node) {
74849                 if (updated === undefined) {
74850                     // Ensure we have a copy of `nodes`, up to the current index.
74851                     updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
74852                     ts.setTextRange(updated, nodes);
74853                 }
74854                 if (visited) {
74855                     if (ts.isArray(visited)) {
74856                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
74857                             var visitedNode = visited_1[_i];
74858                             ts.Debug.assertNode(visitedNode, test);
74859                             ts.aggregateTransformFlags(visitedNode);
74860                             updated.push(visitedNode);
74861                         }
74862                     }
74863                     else {
74864                         ts.Debug.assertNode(visited, test);
74865                         ts.aggregateTransformFlags(visited);
74866                         updated.push(visited);
74867                     }
74868                 }
74869             }
74870         }
74871         return updated || nodes;
74872     }
74873     ts.visitNodes = visitNodes;
74874     /**
74875      * Starts a new lexical environment and visits a statement list, ending the lexical environment
74876      * and merging hoisted declarations upon completion.
74877      */
74878     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
74879         context.startLexicalEnvironment();
74880         statements = visitNodes(statements, visitor, ts.isStatement, start);
74881         if (ensureUseStrict)
74882             statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
74883         return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
74884     }
74885     ts.visitLexicalEnvironment = visitLexicalEnvironment;
74886     function visitParameterList(nodes, visitor, context, nodesVisitor) {
74887         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74888         var updated;
74889         context.startLexicalEnvironment();
74890         if (nodes) {
74891             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
74892             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
74893             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
74894             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
74895             // that we might transform that introduces a temporary variable would fail as the temporary variable
74896             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
74897             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
74898             // when the emit target is greater than ES2015.
74899             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
74900                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
74901                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
74902             }
74903             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
74904         }
74905         context.suspendLexicalEnvironment();
74906         return updated;
74907     }
74908     ts.visitParameterList = visitParameterList;
74909     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
74910         var result;
74911         for (var i = 0; i < parameters.length; i++) {
74912             var parameter = parameters[i];
74913             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
74914             if (result || updated !== parameter) {
74915                 if (!result)
74916                     result = parameters.slice(0, i);
74917                 result[i] = updated;
74918             }
74919         }
74920         if (result) {
74921             return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters);
74922         }
74923         return parameters;
74924     }
74925     function addDefaultValueAssignmentIfNeeded(parameter, context) {
74926         // A rest parameter cannot have a binding pattern or an initializer,
74927         // so let's just ignore it.
74928         return parameter.dotDotDotToken ? parameter :
74929             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
74930                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
74931                     parameter;
74932     }
74933     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
74934         context.addInitializationStatement(ts.createVariableStatement(
74935         /*modifiers*/ undefined, ts.createVariableDeclarationList([
74936             ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ?
74937                 ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) :
74938                 ts.getGeneratedNameForNode(parameter)),
74939         ])));
74940         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
74941         /*initializer*/ undefined);
74942     }
74943     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
74944         context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
74945             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 */))
74946         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
74947         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
74948         /*initializer*/ undefined);
74949     }
74950     function visitFunctionBody(node, visitor, context) {
74951         context.resumeLexicalEnvironment();
74952         var updated = visitNode(node, visitor, ts.isConciseBody);
74953         var declarations = context.endLexicalEnvironment();
74954         if (ts.some(declarations)) {
74955             var block = ts.convertToFunctionBody(updated);
74956             var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
74957             return ts.updateBlock(block, statements);
74958         }
74959         return updated;
74960     }
74961     ts.visitFunctionBody = visitFunctionBody;
74962     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
74963         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74964         if (node === undefined) {
74965             return undefined;
74966         }
74967         var kind = node.kind;
74968         // No need to visit nodes with no children.
74969         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
74970             return node;
74971         }
74972         switch (kind) {
74973             // Names
74974             case 75 /* Identifier */:
74975                 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
74976             case 153 /* QualifiedName */:
74977                 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
74978             case 154 /* ComputedPropertyName */:
74979                 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
74980             // Signature elements
74981             case 155 /* TypeParameter */:
74982                 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
74983             case 156 /* Parameter */:
74984                 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));
74985             case 157 /* Decorator */:
74986                 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
74987             // Type elements
74988             case 158 /* PropertySignature */:
74989                 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));
74990             case 159 /* PropertyDeclaration */:
74991                 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), 
74992                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
74993                 visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74994             case 160 /* MethodSignature */:
74995                 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));
74996             case 161 /* MethodDeclaration */:
74997                 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));
74998             case 162 /* Constructor */:
74999                 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));
75000             case 163 /* GetAccessor */:
75001                 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));
75002             case 164 /* SetAccessor */:
75003                 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));
75004             case 165 /* CallSignature */:
75005                 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
75006             case 166 /* ConstructSignature */:
75007                 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
75008             case 167 /* IndexSignature */:
75009                 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));
75010             // Types
75011             case 168 /* TypePredicate */:
75012                 return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
75013             case 169 /* TypeReference */:
75014                 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
75015             case 170 /* FunctionType */:
75016                 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
75017             case 171 /* ConstructorType */:
75018                 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
75019             case 172 /* TypeQuery */:
75020                 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
75021             case 173 /* TypeLiteral */:
75022                 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
75023             case 174 /* ArrayType */:
75024                 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
75025             case 175 /* TupleType */:
75026                 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
75027             case 176 /* OptionalType */:
75028                 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
75029             case 177 /* RestType */:
75030                 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
75031             case 178 /* UnionType */:
75032                 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
75033             case 179 /* IntersectionType */:
75034                 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
75035             case 180 /* ConditionalType */:
75036                 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));
75037             case 181 /* InferType */:
75038                 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
75039             case 188 /* ImportType */:
75040                 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
75041             case 182 /* ParenthesizedType */:
75042                 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
75043             case 184 /* TypeOperator */:
75044                 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
75045             case 185 /* IndexedAccessType */:
75046                 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
75047             case 186 /* MappedType */:
75048                 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));
75049             case 187 /* LiteralType */:
75050                 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
75051             // Binding patterns
75052             case 189 /* ObjectBindingPattern */:
75053                 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
75054             case 190 /* ArrayBindingPattern */:
75055                 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
75056             case 191 /* BindingElement */:
75057                 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));
75058             // Expression
75059             case 192 /* ArrayLiteralExpression */:
75060                 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75061             case 193 /* ObjectLiteralExpression */:
75062                 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
75063             case 194 /* PropertyAccessExpression */:
75064                 if (node.flags & 32 /* OptionalChain */) {
75065                     return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
75066                 }
75067                 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
75068             case 195 /* ElementAccessExpression */:
75069                 if (node.flags & 32 /* OptionalChain */) {
75070                     return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
75071                 }
75072                 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
75073             case 196 /* CallExpression */:
75074                 if (node.flags & 32 /* OptionalChain */) {
75075                     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));
75076                 }
75077                 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
75078             case 197 /* NewExpression */:
75079                 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
75080             case 198 /* TaggedTemplateExpression */:
75081                 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
75082             case 199 /* TypeAssertionExpression */:
75083                 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
75084             case 200 /* ParenthesizedExpression */:
75085                 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
75086             case 201 /* FunctionExpression */:
75087                 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));
75088             case 202 /* ArrowFunction */:
75089                 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));
75090             case 203 /* DeleteExpression */:
75091                 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
75092             case 204 /* TypeOfExpression */:
75093                 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
75094             case 205 /* VoidExpression */:
75095                 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
75096             case 206 /* AwaitExpression */:
75097                 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
75098             case 207 /* PrefixUnaryExpression */:
75099                 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
75100             case 208 /* PostfixUnaryExpression */:
75101                 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
75102             case 209 /* BinaryExpression */:
75103                 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken));
75104             case 210 /* ConditionalExpression */:
75105                 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));
75106             case 211 /* TemplateExpression */:
75107                 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
75108             case 212 /* YieldExpression */:
75109                 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
75110             case 213 /* SpreadElement */:
75111                 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
75112             case 214 /* ClassExpression */:
75113                 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));
75114             case 216 /* ExpressionWithTypeArguments */:
75115                 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
75116             case 217 /* AsExpression */:
75117                 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
75118             case 218 /* NonNullExpression */:
75119                 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75120             case 219 /* MetaProperty */:
75121                 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
75122             // Misc
75123             case 221 /* TemplateSpan */:
75124                 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
75125             // Element
75126             case 223 /* Block */:
75127                 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75128             case 225 /* VariableStatement */:
75129                 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
75130             case 226 /* ExpressionStatement */:
75131                 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
75132             case 227 /* IfStatement */:
75133                 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));
75134             case 228 /* DoStatement */:
75135                 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
75136             case 229 /* WhileStatement */:
75137                 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75138             case 230 /* ForStatement */:
75139                 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));
75140             case 231 /* ForInStatement */:
75141                 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75142             case 232 /* ForOfStatement */:
75143                 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));
75144             case 233 /* ContinueStatement */:
75145                 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
75146             case 234 /* BreakStatement */:
75147                 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
75148             case 235 /* ReturnStatement */:
75149                 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
75150             case 236 /* WithStatement */:
75151                 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75152             case 237 /* SwitchStatement */:
75153                 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
75154             case 238 /* LabeledStatement */:
75155                 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75156             case 239 /* ThrowStatement */:
75157                 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
75158             case 240 /* TryStatement */:
75159                 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
75160             case 242 /* VariableDeclaration */:
75161                 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));
75162             case 243 /* VariableDeclarationList */:
75163                 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
75164             case 244 /* FunctionDeclaration */:
75165                 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));
75166             case 245 /* ClassDeclaration */:
75167                 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));
75168             case 246 /* InterfaceDeclaration */:
75169                 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));
75170             case 247 /* TypeAliasDeclaration */:
75171                 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));
75172             case 248 /* EnumDeclaration */:
75173                 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));
75174             case 249 /* ModuleDeclaration */:
75175                 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));
75176             case 250 /* ModuleBlock */:
75177                 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75178             case 251 /* CaseBlock */:
75179                 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
75180             case 252 /* NamespaceExportDeclaration */:
75181                 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
75182             case 253 /* ImportEqualsDeclaration */:
75183                 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));
75184             case 254 /* ImportDeclaration */:
75185                 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));
75186             case 255 /* ImportClause */:
75187                 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
75188             case 256 /* NamespaceImport */:
75189                 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
75190             case 262 /* NamespaceExport */:
75191                 return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
75192             case 257 /* NamedImports */:
75193                 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
75194             case 258 /* ImportSpecifier */:
75195                 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75196             case 259 /* ExportAssignment */:
75197                 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
75198             case 260 /* ExportDeclaration */:
75199                 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);
75200             case 261 /* NamedExports */:
75201                 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
75202             case 263 /* ExportSpecifier */:
75203                 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75204             // Module references
75205             case 265 /* ExternalModuleReference */:
75206                 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
75207             // JSX
75208             case 266 /* JsxElement */:
75209                 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
75210             case 267 /* JsxSelfClosingElement */:
75211                 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75212             case 268 /* JsxOpeningElement */:
75213                 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75214             case 269 /* JsxClosingElement */:
75215                 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
75216             case 270 /* JsxFragment */:
75217                 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
75218             case 273 /* JsxAttribute */:
75219                 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
75220             case 274 /* JsxAttributes */:
75221                 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
75222             case 275 /* JsxSpreadAttribute */:
75223                 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
75224             case 276 /* JsxExpression */:
75225                 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75226             // Clauses
75227             case 277 /* CaseClause */:
75228                 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
75229             case 278 /* DefaultClause */:
75230                 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75231             case 279 /* HeritageClause */:
75232                 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
75233             case 280 /* CatchClause */:
75234                 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
75235             // Property assignments
75236             case 281 /* PropertyAssignment */:
75237                 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75238             case 282 /* ShorthandPropertyAssignment */:
75239                 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
75240             case 283 /* SpreadAssignment */:
75241                 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
75242             // Enum
75243             case 284 /* EnumMember */:
75244                 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75245             // Top-level nodes
75246             case 290 /* SourceFile */:
75247                 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
75248             // Transformation nodes
75249             case 326 /* PartiallyEmittedExpression */:
75250                 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75251             case 327 /* CommaListExpression */:
75252                 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75253             default:
75254                 // No need to visit nodes with no children.
75255                 return node;
75256         }
75257     }
75258     ts.visitEachChild = visitEachChild;
75259     /**
75260      * Extracts the single node from a NodeArray.
75261      *
75262      * @param nodes The NodeArray.
75263      */
75264     function extractSingleNode(nodes) {
75265         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
75266         return ts.singleOrUndefined(nodes);
75267     }
75268 })(ts || (ts = {}));
75269 /* @internal */
75270 var ts;
75271 (function (ts) {
75272     function reduceNode(node, f, initial) {
75273         return node ? f(initial, node) : initial;
75274     }
75275     function reduceNodeArray(nodes, f, initial) {
75276         return nodes ? f(initial, nodes) : initial;
75277     }
75278     /**
75279      * Similar to `reduceLeft`, performs a reduction against each child of a node.
75280      * NOTE: Unlike `forEachChild`, this does *not* visit every node.
75281      *
75282      * @param node The node containing the children to reduce.
75283      * @param initial The initial value to supply to the reduction.
75284      * @param f The callback function
75285      */
75286     function reduceEachChild(node, initial, cbNode, cbNodeArray) {
75287         if (node === undefined) {
75288             return initial;
75289         }
75290         var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
75291         var cbNodes = cbNodeArray || cbNode;
75292         var kind = node.kind;
75293         // No need to visit nodes with no children.
75294         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
75295             return initial;
75296         }
75297         // We do not yet support types.
75298         if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
75299             return initial;
75300         }
75301         var result = initial;
75302         switch (node.kind) {
75303             // Leaf nodes
75304             case 222 /* SemicolonClassElement */:
75305             case 224 /* EmptyStatement */:
75306             case 215 /* OmittedExpression */:
75307             case 241 /* DebuggerStatement */:
75308             case 325 /* NotEmittedStatement */:
75309                 // No need to visit nodes with no children.
75310                 break;
75311             // Names
75312             case 153 /* QualifiedName */:
75313                 result = reduceNode(node.left, cbNode, result);
75314                 result = reduceNode(node.right, cbNode, result);
75315                 break;
75316             case 154 /* ComputedPropertyName */:
75317                 result = reduceNode(node.expression, cbNode, result);
75318                 break;
75319             // Signature elements
75320             case 156 /* Parameter */:
75321                 result = reduceNodes(node.decorators, cbNodes, result);
75322                 result = reduceNodes(node.modifiers, cbNodes, result);
75323                 result = reduceNode(node.name, cbNode, result);
75324                 result = reduceNode(node.type, cbNode, result);
75325                 result = reduceNode(node.initializer, cbNode, result);
75326                 break;
75327             case 157 /* Decorator */:
75328                 result = reduceNode(node.expression, cbNode, result);
75329                 break;
75330             // Type member
75331             case 158 /* PropertySignature */:
75332                 result = reduceNodes(node.modifiers, cbNodes, result);
75333                 result = reduceNode(node.name, cbNode, result);
75334                 result = reduceNode(node.questionToken, cbNode, result);
75335                 result = reduceNode(node.type, cbNode, result);
75336                 result = reduceNode(node.initializer, cbNode, result);
75337                 break;
75338             case 159 /* PropertyDeclaration */:
75339                 result = reduceNodes(node.decorators, cbNodes, result);
75340                 result = reduceNodes(node.modifiers, cbNodes, result);
75341                 result = reduceNode(node.name, cbNode, result);
75342                 result = reduceNode(node.type, cbNode, result);
75343                 result = reduceNode(node.initializer, cbNode, result);
75344                 break;
75345             case 161 /* MethodDeclaration */:
75346                 result = reduceNodes(node.decorators, cbNodes, result);
75347                 result = reduceNodes(node.modifiers, cbNodes, result);
75348                 result = reduceNode(node.name, cbNode, result);
75349                 result = reduceNodes(node.typeParameters, cbNodes, result);
75350                 result = reduceNodes(node.parameters, cbNodes, result);
75351                 result = reduceNode(node.type, cbNode, result);
75352                 result = reduceNode(node.body, cbNode, result);
75353                 break;
75354             case 162 /* Constructor */:
75355                 result = reduceNodes(node.modifiers, cbNodes, result);
75356                 result = reduceNodes(node.parameters, cbNodes, result);
75357                 result = reduceNode(node.body, cbNode, result);
75358                 break;
75359             case 163 /* GetAccessor */:
75360                 result = reduceNodes(node.decorators, cbNodes, result);
75361                 result = reduceNodes(node.modifiers, cbNodes, result);
75362                 result = reduceNode(node.name, cbNode, result);
75363                 result = reduceNodes(node.parameters, cbNodes, result);
75364                 result = reduceNode(node.type, cbNode, result);
75365                 result = reduceNode(node.body, cbNode, result);
75366                 break;
75367             case 164 /* SetAccessor */:
75368                 result = reduceNodes(node.decorators, cbNodes, result);
75369                 result = reduceNodes(node.modifiers, cbNodes, result);
75370                 result = reduceNode(node.name, cbNode, result);
75371                 result = reduceNodes(node.parameters, cbNodes, result);
75372                 result = reduceNode(node.body, cbNode, result);
75373                 break;
75374             // Binding patterns
75375             case 189 /* ObjectBindingPattern */:
75376             case 190 /* ArrayBindingPattern */:
75377                 result = reduceNodes(node.elements, cbNodes, result);
75378                 break;
75379             case 191 /* BindingElement */:
75380                 result = reduceNode(node.propertyName, cbNode, result);
75381                 result = reduceNode(node.name, cbNode, result);
75382                 result = reduceNode(node.initializer, cbNode, result);
75383                 break;
75384             // Expression
75385             case 192 /* ArrayLiteralExpression */:
75386                 result = reduceNodes(node.elements, cbNodes, result);
75387                 break;
75388             case 193 /* ObjectLiteralExpression */:
75389                 result = reduceNodes(node.properties, cbNodes, result);
75390                 break;
75391             case 194 /* PropertyAccessExpression */:
75392                 result = reduceNode(node.expression, cbNode, result);
75393                 result = reduceNode(node.name, cbNode, result);
75394                 break;
75395             case 195 /* ElementAccessExpression */:
75396                 result = reduceNode(node.expression, cbNode, result);
75397                 result = reduceNode(node.argumentExpression, cbNode, result);
75398                 break;
75399             case 196 /* CallExpression */:
75400                 result = reduceNode(node.expression, cbNode, result);
75401                 result = reduceNodes(node.typeArguments, cbNodes, result);
75402                 result = reduceNodes(node.arguments, cbNodes, result);
75403                 break;
75404             case 197 /* NewExpression */:
75405                 result = reduceNode(node.expression, cbNode, result);
75406                 result = reduceNodes(node.typeArguments, cbNodes, result);
75407                 result = reduceNodes(node.arguments, cbNodes, result);
75408                 break;
75409             case 198 /* TaggedTemplateExpression */:
75410                 result = reduceNode(node.tag, cbNode, result);
75411                 result = reduceNodes(node.typeArguments, cbNodes, result);
75412                 result = reduceNode(node.template, cbNode, result);
75413                 break;
75414             case 199 /* TypeAssertionExpression */:
75415                 result = reduceNode(node.type, cbNode, result);
75416                 result = reduceNode(node.expression, cbNode, result);
75417                 break;
75418             case 201 /* FunctionExpression */:
75419                 result = reduceNodes(node.modifiers, cbNodes, result);
75420                 result = reduceNode(node.name, cbNode, result);
75421                 result = reduceNodes(node.typeParameters, cbNodes, result);
75422                 result = reduceNodes(node.parameters, cbNodes, result);
75423                 result = reduceNode(node.type, cbNode, result);
75424                 result = reduceNode(node.body, cbNode, result);
75425                 break;
75426             case 202 /* ArrowFunction */:
75427                 result = reduceNodes(node.modifiers, cbNodes, result);
75428                 result = reduceNodes(node.typeParameters, cbNodes, result);
75429                 result = reduceNodes(node.parameters, cbNodes, result);
75430                 result = reduceNode(node.type, cbNode, result);
75431                 result = reduceNode(node.body, cbNode, result);
75432                 break;
75433             case 200 /* ParenthesizedExpression */:
75434             case 203 /* DeleteExpression */:
75435             case 204 /* TypeOfExpression */:
75436             case 205 /* VoidExpression */:
75437             case 206 /* AwaitExpression */:
75438             case 212 /* YieldExpression */:
75439             case 213 /* SpreadElement */:
75440             case 218 /* NonNullExpression */:
75441                 result = reduceNode(node.expression, cbNode, result);
75442                 break;
75443             case 207 /* PrefixUnaryExpression */:
75444             case 208 /* PostfixUnaryExpression */:
75445                 result = reduceNode(node.operand, cbNode, result);
75446                 break;
75447             case 209 /* BinaryExpression */:
75448                 result = reduceNode(node.left, cbNode, result);
75449                 result = reduceNode(node.right, cbNode, result);
75450                 break;
75451             case 210 /* ConditionalExpression */:
75452                 result = reduceNode(node.condition, cbNode, result);
75453                 result = reduceNode(node.whenTrue, cbNode, result);
75454                 result = reduceNode(node.whenFalse, cbNode, result);
75455                 break;
75456             case 211 /* TemplateExpression */:
75457                 result = reduceNode(node.head, cbNode, result);
75458                 result = reduceNodes(node.templateSpans, cbNodes, result);
75459                 break;
75460             case 214 /* ClassExpression */:
75461                 result = reduceNodes(node.modifiers, cbNodes, result);
75462                 result = reduceNode(node.name, cbNode, result);
75463                 result = reduceNodes(node.typeParameters, cbNodes, result);
75464                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75465                 result = reduceNodes(node.members, cbNodes, result);
75466                 break;
75467             case 216 /* ExpressionWithTypeArguments */:
75468                 result = reduceNode(node.expression, cbNode, result);
75469                 result = reduceNodes(node.typeArguments, cbNodes, result);
75470                 break;
75471             case 217 /* AsExpression */:
75472                 result = reduceNode(node.expression, cbNode, result);
75473                 result = reduceNode(node.type, cbNode, result);
75474                 break;
75475             // Misc
75476             case 221 /* TemplateSpan */:
75477                 result = reduceNode(node.expression, cbNode, result);
75478                 result = reduceNode(node.literal, cbNode, result);
75479                 break;
75480             // Element
75481             case 223 /* Block */:
75482                 result = reduceNodes(node.statements, cbNodes, result);
75483                 break;
75484             case 225 /* VariableStatement */:
75485                 result = reduceNodes(node.modifiers, cbNodes, result);
75486                 result = reduceNode(node.declarationList, cbNode, result);
75487                 break;
75488             case 226 /* ExpressionStatement */:
75489                 result = reduceNode(node.expression, cbNode, result);
75490                 break;
75491             case 227 /* IfStatement */:
75492                 result = reduceNode(node.expression, cbNode, result);
75493                 result = reduceNode(node.thenStatement, cbNode, result);
75494                 result = reduceNode(node.elseStatement, cbNode, result);
75495                 break;
75496             case 228 /* DoStatement */:
75497                 result = reduceNode(node.statement, cbNode, result);
75498                 result = reduceNode(node.expression, cbNode, result);
75499                 break;
75500             case 229 /* WhileStatement */:
75501             case 236 /* WithStatement */:
75502                 result = reduceNode(node.expression, cbNode, result);
75503                 result = reduceNode(node.statement, cbNode, result);
75504                 break;
75505             case 230 /* ForStatement */:
75506                 result = reduceNode(node.initializer, cbNode, result);
75507                 result = reduceNode(node.condition, cbNode, result);
75508                 result = reduceNode(node.incrementor, cbNode, result);
75509                 result = reduceNode(node.statement, cbNode, result);
75510                 break;
75511             case 231 /* ForInStatement */:
75512             case 232 /* ForOfStatement */:
75513                 result = reduceNode(node.initializer, cbNode, result);
75514                 result = reduceNode(node.expression, cbNode, result);
75515                 result = reduceNode(node.statement, cbNode, result);
75516                 break;
75517             case 235 /* ReturnStatement */:
75518             case 239 /* ThrowStatement */:
75519                 result = reduceNode(node.expression, cbNode, result);
75520                 break;
75521             case 237 /* SwitchStatement */:
75522                 result = reduceNode(node.expression, cbNode, result);
75523                 result = reduceNode(node.caseBlock, cbNode, result);
75524                 break;
75525             case 238 /* LabeledStatement */:
75526                 result = reduceNode(node.label, cbNode, result);
75527                 result = reduceNode(node.statement, cbNode, result);
75528                 break;
75529             case 240 /* TryStatement */:
75530                 result = reduceNode(node.tryBlock, cbNode, result);
75531                 result = reduceNode(node.catchClause, cbNode, result);
75532                 result = reduceNode(node.finallyBlock, cbNode, result);
75533                 break;
75534             case 242 /* VariableDeclaration */:
75535                 result = reduceNode(node.name, cbNode, result);
75536                 result = reduceNode(node.type, cbNode, result);
75537                 result = reduceNode(node.initializer, cbNode, result);
75538                 break;
75539             case 243 /* VariableDeclarationList */:
75540                 result = reduceNodes(node.declarations, cbNodes, result);
75541                 break;
75542             case 244 /* FunctionDeclaration */:
75543                 result = reduceNodes(node.decorators, cbNodes, result);
75544                 result = reduceNodes(node.modifiers, cbNodes, result);
75545                 result = reduceNode(node.name, cbNode, result);
75546                 result = reduceNodes(node.typeParameters, cbNodes, result);
75547                 result = reduceNodes(node.parameters, cbNodes, result);
75548                 result = reduceNode(node.type, cbNode, result);
75549                 result = reduceNode(node.body, cbNode, result);
75550                 break;
75551             case 245 /* ClassDeclaration */:
75552                 result = reduceNodes(node.decorators, cbNodes, result);
75553                 result = reduceNodes(node.modifiers, cbNodes, result);
75554                 result = reduceNode(node.name, cbNode, result);
75555                 result = reduceNodes(node.typeParameters, cbNodes, result);
75556                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75557                 result = reduceNodes(node.members, cbNodes, result);
75558                 break;
75559             case 248 /* EnumDeclaration */:
75560                 result = reduceNodes(node.decorators, cbNodes, result);
75561                 result = reduceNodes(node.modifiers, cbNodes, result);
75562                 result = reduceNode(node.name, cbNode, result);
75563                 result = reduceNodes(node.members, cbNodes, result);
75564                 break;
75565             case 249 /* ModuleDeclaration */:
75566                 result = reduceNodes(node.decorators, cbNodes, result);
75567                 result = reduceNodes(node.modifiers, cbNodes, result);
75568                 result = reduceNode(node.name, cbNode, result);
75569                 result = reduceNode(node.body, cbNode, result);
75570                 break;
75571             case 250 /* ModuleBlock */:
75572                 result = reduceNodes(node.statements, cbNodes, result);
75573                 break;
75574             case 251 /* CaseBlock */:
75575                 result = reduceNodes(node.clauses, cbNodes, result);
75576                 break;
75577             case 253 /* ImportEqualsDeclaration */:
75578                 result = reduceNodes(node.decorators, cbNodes, result);
75579                 result = reduceNodes(node.modifiers, cbNodes, result);
75580                 result = reduceNode(node.name, cbNode, result);
75581                 result = reduceNode(node.moduleReference, cbNode, result);
75582                 break;
75583             case 254 /* ImportDeclaration */:
75584                 result = reduceNodes(node.decorators, cbNodes, result);
75585                 result = reduceNodes(node.modifiers, cbNodes, result);
75586                 result = reduceNode(node.importClause, cbNode, result);
75587                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75588                 break;
75589             case 255 /* ImportClause */:
75590                 result = reduceNode(node.name, cbNode, result);
75591                 result = reduceNode(node.namedBindings, cbNode, result);
75592                 break;
75593             case 256 /* NamespaceImport */:
75594                 result = reduceNode(node.name, cbNode, result);
75595                 break;
75596             case 262 /* NamespaceExport */:
75597                 result = reduceNode(node.name, cbNode, result);
75598                 break;
75599             case 257 /* NamedImports */:
75600             case 261 /* NamedExports */:
75601                 result = reduceNodes(node.elements, cbNodes, result);
75602                 break;
75603             case 258 /* ImportSpecifier */:
75604             case 263 /* ExportSpecifier */:
75605                 result = reduceNode(node.propertyName, cbNode, result);
75606                 result = reduceNode(node.name, cbNode, result);
75607                 break;
75608             case 259 /* ExportAssignment */:
75609                 result = ts.reduceLeft(node.decorators, cbNode, result);
75610                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75611                 result = reduceNode(node.expression, cbNode, result);
75612                 break;
75613             case 260 /* ExportDeclaration */:
75614                 result = ts.reduceLeft(node.decorators, cbNode, result);
75615                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75616                 result = reduceNode(node.exportClause, cbNode, result);
75617                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75618                 break;
75619             // Module references
75620             case 265 /* ExternalModuleReference */:
75621                 result = reduceNode(node.expression, cbNode, result);
75622                 break;
75623             // JSX
75624             case 266 /* JsxElement */:
75625                 result = reduceNode(node.openingElement, cbNode, result);
75626                 result = ts.reduceLeft(node.children, cbNode, result);
75627                 result = reduceNode(node.closingElement, cbNode, result);
75628                 break;
75629             case 270 /* JsxFragment */:
75630                 result = reduceNode(node.openingFragment, cbNode, result);
75631                 result = ts.reduceLeft(node.children, cbNode, result);
75632                 result = reduceNode(node.closingFragment, cbNode, result);
75633                 break;
75634             case 267 /* JsxSelfClosingElement */:
75635             case 268 /* JsxOpeningElement */:
75636                 result = reduceNode(node.tagName, cbNode, result);
75637                 result = reduceNodes(node.typeArguments, cbNode, result);
75638                 result = reduceNode(node.attributes, cbNode, result);
75639                 break;
75640             case 274 /* JsxAttributes */:
75641                 result = reduceNodes(node.properties, cbNodes, result);
75642                 break;
75643             case 269 /* JsxClosingElement */:
75644                 result = reduceNode(node.tagName, cbNode, result);
75645                 break;
75646             case 273 /* JsxAttribute */:
75647                 result = reduceNode(node.name, cbNode, result);
75648                 result = reduceNode(node.initializer, cbNode, result);
75649                 break;
75650             case 275 /* JsxSpreadAttribute */:
75651                 result = reduceNode(node.expression, cbNode, result);
75652                 break;
75653             case 276 /* JsxExpression */:
75654                 result = reduceNode(node.expression, cbNode, result);
75655                 break;
75656             // Clauses
75657             case 277 /* CaseClause */:
75658                 result = reduceNode(node.expression, cbNode, result);
75659             // falls through
75660             case 278 /* DefaultClause */:
75661                 result = reduceNodes(node.statements, cbNodes, result);
75662                 break;
75663             case 279 /* HeritageClause */:
75664                 result = reduceNodes(node.types, cbNodes, result);
75665                 break;
75666             case 280 /* CatchClause */:
75667                 result = reduceNode(node.variableDeclaration, cbNode, result);
75668                 result = reduceNode(node.block, cbNode, result);
75669                 break;
75670             // Property assignments
75671             case 281 /* PropertyAssignment */:
75672                 result = reduceNode(node.name, cbNode, result);
75673                 result = reduceNode(node.initializer, cbNode, result);
75674                 break;
75675             case 282 /* ShorthandPropertyAssignment */:
75676                 result = reduceNode(node.name, cbNode, result);
75677                 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
75678                 break;
75679             case 283 /* SpreadAssignment */:
75680                 result = reduceNode(node.expression, cbNode, result);
75681                 break;
75682             // Enum
75683             case 284 /* EnumMember */:
75684                 result = reduceNode(node.name, cbNode, result);
75685                 result = reduceNode(node.initializer, cbNode, result);
75686                 break;
75687             // Top-level nodes
75688             case 290 /* SourceFile */:
75689                 result = reduceNodes(node.statements, cbNodes, result);
75690                 break;
75691             // Transformation nodes
75692             case 326 /* PartiallyEmittedExpression */:
75693                 result = reduceNode(node.expression, cbNode, result);
75694                 break;
75695             case 327 /* CommaListExpression */:
75696                 result = reduceNodes(node.elements, cbNodes, result);
75697                 break;
75698             default:
75699                 break;
75700         }
75701         return result;
75702     }
75703     ts.reduceEachChild = reduceEachChild;
75704     function findSpanEnd(array, test, start) {
75705         var i = start;
75706         while (i < array.length && test(array[i])) {
75707             i++;
75708         }
75709         return i;
75710     }
75711     function mergeLexicalEnvironment(statements, declarations) {
75712         if (!ts.some(declarations)) {
75713             return statements;
75714         }
75715         // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
75716         //
75717         // Given:
75718         //
75719         // | Left                               | Right                               |
75720         // |------------------------------------|-------------------------------------|
75721         // | [standard prologues (left)]        | [standard prologues (right)]        |
75722         // | [hoisted functions (left)]         | [hoisted functions (right)]         |
75723         // | [hoisted variables (left)]         | [hoisted variables (right)]         |
75724         // | [lexical init statements (left)]   | [lexical init statements (right)]   |
75725         // | [other statements (left)]          |                                     |
75726         //
75727         // The resulting statement list will be:
75728         //
75729         // | Result                              |
75730         // |-------------------------------------|
75731         // | [standard prologues (right)]        |
75732         // | [standard prologues (left)]         |
75733         // | [hoisted functions (right)]         |
75734         // | [hoisted functions (left)]          |
75735         // | [hoisted variables (right)]         |
75736         // | [hoisted variables (left)]          |
75737         // | [lexical init statements (right)]   |
75738         // | [lexical init statements (left)]    |
75739         // | [other statements (left)]           |
75740         //
75741         // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
75742         // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
75743         // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
75744         var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
75745         var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
75746         var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
75747         // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
75748         var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
75749         var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
75750         var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
75751         var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
75752         ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
75753         // splice prologues from the right into the left. We do this in reverse order
75754         // so that we don't need to recompute the index on the left when we insert items.
75755         var left = ts.isNodeArray(statements) ? statements.slice() : statements;
75756         // splice other custom prologues from right into left
75757         if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
75758             left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
75759         }
75760         // splice hoisted variables from right into left
75761         if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
75762             left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
75763         }
75764         // splice hoisted functions from right into left
75765         if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
75766             left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
75767         }
75768         // splice standard prologues from right into left (that are not already in left)
75769         if (rightStandardPrologueEnd > 0) {
75770             if (leftStandardPrologueEnd === 0) {
75771                 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
75772             }
75773             else {
75774                 var leftPrologues = ts.createMap();
75775                 for (var i = 0; i < leftStandardPrologueEnd; i++) {
75776                     var leftPrologue = statements[i];
75777                     leftPrologues.set(leftPrologue.expression.text, true);
75778                 }
75779                 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
75780                     var rightPrologue = declarations[i];
75781                     if (!leftPrologues.has(rightPrologue.expression.text)) {
75782                         left.unshift(rightPrologue);
75783                     }
75784                 }
75785             }
75786         }
75787         if (ts.isNodeArray(statements)) {
75788             return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements);
75789         }
75790         return statements;
75791     }
75792     ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
75793     /**
75794      * Lifts a NodeArray containing only Statement nodes to a block.
75795      *
75796      * @param nodes The NodeArray.
75797      */
75798     function liftToBlock(nodes) {
75799         ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
75800         return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
75801     }
75802     ts.liftToBlock = liftToBlock;
75803     /**
75804      * Aggregates the TransformFlags for a Node and its subtree.
75805      */
75806     function aggregateTransformFlags(node) {
75807         aggregateTransformFlagsForNode(node);
75808         return node;
75809     }
75810     ts.aggregateTransformFlags = aggregateTransformFlags;
75811     /**
75812      * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
75813      * computed first, then the transform flags for the current node are computed from the subtree
75814      * flags and the state of the current node. Finally, the transform flags of the node are
75815      * returned, excluding any flags that should not be included in its parent node's subtree
75816      * flags.
75817      */
75818     function aggregateTransformFlagsForNode(node) {
75819         if (node === undefined) {
75820             return 0 /* None */;
75821         }
75822         if (node.transformFlags & 536870912 /* HasComputedFlags */) {
75823             return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
75824         }
75825         var subtreeFlags = aggregateTransformFlagsForSubtree(node);
75826         return ts.computeTransformFlagsForNode(node, subtreeFlags);
75827     }
75828     function aggregateTransformFlagsForNodeArray(nodes) {
75829         if (nodes === undefined) {
75830             return 0 /* None */;
75831         }
75832         var subtreeFlags = 0 /* None */;
75833         var nodeArrayFlags = 0 /* None */;
75834         for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
75835             var node = nodes_3[_i];
75836             subtreeFlags |= aggregateTransformFlagsForNode(node);
75837             nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
75838         }
75839         nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
75840         return subtreeFlags;
75841     }
75842     /**
75843      * Aggregates the transform flags for the subtree of a node.
75844      */
75845     function aggregateTransformFlagsForSubtree(node) {
75846         // We do not transform ambient declarations or types, so there is no need to
75847         // recursively aggregate transform flags.
75848         if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
75849             return 0 /* None */;
75850         }
75851         // Aggregate the transform flags of each child.
75852         return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
75853     }
75854     /**
75855      * Aggregates the TransformFlags of a child node with the TransformFlags of its
75856      * siblings.
75857      */
75858     function aggregateTransformFlagsForChildNode(transformFlags, node) {
75859         return transformFlags | aggregateTransformFlagsForNode(node);
75860     }
75861     function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
75862         return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
75863     }
75864 })(ts || (ts = {}));
75865 /* @internal */
75866 var ts;
75867 (function (ts) {
75868     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
75869         var _a = generatorOptions.extendedDiagnostics
75870             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
75871             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
75872         // Current source map file and its index in the sources list
75873         var rawSources = [];
75874         var sources = [];
75875         var sourceToSourceIndexMap = ts.createMap();
75876         var sourcesContent;
75877         var names = [];
75878         var nameToNameIndexMap;
75879         var mappings = "";
75880         // Last recorded and encoded mappings
75881         var lastGeneratedLine = 0;
75882         var lastGeneratedCharacter = 0;
75883         var lastSourceIndex = 0;
75884         var lastSourceLine = 0;
75885         var lastSourceCharacter = 0;
75886         var lastNameIndex = 0;
75887         var hasLast = false;
75888         var pendingGeneratedLine = 0;
75889         var pendingGeneratedCharacter = 0;
75890         var pendingSourceIndex = 0;
75891         var pendingSourceLine = 0;
75892         var pendingSourceCharacter = 0;
75893         var pendingNameIndex = 0;
75894         var hasPending = false;
75895         var hasPendingSource = false;
75896         var hasPendingName = false;
75897         return {
75898             getSources: function () { return rawSources; },
75899             addSource: addSource,
75900             setSourceContent: setSourceContent,
75901             addName: addName,
75902             addMapping: addMapping,
75903             appendSourceMap: appendSourceMap,
75904             toJSON: toJSON,
75905             toString: function () { return JSON.stringify(toJSON()); }
75906         };
75907         function addSource(fileName) {
75908             enter();
75909             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
75910             /*isAbsolutePathAnUrl*/ true);
75911             var sourceIndex = sourceToSourceIndexMap.get(source);
75912             if (sourceIndex === undefined) {
75913                 sourceIndex = sources.length;
75914                 sources.push(source);
75915                 rawSources.push(fileName);
75916                 sourceToSourceIndexMap.set(source, sourceIndex);
75917             }
75918             exit();
75919             return sourceIndex;
75920         }
75921         /* eslint-disable boolean-trivia, no-null/no-null */
75922         function setSourceContent(sourceIndex, content) {
75923             enter();
75924             if (content !== null) {
75925                 if (!sourcesContent)
75926                     sourcesContent = [];
75927                 while (sourcesContent.length < sourceIndex) {
75928                     sourcesContent.push(null);
75929                 }
75930                 sourcesContent[sourceIndex] = content;
75931             }
75932             exit();
75933         }
75934         /* eslint-enable boolean-trivia, no-null/no-null */
75935         function addName(name) {
75936             enter();
75937             if (!nameToNameIndexMap)
75938                 nameToNameIndexMap = ts.createMap();
75939             var nameIndex = nameToNameIndexMap.get(name);
75940             if (nameIndex === undefined) {
75941                 nameIndex = names.length;
75942                 names.push(name);
75943                 nameToNameIndexMap.set(name, nameIndex);
75944             }
75945             exit();
75946             return nameIndex;
75947         }
75948         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
75949             return !hasPending
75950                 || pendingGeneratedLine !== generatedLine
75951                 || pendingGeneratedCharacter !== generatedCharacter;
75952         }
75953         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
75954             return sourceIndex !== undefined
75955                 && sourceLine !== undefined
75956                 && sourceCharacter !== undefined
75957                 && pendingSourceIndex === sourceIndex
75958                 && (pendingSourceLine > sourceLine
75959                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
75960         }
75961         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
75962             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75963             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75964             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
75965             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
75966             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
75967             enter();
75968             // If this location wasn't recorded or the location in source is going backwards, record the mapping
75969             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
75970                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
75971                 commitPendingMapping();
75972                 pendingGeneratedLine = generatedLine;
75973                 pendingGeneratedCharacter = generatedCharacter;
75974                 hasPendingSource = false;
75975                 hasPendingName = false;
75976                 hasPending = true;
75977             }
75978             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
75979                 pendingSourceIndex = sourceIndex;
75980                 pendingSourceLine = sourceLine;
75981                 pendingSourceCharacter = sourceCharacter;
75982                 hasPendingSource = true;
75983                 if (nameIndex !== undefined) {
75984                     pendingNameIndex = nameIndex;
75985                     hasPendingName = true;
75986                 }
75987             }
75988             exit();
75989         }
75990         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
75991             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75992             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75993             enter();
75994             // First, decode the old component sourcemap
75995             var sourceIndexToNewSourceIndexMap = [];
75996             var nameIndexToNewNameIndexMap;
75997             var mappingIterator = decodeMappings(map.mappings);
75998             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
75999                 var raw = iterResult.value;
76000                 if (end && (raw.generatedLine > end.line ||
76001                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
76002                     break;
76003                 }
76004                 if (start && (raw.generatedLine < start.line ||
76005                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
76006                     continue;
76007                 }
76008                 // Then reencode all the updated mappings into the overall map
76009                 var newSourceIndex = void 0;
76010                 var newSourceLine = void 0;
76011                 var newSourceCharacter = void 0;
76012                 var newNameIndex = void 0;
76013                 if (raw.sourceIndex !== undefined) {
76014                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
76015                     if (newSourceIndex === undefined) {
76016                         // Apply offsets to each position and fixup source entries
76017                         var rawPath = map.sources[raw.sourceIndex];
76018                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
76019                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
76020                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
76021                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
76022                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
76023                         }
76024                     }
76025                     newSourceLine = raw.sourceLine;
76026                     newSourceCharacter = raw.sourceCharacter;
76027                     if (map.names && raw.nameIndex !== undefined) {
76028                         if (!nameIndexToNewNameIndexMap)
76029                             nameIndexToNewNameIndexMap = [];
76030                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
76031                         if (newNameIndex === undefined) {
76032                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
76033                         }
76034                     }
76035                 }
76036                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
76037                 var newGeneratedLine = rawGeneratedLine + generatedLine;
76038                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
76039                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
76040                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
76041             }
76042             exit();
76043         }
76044         function shouldCommitMapping() {
76045             return !hasLast
76046                 || lastGeneratedLine !== pendingGeneratedLine
76047                 || lastGeneratedCharacter !== pendingGeneratedCharacter
76048                 || lastSourceIndex !== pendingSourceIndex
76049                 || lastSourceLine !== pendingSourceLine
76050                 || lastSourceCharacter !== pendingSourceCharacter
76051                 || lastNameIndex !== pendingNameIndex;
76052         }
76053         function commitPendingMapping() {
76054             if (!hasPending || !shouldCommitMapping()) {
76055                 return;
76056             }
76057             enter();
76058             // Line/Comma delimiters
76059             if (lastGeneratedLine < pendingGeneratedLine) {
76060                 // Emit line delimiters
76061                 do {
76062                     mappings += ";";
76063                     lastGeneratedLine++;
76064                     lastGeneratedCharacter = 0;
76065                 } while (lastGeneratedLine < pendingGeneratedLine);
76066             }
76067             else {
76068                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
76069                 // Emit comma to separate the entry
76070                 if (hasLast) {
76071                     mappings += ",";
76072                 }
76073             }
76074             // 1. Relative generated character
76075             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
76076             lastGeneratedCharacter = pendingGeneratedCharacter;
76077             if (hasPendingSource) {
76078                 // 2. Relative sourceIndex
76079                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
76080                 lastSourceIndex = pendingSourceIndex;
76081                 // 3. Relative source line
76082                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
76083                 lastSourceLine = pendingSourceLine;
76084                 // 4. Relative source character
76085                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
76086                 lastSourceCharacter = pendingSourceCharacter;
76087                 if (hasPendingName) {
76088                     // 5. Relative nameIndex
76089                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
76090                     lastNameIndex = pendingNameIndex;
76091                 }
76092             }
76093             hasLast = true;
76094             exit();
76095         }
76096         function toJSON() {
76097             commitPendingMapping();
76098             return {
76099                 version: 3,
76100                 file: file,
76101                 sourceRoot: sourceRoot,
76102                 sources: sources,
76103                 names: names,
76104                 mappings: mappings,
76105                 sourcesContent: sourcesContent,
76106             };
76107         }
76108     }
76109     ts.createSourceMapGenerator = createSourceMapGenerator;
76110     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
76111     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
76112     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
76113     function getLineInfo(text, lineStarts) {
76114         return {
76115             getLineCount: function () { return lineStarts.length; },
76116             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
76117         };
76118     }
76119     ts.getLineInfo = getLineInfo;
76120     /**
76121      * Tries to find the sourceMappingURL comment at the end of a file.
76122      */
76123     function tryGetSourceMappingURL(lineInfo) {
76124         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
76125             var line = lineInfo.getLineText(index);
76126             var comment = sourceMapCommentRegExp.exec(line);
76127             if (comment) {
76128                 return comment[1];
76129             }
76130             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
76131             else if (!line.match(whitespaceOrMapCommentRegExp)) {
76132                 break;
76133             }
76134         }
76135     }
76136     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
76137     /* eslint-disable no-null/no-null */
76138     function isStringOrNull(x) {
76139         return typeof x === "string" || x === null;
76140     }
76141     function isRawSourceMap(x) {
76142         return x !== null
76143             && typeof x === "object"
76144             && x.version === 3
76145             && typeof x.file === "string"
76146             && typeof x.mappings === "string"
76147             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
76148             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
76149             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
76150             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
76151     }
76152     ts.isRawSourceMap = isRawSourceMap;
76153     /* eslint-enable no-null/no-null */
76154     function tryParseRawSourceMap(text) {
76155         try {
76156             var parsed = JSON.parse(text);
76157             if (isRawSourceMap(parsed)) {
76158                 return parsed;
76159             }
76160         }
76161         catch (_a) {
76162             // empty
76163         }
76164         return undefined;
76165     }
76166     ts.tryParseRawSourceMap = tryParseRawSourceMap;
76167     function decodeMappings(mappings) {
76168         var done = false;
76169         var pos = 0;
76170         var generatedLine = 0;
76171         var generatedCharacter = 0;
76172         var sourceIndex = 0;
76173         var sourceLine = 0;
76174         var sourceCharacter = 0;
76175         var nameIndex = 0;
76176         var error;
76177         return {
76178             get pos() { return pos; },
76179             get error() { return error; },
76180             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
76181             next: function () {
76182                 while (!done && pos < mappings.length) {
76183                     var ch = mappings.charCodeAt(pos);
76184                     if (ch === 59 /* semicolon */) {
76185                         // new line
76186                         generatedLine++;
76187                         generatedCharacter = 0;
76188                         pos++;
76189                         continue;
76190                     }
76191                     if (ch === 44 /* comma */) {
76192                         // Next entry is on same line - no action needed
76193                         pos++;
76194                         continue;
76195                     }
76196                     var hasSource = false;
76197                     var hasName = false;
76198                     generatedCharacter += base64VLQFormatDecode();
76199                     if (hasReportedError())
76200                         return stopIterating();
76201                     if (generatedCharacter < 0)
76202                         return setErrorAndStopIterating("Invalid generatedCharacter found");
76203                     if (!isSourceMappingSegmentEnd()) {
76204                         hasSource = true;
76205                         sourceIndex += base64VLQFormatDecode();
76206                         if (hasReportedError())
76207                             return stopIterating();
76208                         if (sourceIndex < 0)
76209                             return setErrorAndStopIterating("Invalid sourceIndex found");
76210                         if (isSourceMappingSegmentEnd())
76211                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
76212                         sourceLine += base64VLQFormatDecode();
76213                         if (hasReportedError())
76214                             return stopIterating();
76215                         if (sourceLine < 0)
76216                             return setErrorAndStopIterating("Invalid sourceLine found");
76217                         if (isSourceMappingSegmentEnd())
76218                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
76219                         sourceCharacter += base64VLQFormatDecode();
76220                         if (hasReportedError())
76221                             return stopIterating();
76222                         if (sourceCharacter < 0)
76223                             return setErrorAndStopIterating("Invalid sourceCharacter found");
76224                         if (!isSourceMappingSegmentEnd()) {
76225                             hasName = true;
76226                             nameIndex += base64VLQFormatDecode();
76227                             if (hasReportedError())
76228                                 return stopIterating();
76229                             if (nameIndex < 0)
76230                                 return setErrorAndStopIterating("Invalid nameIndex found");
76231                             if (!isSourceMappingSegmentEnd())
76232                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
76233                         }
76234                     }
76235                     return { value: captureMapping(hasSource, hasName), done: done };
76236                 }
76237                 return stopIterating();
76238             }
76239         };
76240         function captureMapping(hasSource, hasName) {
76241             return {
76242                 generatedLine: generatedLine,
76243                 generatedCharacter: generatedCharacter,
76244                 sourceIndex: hasSource ? sourceIndex : undefined,
76245                 sourceLine: hasSource ? sourceLine : undefined,
76246                 sourceCharacter: hasSource ? sourceCharacter : undefined,
76247                 nameIndex: hasName ? nameIndex : undefined
76248             };
76249         }
76250         function stopIterating() {
76251             done = true;
76252             return { value: undefined, done: true };
76253         }
76254         function setError(message) {
76255             if (error === undefined) {
76256                 error = message;
76257             }
76258         }
76259         function setErrorAndStopIterating(message) {
76260             setError(message);
76261             return stopIterating();
76262         }
76263         function hasReportedError() {
76264             return error !== undefined;
76265         }
76266         function isSourceMappingSegmentEnd() {
76267             return (pos === mappings.length ||
76268                 mappings.charCodeAt(pos) === 44 /* comma */ ||
76269                 mappings.charCodeAt(pos) === 59 /* semicolon */);
76270         }
76271         function base64VLQFormatDecode() {
76272             var moreDigits = true;
76273             var shiftCount = 0;
76274             var value = 0;
76275             for (; moreDigits; pos++) {
76276                 if (pos >= mappings.length)
76277                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
76278                 // 6 digit number
76279                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
76280                 if (currentByte === -1)
76281                     return setError("Invalid character in VLQ"), -1;
76282                 // If msb is set, we still have more bits to continue
76283                 moreDigits = (currentByte & 32) !== 0;
76284                 // least significant 5 bits are the next msbs in the final value.
76285                 value = value | ((currentByte & 31) << shiftCount);
76286                 shiftCount += 5;
76287             }
76288             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
76289             if ((value & 1) === 0) {
76290                 // + number
76291                 value = value >> 1;
76292             }
76293             else {
76294                 // - number
76295                 value = value >> 1;
76296                 value = -value;
76297             }
76298             return value;
76299         }
76300     }
76301     ts.decodeMappings = decodeMappings;
76302     function sameMapping(left, right) {
76303         return left === right
76304             || left.generatedLine === right.generatedLine
76305                 && left.generatedCharacter === right.generatedCharacter
76306                 && left.sourceIndex === right.sourceIndex
76307                 && left.sourceLine === right.sourceLine
76308                 && left.sourceCharacter === right.sourceCharacter
76309                 && left.nameIndex === right.nameIndex;
76310     }
76311     ts.sameMapping = sameMapping;
76312     function isSourceMapping(mapping) {
76313         return mapping.sourceIndex !== undefined
76314             && mapping.sourceLine !== undefined
76315             && mapping.sourceCharacter !== undefined;
76316     }
76317     ts.isSourceMapping = isSourceMapping;
76318     function base64FormatEncode(value) {
76319         return value >= 0 && value < 26 ? 65 /* A */ + value :
76320             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
76321                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
76322                     value === 62 ? 43 /* plus */ :
76323                         value === 63 ? 47 /* slash */ :
76324                             ts.Debug.fail(value + ": not a base64 value");
76325     }
76326     function base64FormatDecode(ch) {
76327         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
76328             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
76329                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
76330                     ch === 43 /* plus */ ? 62 :
76331                         ch === 47 /* slash */ ? 63 :
76332                             -1;
76333     }
76334     function base64VLQFormatEncode(inValue) {
76335         // Add a new least significant bit that has the sign of the value.
76336         // if negative number the least significant bit that gets added to the number has value 1
76337         // else least significant bit value that gets added is 0
76338         // eg. -1 changes to binary : 01 [1] => 3
76339         //     +1 changes to binary : 01 [0] => 2
76340         if (inValue < 0) {
76341             inValue = ((-inValue) << 1) + 1;
76342         }
76343         else {
76344             inValue = inValue << 1;
76345         }
76346         // Encode 5 bits at a time starting from least significant bits
76347         var encodedStr = "";
76348         do {
76349             var currentDigit = inValue & 31; // 11111
76350             inValue = inValue >> 5;
76351             if (inValue > 0) {
76352                 // There are still more digits to decode, set the msb (6th bit)
76353                 currentDigit = currentDigit | 32;
76354             }
76355             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
76356         } while (inValue > 0);
76357         return encodedStr;
76358     }
76359     function isSourceMappedPosition(value) {
76360         return value.sourceIndex !== undefined
76361             && value.sourcePosition !== undefined;
76362     }
76363     function sameMappedPosition(left, right) {
76364         return left.generatedPosition === right.generatedPosition
76365             && left.sourceIndex === right.sourceIndex
76366             && left.sourcePosition === right.sourcePosition;
76367     }
76368     function compareSourcePositions(left, right) {
76369         // Compares sourcePosition without comparing sourceIndex
76370         // since the mappings are grouped by sourceIndex
76371         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
76372         return ts.compareValues(left.sourcePosition, right.sourcePosition);
76373     }
76374     function compareGeneratedPositions(left, right) {
76375         return ts.compareValues(left.generatedPosition, right.generatedPosition);
76376     }
76377     function getSourcePositionOfMapping(value) {
76378         return value.sourcePosition;
76379     }
76380     function getGeneratedPositionOfMapping(value) {
76381         return value.generatedPosition;
76382     }
76383     function createDocumentPositionMapper(host, map, mapPath) {
76384         var mapDirectory = ts.getDirectoryPath(mapPath);
76385         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
76386         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
76387         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
76388         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
76389         var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
76390         var decodedMappings;
76391         var generatedMappings;
76392         var sourceMappings;
76393         return {
76394             getSourcePosition: getSourcePosition,
76395             getGeneratedPosition: getGeneratedPosition
76396         };
76397         function processMapping(mapping) {
76398             var generatedPosition = generatedFile !== undefined
76399                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
76400                 : -1;
76401             var source;
76402             var sourcePosition;
76403             if (isSourceMapping(mapping)) {
76404                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
76405                 source = map.sources[mapping.sourceIndex];
76406                 sourcePosition = sourceFile !== undefined
76407                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
76408                     : -1;
76409             }
76410             return {
76411                 generatedPosition: generatedPosition,
76412                 source: source,
76413                 sourceIndex: mapping.sourceIndex,
76414                 sourcePosition: sourcePosition,
76415                 nameIndex: mapping.nameIndex
76416             };
76417         }
76418         function getDecodedMappings() {
76419             if (decodedMappings === undefined) {
76420                 var decoder = decodeMappings(map.mappings);
76421                 var mappings = ts.arrayFrom(decoder, processMapping);
76422                 if (decoder.error !== undefined) {
76423                     if (host.log) {
76424                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
76425                     }
76426                     decodedMappings = ts.emptyArray;
76427                 }
76428                 else {
76429                     decodedMappings = mappings;
76430                 }
76431             }
76432             return decodedMappings;
76433         }
76434         function getSourceMappings(sourceIndex) {
76435             if (sourceMappings === undefined) {
76436                 var lists = [];
76437                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76438                     var mapping = _a[_i];
76439                     if (!isSourceMappedPosition(mapping))
76440                         continue;
76441                     var list = lists[mapping.sourceIndex];
76442                     if (!list)
76443                         lists[mapping.sourceIndex] = list = [];
76444                     list.push(mapping);
76445                 }
76446                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
76447             }
76448             return sourceMappings[sourceIndex];
76449         }
76450         function getGeneratedMappings() {
76451             if (generatedMappings === undefined) {
76452                 var list = [];
76453                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76454                     var mapping = _a[_i];
76455                     list.push(mapping);
76456                 }
76457                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
76458             }
76459             return generatedMappings;
76460         }
76461         function getGeneratedPosition(loc) {
76462             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
76463             if (sourceIndex === undefined)
76464                 return loc;
76465             var sourceMappings = getSourceMappings(sourceIndex);
76466             if (!ts.some(sourceMappings))
76467                 return loc;
76468             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
76469             if (targetIndex < 0) {
76470                 // if no exact match, closest is 2's complement of result
76471                 targetIndex = ~targetIndex;
76472             }
76473             var mapping = sourceMappings[targetIndex];
76474             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
76475                 return loc;
76476             }
76477             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
76478         }
76479         function getSourcePosition(loc) {
76480             var generatedMappings = getGeneratedMappings();
76481             if (!ts.some(generatedMappings))
76482                 return loc;
76483             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
76484             if (targetIndex < 0) {
76485                 // if no exact match, closest is 2's complement of result
76486                 targetIndex = ~targetIndex;
76487             }
76488             var mapping = generatedMappings[targetIndex];
76489             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
76490                 return loc;
76491             }
76492             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
76493         }
76494     }
76495     ts.createDocumentPositionMapper = createDocumentPositionMapper;
76496     ts.identitySourceMapConsumer = {
76497         getSourcePosition: ts.identity,
76498         getGeneratedPosition: ts.identity
76499     };
76500 })(ts || (ts = {}));
76501 /* @internal */
76502 var ts;
76503 (function (ts) {
76504     function getOriginalNodeId(node) {
76505         node = ts.getOriginalNode(node);
76506         return node ? ts.getNodeId(node) : 0;
76507     }
76508     ts.getOriginalNodeId = getOriginalNodeId;
76509     function containsDefaultReference(node) {
76510         if (!node)
76511             return false;
76512         if (!ts.isNamedImports(node))
76513             return false;
76514         return ts.some(node.elements, isNamedDefaultReference);
76515     }
76516     function isNamedDefaultReference(e) {
76517         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
76518     }
76519     function chainBundle(transformSourceFile) {
76520         return transformSourceFileOrBundle;
76521         function transformSourceFileOrBundle(node) {
76522             return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
76523         }
76524         function transformBundle(node) {
76525             return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
76526         }
76527     }
76528     ts.chainBundle = chainBundle;
76529     function getExportNeedsImportStarHelper(node) {
76530         return !!ts.getNamespaceDeclarationNode(node);
76531     }
76532     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
76533     function getImportNeedsImportStarHelper(node) {
76534         if (!!ts.getNamespaceDeclarationNode(node)) {
76535             return true;
76536         }
76537         var bindings = node.importClause && node.importClause.namedBindings;
76538         if (!bindings) {
76539             return false;
76540         }
76541         if (!ts.isNamedImports(bindings))
76542             return false;
76543         var defaultRefCount = 0;
76544         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
76545             var binding = _a[_i];
76546             if (isNamedDefaultReference(binding)) {
76547                 defaultRefCount++;
76548             }
76549         }
76550         // 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
76551         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
76552     }
76553     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
76554     function getImportNeedsImportDefaultHelper(node) {
76555         // 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)
76556         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
76557     }
76558     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
76559     function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
76560         var externalImports = [];
76561         var exportSpecifiers = ts.createMultiMap();
76562         var exportedBindings = [];
76563         var uniqueExports = ts.createMap();
76564         var exportedNames;
76565         var hasExportDefault = false;
76566         var exportEquals;
76567         var hasExportStarsToExportValues = false;
76568         var hasImportStar = false;
76569         var hasImportDefault = false;
76570         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76571             var node = _a[_i];
76572             switch (node.kind) {
76573                 case 254 /* ImportDeclaration */:
76574                     // import "mod"
76575                     // import x from "mod"
76576                     // import * as x from "mod"
76577                     // import { x, y } from "mod"
76578                     externalImports.push(node);
76579                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
76580                         hasImportStar = true;
76581                     }
76582                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
76583                         hasImportDefault = true;
76584                     }
76585                     break;
76586                 case 253 /* ImportEqualsDeclaration */:
76587                     if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
76588                         // import x = require("mod")
76589                         externalImports.push(node);
76590                     }
76591                     break;
76592                 case 260 /* ExportDeclaration */:
76593                     if (node.moduleSpecifier) {
76594                         if (!node.exportClause) {
76595                             // export * from "mod"
76596                             externalImports.push(node);
76597                             hasExportStarsToExportValues = true;
76598                         }
76599                         else {
76600                             // export * as ns from "mod"
76601                             // export { x, y } from "mod"
76602                             externalImports.push(node);
76603                         }
76604                     }
76605                     else {
76606                         // export { x, y }
76607                         for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
76608                             var specifier = _c[_b];
76609                             if (!uniqueExports.get(ts.idText(specifier.name))) {
76610                                 var name = specifier.propertyName || specifier.name;
76611                                 exportSpecifiers.add(ts.idText(name), specifier);
76612                                 var decl = resolver.getReferencedImportDeclaration(name)
76613                                     || resolver.getReferencedValueDeclaration(name);
76614                                 if (decl) {
76615                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
76616                                 }
76617                                 uniqueExports.set(ts.idText(specifier.name), true);
76618                                 exportedNames = ts.append(exportedNames, specifier.name);
76619                             }
76620                         }
76621                     }
76622                     break;
76623                 case 259 /* ExportAssignment */:
76624                     if (node.isExportEquals && !exportEquals) {
76625                         // export = x
76626                         exportEquals = node;
76627                     }
76628                     break;
76629                 case 225 /* VariableStatement */:
76630                     if (ts.hasModifier(node, 1 /* Export */)) {
76631                         for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
76632                             var decl = _e[_d];
76633                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
76634                         }
76635                     }
76636                     break;
76637                 case 244 /* FunctionDeclaration */:
76638                     if (ts.hasModifier(node, 1 /* Export */)) {
76639                         if (ts.hasModifier(node, 512 /* Default */)) {
76640                             // export default function() { }
76641                             if (!hasExportDefault) {
76642                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76643                                 hasExportDefault = true;
76644                             }
76645                         }
76646                         else {
76647                             // export function x() { }
76648                             var name = node.name;
76649                             if (!uniqueExports.get(ts.idText(name))) {
76650                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76651                                 uniqueExports.set(ts.idText(name), true);
76652                                 exportedNames = ts.append(exportedNames, name);
76653                             }
76654                         }
76655                     }
76656                     break;
76657                 case 245 /* ClassDeclaration */:
76658                     if (ts.hasModifier(node, 1 /* Export */)) {
76659                         if (ts.hasModifier(node, 512 /* Default */)) {
76660                             // export default class { }
76661                             if (!hasExportDefault) {
76662                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76663                                 hasExportDefault = true;
76664                             }
76665                         }
76666                         else {
76667                             // export class x { }
76668                             var name = node.name;
76669                             if (name && !uniqueExports.get(ts.idText(name))) {
76670                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76671                                 uniqueExports.set(ts.idText(name), true);
76672                                 exportedNames = ts.append(exportedNames, name);
76673                             }
76674                         }
76675                     }
76676                     break;
76677             }
76678         }
76679         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
76680         if (externalHelpersImportDeclaration) {
76681             externalImports.unshift(externalHelpersImportDeclaration);
76682         }
76683         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
76684     }
76685     ts.collectExternalModuleInfo = collectExternalModuleInfo;
76686     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
76687         if (ts.isBindingPattern(decl.name)) {
76688             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
76689                 var element = _a[_i];
76690                 if (!ts.isOmittedExpression(element)) {
76691                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
76692                 }
76693             }
76694         }
76695         else if (!ts.isGeneratedIdentifier(decl.name)) {
76696             var text = ts.idText(decl.name);
76697             if (!uniqueExports.get(text)) {
76698                 uniqueExports.set(text, true);
76699                 exportedNames = ts.append(exportedNames, decl.name);
76700             }
76701         }
76702         return exportedNames;
76703     }
76704     /** Use a sparse array as a multi-map. */
76705     function multiMapSparseArrayAdd(map, key, value) {
76706         var values = map[key];
76707         if (values) {
76708             values.push(value);
76709         }
76710         else {
76711             map[key] = values = [value];
76712         }
76713         return values;
76714     }
76715     /**
76716      * Used in the module transformer to check if an expression is reasonably without sideeffect,
76717      *  and thus better to copy into multiple places rather than to cache in a temporary variable
76718      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
76719      */
76720     function isSimpleCopiableExpression(expression) {
76721         return ts.isStringLiteralLike(expression) ||
76722             expression.kind === 8 /* NumericLiteral */ ||
76723             ts.isKeyword(expression.kind) ||
76724             ts.isIdentifier(expression);
76725     }
76726     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
76727     /**
76728      * A simple inlinable expression is an expression which can be copied into multiple locations
76729      * without risk of repeating any sideeffects and whose value could not possibly change between
76730      * any such locations
76731      */
76732     function isSimpleInlineableExpression(expression) {
76733         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
76734             ts.isWellKnownSymbolSyntactically(expression);
76735     }
76736     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
76737     function isCompoundAssignment(kind) {
76738         return kind >= 63 /* FirstCompoundAssignment */
76739             && kind <= 74 /* LastCompoundAssignment */;
76740     }
76741     ts.isCompoundAssignment = isCompoundAssignment;
76742     function getNonAssignmentOperatorForCompoundAssignment(kind) {
76743         switch (kind) {
76744             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
76745             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
76746             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
76747             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
76748             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
76749             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
76750             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
76751             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
76752             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
76753             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
76754             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
76755             case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
76756         }
76757     }
76758     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
76759     /**
76760      * Adds super call and preceding prologue directives into the list of statements.
76761      *
76762      * @param ctor The constructor node.
76763      * @param result The list of statements.
76764      * @param visitor The visitor to apply to each node added to the result array.
76765      * @returns index of the statement that follows super call
76766      */
76767     function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
76768         if (ctor.body) {
76769             var statements = ctor.body.statements;
76770             // add prologue directives to the list (if any)
76771             var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
76772             if (index === statements.length) {
76773                 // list contains nothing but prologue directives (or empty) - exit
76774                 return index;
76775             }
76776             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
76777             if (superIndex > -1) {
76778                 for (var i = index; i <= superIndex; i++) {
76779                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
76780                 }
76781                 return superIndex + 1;
76782             }
76783             return index;
76784         }
76785         return 0;
76786     }
76787     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
76788     /**
76789      * @param input Template string input strings
76790      * @param args Names which need to be made file-level unique
76791      */
76792     function helperString(input) {
76793         var args = [];
76794         for (var _i = 1; _i < arguments.length; _i++) {
76795             args[_i - 1] = arguments[_i];
76796         }
76797         return function (uniqueName) {
76798             var result = "";
76799             for (var i = 0; i < args.length; i++) {
76800                 result += input[i];
76801                 result += uniqueName(args[i]);
76802             }
76803             result += input[input.length - 1];
76804             return result;
76805         };
76806     }
76807     ts.helperString = helperString;
76808     /**
76809      * Gets all the static or all the instance property declarations of a class
76810      *
76811      * @param node The class node.
76812      * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
76813      */
76814     function getProperties(node, requireInitializer, isStatic) {
76815         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
76816     }
76817     ts.getProperties = getProperties;
76818     /**
76819      * Is a class element either a static or an instance property declaration with an initializer?
76820      *
76821      * @param member The class element node.
76822      * @param isStatic A value indicating whether the member should be a static or instance member.
76823      */
76824     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
76825         return ts.isPropertyDeclaration(member)
76826             && (!!member.initializer || !requireInitializer)
76827             && ts.hasStaticModifier(member) === isStatic;
76828     }
76829     /**
76830      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
76831      *
76832      * @param member The class element node.
76833      * @param isStatic A value indicating whether the member should be a static or instance member.
76834      */
76835     function isInitializedProperty(member) {
76836         return member.kind === 159 /* PropertyDeclaration */
76837             && member.initializer !== undefined;
76838     }
76839     ts.isInitializedProperty = isInitializedProperty;
76840 })(ts || (ts = {}));
76841 /*@internal*/
76842 var ts;
76843 (function (ts) {
76844     var FlattenLevel;
76845     (function (FlattenLevel) {
76846         FlattenLevel[FlattenLevel["All"] = 0] = "All";
76847         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
76848     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
76849     /**
76850      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
76851      *
76852      * @param node The node to flatten.
76853      * @param visitor An optional visitor used to visit initializers.
76854      * @param context The transformation context.
76855      * @param level Indicates the extent to which flattening should occur.
76856      * @param needsValue An optional value indicating whether the value from the right-hand-side of
76857      * the destructuring assignment is needed as part of a larger expression.
76858      * @param createAssignmentCallback An optional callback used to create the assignment expression.
76859      */
76860     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
76861         var location = node;
76862         var value;
76863         if (ts.isDestructuringAssignment(node)) {
76864             value = node.right;
76865             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
76866                 if (ts.isDestructuringAssignment(value)) {
76867                     location = node = value;
76868                     value = node.right;
76869                 }
76870                 else {
76871                     return ts.visitNode(value, visitor, ts.isExpression);
76872                 }
76873             }
76874         }
76875         var expressions;
76876         var flattenContext = {
76877             context: context,
76878             level: level,
76879             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76880             hoistTempVariables: true,
76881             emitExpression: emitExpression,
76882             emitBindingOrAssignment: emitBindingOrAssignment,
76883             createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
76884             createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
76885             createArrayBindingOrAssignmentElement: makeAssignmentElement,
76886             visitor: visitor
76887         };
76888         if (value) {
76889             value = ts.visitNode(value, visitor, ts.isExpression);
76890             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
76891                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
76892                 // If the right-hand value of the assignment is also an assignment target then
76893                 // we need to cache the right-hand value.
76894                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
76895             }
76896             else if (needsValue) {
76897                 // If the right-hand value of the destructuring assignment needs to be preserved (as
76898                 // is the case when the destructuring assignment is part of a larger expression),
76899                 // then we need to cache the right-hand value.
76900                 //
76901                 // The source map location for the assignment should point to the entire binary
76902                 // expression.
76903                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
76904             }
76905             else if (ts.nodeIsSynthesized(node)) {
76906                 // Generally, the source map location for a destructuring assignment is the root
76907                 // expression.
76908                 //
76909                 // However, if the root expression is synthesized (as in the case
76910                 // of the initializer when transforming a ForOfStatement), then the source map
76911                 // location should point to the right-hand value of the expression.
76912                 location = value;
76913             }
76914         }
76915         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
76916         if (value && needsValue) {
76917             if (!ts.some(expressions)) {
76918                 return value;
76919             }
76920             expressions.push(value);
76921         }
76922         return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
76923         function emitExpression(expression) {
76924             ts.aggregateTransformFlags(expression);
76925             expressions = ts.append(expressions, expression);
76926         }
76927         function emitBindingOrAssignment(target, value, location, original) {
76928             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
76929             var expression = createAssignmentCallback
76930                 ? createAssignmentCallback(target, value, location)
76931                 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
76932             expression.original = original;
76933             emitExpression(expression);
76934         }
76935     }
76936     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
76937     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
76938         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76939         if (ts.isBindingOrAssignmentPattern(target)) {
76940             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
76941         }
76942         else if (ts.isIdentifier(target)) {
76943             return target.escapedText === escapedName;
76944         }
76945         return false;
76946     }
76947     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
76948         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76949         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
76950             var element = elements_3[_i];
76951             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
76952                 return true;
76953             }
76954         }
76955         return false;
76956     }
76957     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
76958         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
76959         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
76960             return true;
76961         }
76962         var target = ts.getTargetOfBindingOrAssignmentElement(element);
76963         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
76964     }
76965     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
76966         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
76967     }
76968     /**
76969      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
76970      *
76971      * @param node The node to flatten.
76972      * @param visitor An optional visitor used to visit initializers.
76973      * @param context The transformation context.
76974      * @param boundValue The value bound to the declaration.
76975      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
76976      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
76977      * @param level Indicates the extent to which flattening should occur.
76978      */
76979     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
76980         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
76981         var pendingExpressions;
76982         var pendingDeclarations = [];
76983         var declarations = [];
76984         var flattenContext = {
76985             context: context,
76986             level: level,
76987             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76988             hoistTempVariables: hoistTempVariables,
76989             emitExpression: emitExpression,
76990             emitBindingOrAssignment: emitBindingOrAssignment,
76991             createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
76992             createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
76993             createArrayBindingOrAssignmentElement: makeBindingElement,
76994             visitor: visitor
76995         };
76996         if (ts.isVariableDeclaration(node)) {
76997             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
76998             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
76999                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
77000                 // If the right-hand value of the assignment is also an assignment target then
77001                 // we need to cache the right-hand value.
77002                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
77003                 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
77004             }
77005         }
77006         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
77007         if (pendingExpressions) {
77008             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77009             if (hoistTempVariables) {
77010                 var value = ts.inlineExpressions(pendingExpressions);
77011                 pendingExpressions = undefined;
77012                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
77013             }
77014             else {
77015                 context.hoistVariableDeclaration(temp);
77016                 var pendingDeclaration = ts.last(pendingDeclarations);
77017                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
77018                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
77019                 pendingDeclaration.value = temp;
77020             }
77021         }
77022         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
77023             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
77024             var variable = ts.createVariableDeclaration(name, 
77025             /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
77026             variable.original = original;
77027             ts.setTextRange(variable, location);
77028             ts.aggregateTransformFlags(variable);
77029             declarations.push(variable);
77030         }
77031         return declarations;
77032         function emitExpression(value) {
77033             pendingExpressions = ts.append(pendingExpressions, value);
77034         }
77035         function emitBindingOrAssignment(target, value, location, original) {
77036             ts.Debug.assertNode(target, ts.isBindingName);
77037             if (pendingExpressions) {
77038                 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
77039                 pendingExpressions = undefined;
77040             }
77041             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
77042         }
77043     }
77044     ts.flattenDestructuringBinding = flattenDestructuringBinding;
77045     /**
77046      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
77047      *
77048      * @param flattenContext Options used to control flattening.
77049      * @param element The element to flatten.
77050      * @param value The current RHS value to assign to the element.
77051      * @param location The location to use for source maps and comments.
77052      * @param skipInitializer An optional value indicating whether to include the initializer
77053      * for the element.
77054      */
77055     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
77056         if (!skipInitializer) {
77057             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
77058             if (initializer) {
77059                 // Combine value and initializer
77060                 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
77061             }
77062             else if (!value) {
77063                 // Use 'void 0' in absence of value and initializer
77064                 value = ts.createVoidZero();
77065             }
77066         }
77067         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
77068         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
77069             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
77070         }
77071         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
77072             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
77073         }
77074         else {
77075             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
77076         }
77077     }
77078     /**
77079      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
77080      *
77081      * @param flattenContext Options used to control flattening.
77082      * @param parent The parent element of the pattern.
77083      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
77084      * @param value The current RHS value to assign to the element.
77085      * @param location The location to use for source maps and comments.
77086      */
77087     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
77088         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
77089         var numElements = elements.length;
77090         if (numElements !== 1) {
77091             // For anything other than a single-element destructuring we need to generate a temporary
77092             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
77093             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
77094             // so in that case, we'll intentionally create that temporary.
77095             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
77096             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
77097         }
77098         var bindingElements;
77099         var computedTempVariables;
77100         for (var i = 0; i < numElements; i++) {
77101             var element = elements[i];
77102             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77103                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
77104                 if (flattenContext.level >= 1 /* ObjectRest */
77105                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
77106                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
77107                     && !ts.isComputedPropertyName(propertyName)) {
77108                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
77109                 }
77110                 else {
77111                     if (bindingElements) {
77112                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77113                         bindingElements = undefined;
77114                     }
77115                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
77116                     if (ts.isComputedPropertyName(propertyName)) {
77117                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
77118                     }
77119                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77120                 }
77121             }
77122             else if (i === numElements - 1) {
77123                 if (bindingElements) {
77124                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77125                     bindingElements = undefined;
77126                 }
77127                 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
77128                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
77129             }
77130         }
77131         if (bindingElements) {
77132             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77133         }
77134     }
77135     /**
77136      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
77137      *
77138      * @param flattenContext Options used to control flattening.
77139      * @param parent The parent element of the pattern.
77140      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
77141      * @param value The current RHS value to assign to the element.
77142      * @param location The location to use for source maps and comments.
77143      */
77144     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
77145         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
77146         var numElements = elements.length;
77147         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
77148             // Read the elements of the iterable into an array
77149             value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
77150                 ? undefined
77151                 : numElements, location), 
77152             /*reuseIdentifierExpressions*/ false, location);
77153         }
77154         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
77155             || ts.every(elements, ts.isOmittedExpression)) {
77156             // For anything other than a single-element destructuring we need to generate a temporary
77157             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
77158             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
77159             // so in that case, we'll intentionally create that temporary.
77160             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
77161             // then we will create temporary variable.
77162             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
77163             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
77164         }
77165         var bindingElements;
77166         var restContainingElements;
77167         for (var i = 0; i < numElements; i++) {
77168             var element = elements[i];
77169             if (flattenContext.level >= 1 /* ObjectRest */) {
77170                 // If an array pattern contains an ObjectRest, we must cache the result so that we
77171                 // can perform the ObjectRest destructuring in a different declaration
77172                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
77173                     var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77174                     if (flattenContext.hoistTempVariables) {
77175                         flattenContext.context.hoistVariableDeclaration(temp);
77176                     }
77177                     restContainingElements = ts.append(restContainingElements, [temp, element]);
77178                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
77179                 }
77180                 else {
77181                     bindingElements = ts.append(bindingElements, element);
77182                 }
77183             }
77184             else if (ts.isOmittedExpression(element)) {
77185                 continue;
77186             }
77187             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77188                 var rhsValue = ts.createElementAccess(value, i);
77189                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77190             }
77191             else if (i === numElements - 1) {
77192                 var rhsValue = ts.createArraySlice(value, i);
77193                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77194             }
77195         }
77196         if (bindingElements) {
77197             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77198         }
77199         if (restContainingElements) {
77200             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
77201                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
77202                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
77203             }
77204         }
77205     }
77206     /**
77207      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
77208      *
77209      * @param flattenContext Options used to control flattening.
77210      * @param value The RHS value to test.
77211      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
77212      * @param location The location to use for source maps and comments.
77213      */
77214     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
77215         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
77216         return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
77217     }
77218     /**
77219      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
77220      * right-hand side of a transformed destructuring assignment.
77221      *
77222      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
77223      *
77224      * @param flattenContext Options used to control flattening.
77225      * @param value The RHS value that is the source of the property.
77226      * @param propertyName The destructuring property name.
77227      */
77228     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
77229         if (ts.isComputedPropertyName(propertyName)) {
77230             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
77231             return ts.createElementAccess(value, argumentExpression);
77232         }
77233         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
77234             var argumentExpression = ts.getSynthesizedClone(propertyName);
77235             argumentExpression.text = argumentExpression.text;
77236             return ts.createElementAccess(value, argumentExpression);
77237         }
77238         else {
77239             var name = ts.createIdentifier(ts.idText(propertyName));
77240             return ts.createPropertyAccess(value, name);
77241         }
77242     }
77243     /**
77244      * Ensures that there exists a declared identifier whose value holds the given expression.
77245      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
77246      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
77247      *
77248      * @param flattenContext Options used to control flattening.
77249      * @param value the expression whose value needs to be bound.
77250      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
77251      * false if it is necessary to always emit an identifier.
77252      * @param location The location to use for source maps and comments.
77253      */
77254     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
77255         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
77256             return value;
77257         }
77258         else {
77259             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77260             if (flattenContext.hoistTempVariables) {
77261                 flattenContext.context.hoistVariableDeclaration(temp);
77262                 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
77263             }
77264             else {
77265                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
77266             }
77267             return temp;
77268         }
77269     }
77270     function makeArrayBindingPattern(elements) {
77271         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
77272         return ts.createArrayBindingPattern(elements);
77273     }
77274     function makeArrayAssignmentPattern(elements) {
77275         return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
77276     }
77277     function makeObjectBindingPattern(elements) {
77278         ts.Debug.assertEachNode(elements, ts.isBindingElement);
77279         return ts.createObjectBindingPattern(elements);
77280     }
77281     function makeObjectAssignmentPattern(elements) {
77282         return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
77283     }
77284     function makeBindingElement(name) {
77285         return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
77286     }
77287     function makeAssignmentElement(name) {
77288         return name;
77289     }
77290     ts.restHelper = {
77291         name: "typescript:rest",
77292         importName: "__rest",
77293         scoped: false,
77294         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            };"
77295     };
77296     /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
77297      * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
77298      */
77299     function createRestCall(context, value, elements, computedTempVariables, location) {
77300         context.requestEmitHelper(ts.restHelper);
77301         var propertyNames = [];
77302         var computedTempVariableOffset = 0;
77303         for (var i = 0; i < elements.length - 1; i++) {
77304             var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
77305             if (propertyName) {
77306                 if (ts.isComputedPropertyName(propertyName)) {
77307                     var temp = computedTempVariables[computedTempVariableOffset];
77308                     computedTempVariableOffset++;
77309                     // typeof _tmp === "symbol" ? _tmp : _tmp + ""
77310                     propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
77311                 }
77312                 else {
77313                     propertyNames.push(ts.createLiteral(propertyName));
77314                 }
77315             }
77316         }
77317         return ts.createCall(ts.getUnscopedHelperName("__rest"), 
77318         /*typeArguments*/ undefined, [
77319             value,
77320             ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
77321         ]);
77322     }
77323 })(ts || (ts = {}));
77324 /*@internal*/
77325 var ts;
77326 (function (ts) {
77327     var ProcessLevel;
77328     (function (ProcessLevel) {
77329         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
77330         ProcessLevel[ProcessLevel["All"] = 1] = "All";
77331     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
77332     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
77333         // Visit the tag expression
77334         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
77335         // Build up the template arguments and the raw and cooked strings for the template.
77336         // We start out with 'undefined' for the first argument and revisit later
77337         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
77338         var templateArguments = [undefined];
77339         var cookedStrings = [];
77340         var rawStrings = [];
77341         var template = node.template;
77342         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template))
77343             return node;
77344         if (ts.isNoSubstitutionTemplateLiteral(template)) {
77345             cookedStrings.push(createTemplateCooked(template));
77346             rawStrings.push(getRawLiteral(template, currentSourceFile));
77347         }
77348         else {
77349             cookedStrings.push(createTemplateCooked(template.head));
77350             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
77351             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
77352                 var templateSpan = _a[_i];
77353                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
77354                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
77355                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
77356             }
77357         }
77358         var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
77359         // Create a variable to cache the template object if we're in a module.
77360         // Do not do this in the global scope, as any variable we currently generate could conflict with
77361         // variables from outside of the current compilation. In the future, we can revisit this behavior.
77362         if (ts.isExternalModule(currentSourceFile)) {
77363             var tempVar = ts.createUniqueName("templateObject");
77364             recordTaggedTemplateString(tempVar);
77365             templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
77366         }
77367         else {
77368             templateArguments[0] = helperCall;
77369         }
77370         return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
77371     }
77372     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
77373     function createTemplateCooked(template) {
77374         return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text);
77375     }
77376     /**
77377      * Creates an ES5 compatible literal from an ES6 template literal.
77378      *
77379      * @param node The ES6 template literal.
77380      */
77381     function getRawLiteral(node, currentSourceFile) {
77382         // Find original source text, since we need to emit the raw strings of the tagged template.
77383         // The raw strings contain the (escaped) strings of what the user wrote.
77384         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
77385         var text = node.rawText;
77386         if (text === undefined) {
77387             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
77388             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
77389             // thus we need to remove those characters.
77390             // First template piece starts with "`", others with "}"
77391             // Last template piece ends with "`", others with "${"
77392             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
77393             text = text.substring(1, text.length - (isLast ? 1 : 2));
77394         }
77395         // Newline normalization:
77396         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
77397         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
77398         text = text.replace(/\r\n?/g, "\n");
77399         return ts.setTextRange(ts.createLiteral(text), node);
77400     }
77401     function createTemplateObjectHelper(context, cooked, raw) {
77402         context.requestEmitHelper(ts.templateObjectHelper);
77403         return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), 
77404         /*typeArguments*/ undefined, [
77405             cooked,
77406             raw
77407         ]);
77408     }
77409     ts.templateObjectHelper = {
77410         name: "typescript:makeTemplateObject",
77411         importName: "__makeTemplateObject",
77412         scoped: false,
77413         priority: 0,
77414         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            };"
77415     };
77416 })(ts || (ts = {}));
77417 /*@internal*/
77418 var ts;
77419 (function (ts) {
77420     /**
77421      * Indicates whether to emit type metadata in the new format.
77422      */
77423     var USE_NEW_TYPE_METADATA_FORMAT = false;
77424     var TypeScriptSubstitutionFlags;
77425     (function (TypeScriptSubstitutionFlags) {
77426         /** Enables substitutions for decorated classes. */
77427         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
77428         /** Enables substitutions for namespace exports. */
77429         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
77430         /* Enables substitutions for unqualified enum members */
77431         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
77432     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
77433     var ClassFacts;
77434     (function (ClassFacts) {
77435         ClassFacts[ClassFacts["None"] = 0] = "None";
77436         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
77437         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
77438         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
77439         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
77440         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
77441         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
77442         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
77443         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
77444         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
77445         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
77446         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
77447         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
77448     })(ClassFacts || (ClassFacts = {}));
77449     function transformTypeScript(context) {
77450         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
77451         var resolver = context.getEmitResolver();
77452         var compilerOptions = context.getCompilerOptions();
77453         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
77454         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
77455         var moduleKind = ts.getEmitModuleKind(compilerOptions);
77456         // Save the previous transformation hooks.
77457         var previousOnEmitNode = context.onEmitNode;
77458         var previousOnSubstituteNode = context.onSubstituteNode;
77459         // Set new transformation hooks.
77460         context.onEmitNode = onEmitNode;
77461         context.onSubstituteNode = onSubstituteNode;
77462         // Enable substitution for property/element access to emit const enum values.
77463         context.enableSubstitution(194 /* PropertyAccessExpression */);
77464         context.enableSubstitution(195 /* ElementAccessExpression */);
77465         // These variables contain state that changes as we descend into the tree.
77466         var currentSourceFile;
77467         var currentNamespace;
77468         var currentNamespaceContainerName;
77469         var currentLexicalScope;
77470         var currentNameScope;
77471         var currentScopeFirstDeclarationsOfName;
77472         var currentClassHasParameterProperties;
77473         /**
77474          * Keeps track of whether expression substitution has been enabled for specific edge cases.
77475          * They are persisted between each SourceFile transformation and should not be reset.
77476          */
77477         var enabledSubstitutions;
77478         /**
77479          * A map that keeps track of aliases created for classes with decorators to avoid issues
77480          * with the double-binding behavior of classes.
77481          */
77482         var classAliases;
77483         /**
77484          * Keeps track of whether we are within any containing namespaces when performing
77485          * just-in-time substitution while printing an expression identifier.
77486          */
77487         var applicableSubstitutions;
77488         return transformSourceFileOrBundle;
77489         function transformSourceFileOrBundle(node) {
77490             if (node.kind === 291 /* Bundle */) {
77491                 return transformBundle(node);
77492             }
77493             return transformSourceFile(node);
77494         }
77495         function transformBundle(node) {
77496             return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
77497                 if (prepend.kind === 293 /* InputFiles */) {
77498                     return ts.createUnparsedSourceFile(prepend, "js");
77499                 }
77500                 return prepend;
77501             }));
77502         }
77503         /**
77504          * Transform TypeScript-specific syntax in a SourceFile.
77505          *
77506          * @param node A SourceFile node.
77507          */
77508         function transformSourceFile(node) {
77509             if (node.isDeclarationFile) {
77510                 return node;
77511             }
77512             currentSourceFile = node;
77513             var visited = saveStateAndInvoke(node, visitSourceFile);
77514             ts.addEmitHelpers(visited, context.readEmitHelpers());
77515             currentSourceFile = undefined;
77516             return visited;
77517         }
77518         /**
77519          * Visits a node, saving and restoring state variables on the stack.
77520          *
77521          * @param node The node to visit.
77522          */
77523         function saveStateAndInvoke(node, f) {
77524             // Save state
77525             var savedCurrentScope = currentLexicalScope;
77526             var savedCurrentNameScope = currentNameScope;
77527             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
77528             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
77529             // Handle state changes before visiting a node.
77530             onBeforeVisitNode(node);
77531             var visited = f(node);
77532             // Restore state
77533             if (currentLexicalScope !== savedCurrentScope) {
77534                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
77535             }
77536             currentLexicalScope = savedCurrentScope;
77537             currentNameScope = savedCurrentNameScope;
77538             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
77539             return visited;
77540         }
77541         /**
77542          * Performs actions that should always occur immediately before visiting a node.
77543          *
77544          * @param node The node to visit.
77545          */
77546         function onBeforeVisitNode(node) {
77547             switch (node.kind) {
77548                 case 290 /* SourceFile */:
77549                 case 251 /* CaseBlock */:
77550                 case 250 /* ModuleBlock */:
77551                 case 223 /* Block */:
77552                     currentLexicalScope = node;
77553                     currentNameScope = undefined;
77554                     currentScopeFirstDeclarationsOfName = undefined;
77555                     break;
77556                 case 245 /* ClassDeclaration */:
77557                 case 244 /* FunctionDeclaration */:
77558                     if (ts.hasModifier(node, 2 /* Ambient */)) {
77559                         break;
77560                     }
77561                     // Record these declarations provided that they have a name.
77562                     if (node.name) {
77563                         recordEmittedDeclarationInScope(node);
77564                     }
77565                     else {
77566                         // These nodes should always have names unless they are default-exports;
77567                         // however, class declaration parsing allows for undefined names, so syntactically invalid
77568                         // programs may also have an undefined name.
77569                         ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
77570                     }
77571                     if (ts.isClassDeclaration(node)) {
77572                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
77573                         currentNameScope = node;
77574                     }
77575                     break;
77576             }
77577         }
77578         /**
77579          * General-purpose node visitor.
77580          *
77581          * @param node The node to visit.
77582          */
77583         function visitor(node) {
77584             return saveStateAndInvoke(node, visitorWorker);
77585         }
77586         /**
77587          * Visits and possibly transforms any node.
77588          *
77589          * @param node The node to visit.
77590          */
77591         function visitorWorker(node) {
77592             if (node.transformFlags & 1 /* ContainsTypeScript */) {
77593                 return visitTypeScript(node);
77594             }
77595             return node;
77596         }
77597         /**
77598          * Specialized visitor that visits the immediate children of a SourceFile.
77599          *
77600          * @param node The node to visit.
77601          */
77602         function sourceElementVisitor(node) {
77603             return saveStateAndInvoke(node, sourceElementVisitorWorker);
77604         }
77605         /**
77606          * Specialized visitor that visits the immediate children of a SourceFile.
77607          *
77608          * @param node The node to visit.
77609          */
77610         function sourceElementVisitorWorker(node) {
77611             switch (node.kind) {
77612                 case 254 /* ImportDeclaration */:
77613                 case 253 /* ImportEqualsDeclaration */:
77614                 case 259 /* ExportAssignment */:
77615                 case 260 /* ExportDeclaration */:
77616                     return visitEllidableStatement(node);
77617                 default:
77618                     return visitorWorker(node);
77619             }
77620         }
77621         function visitEllidableStatement(node) {
77622             var parsed = ts.getParseTreeNode(node);
77623             if (parsed !== node) {
77624                 // If the node has been transformed by a `before` transformer, perform no ellision on it
77625                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
77626                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
77627                 // and will trigger debug failures when debug verbosity is turned up
77628                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
77629                     // This node contains TypeScript, so we should visit its children.
77630                     return ts.visitEachChild(node, visitor, context);
77631                 }
77632                 // Otherwise, we can just return the node
77633                 return node;
77634             }
77635             switch (node.kind) {
77636                 case 254 /* ImportDeclaration */:
77637                     return visitImportDeclaration(node);
77638                 case 253 /* ImportEqualsDeclaration */:
77639                     return visitImportEqualsDeclaration(node);
77640                 case 259 /* ExportAssignment */:
77641                     return visitExportAssignment(node);
77642                 case 260 /* ExportDeclaration */:
77643                     return visitExportDeclaration(node);
77644                 default:
77645                     ts.Debug.fail("Unhandled ellided statement");
77646             }
77647         }
77648         /**
77649          * Specialized visitor that visits the immediate children of a namespace.
77650          *
77651          * @param node The node to visit.
77652          */
77653         function namespaceElementVisitor(node) {
77654             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
77655         }
77656         /**
77657          * Specialized visitor that visits the immediate children of a namespace.
77658          *
77659          * @param node The node to visit.
77660          */
77661         function namespaceElementVisitorWorker(node) {
77662             if (node.kind === 260 /* ExportDeclaration */ ||
77663                 node.kind === 254 /* ImportDeclaration */ ||
77664                 node.kind === 255 /* ImportClause */ ||
77665                 (node.kind === 253 /* ImportEqualsDeclaration */ &&
77666                     node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
77667                 // do not emit ES6 imports and exports since they are illegal inside a namespace
77668                 return undefined;
77669             }
77670             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
77671                 return visitTypeScript(node);
77672             }
77673             return node;
77674         }
77675         /**
77676          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77677          *
77678          * @param node The node to visit.
77679          */
77680         function classElementVisitor(node) {
77681             return saveStateAndInvoke(node, classElementVisitorWorker);
77682         }
77683         /**
77684          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77685          *
77686          * @param node The node to visit.
77687          */
77688         function classElementVisitorWorker(node) {
77689             switch (node.kind) {
77690                 case 162 /* Constructor */:
77691                     return visitConstructor(node);
77692                 case 159 /* PropertyDeclaration */:
77693                     // Property declarations are not TypeScript syntax, but they must be visited
77694                     // for the decorator transformation.
77695                     return visitPropertyDeclaration(node);
77696                 case 167 /* IndexSignature */:
77697                 case 163 /* GetAccessor */:
77698                 case 164 /* SetAccessor */:
77699                 case 161 /* MethodDeclaration */:
77700                     // Fallback to the default visit behavior.
77701                     return visitorWorker(node);
77702                 case 222 /* SemicolonClassElement */:
77703                     return node;
77704                 default:
77705                     return ts.Debug.failBadSyntaxKind(node);
77706             }
77707         }
77708         function modifierVisitor(node) {
77709             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
77710                 return undefined;
77711             }
77712             else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
77713                 return undefined;
77714             }
77715             return node;
77716         }
77717         /**
77718          * Branching visitor, visits a TypeScript syntax node.
77719          *
77720          * @param node The node to visit.
77721          */
77722         function visitTypeScript(node) {
77723             if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
77724                 // TypeScript ambient declarations are elided, but some comments may be preserved.
77725                 // See the implementation of `getLeadingComments` in comments.ts for more details.
77726                 return ts.createNotEmittedStatement(node);
77727             }
77728             switch (node.kind) {
77729                 case 89 /* ExportKeyword */:
77730                 case 84 /* DefaultKeyword */:
77731                     // ES6 export and default modifiers are elided when inside a namespace.
77732                     return currentNamespace ? undefined : node;
77733                 case 119 /* PublicKeyword */:
77734                 case 117 /* PrivateKeyword */:
77735                 case 118 /* ProtectedKeyword */:
77736                 case 122 /* AbstractKeyword */:
77737                 case 81 /* ConstKeyword */:
77738                 case 130 /* DeclareKeyword */:
77739                 case 138 /* ReadonlyKeyword */:
77740                 // TypeScript accessibility and readonly modifiers are elided
77741                 // falls through
77742                 case 174 /* ArrayType */:
77743                 case 175 /* TupleType */:
77744                 case 176 /* OptionalType */:
77745                 case 177 /* RestType */:
77746                 case 173 /* TypeLiteral */:
77747                 case 168 /* TypePredicate */:
77748                 case 155 /* TypeParameter */:
77749                 case 125 /* AnyKeyword */:
77750                 case 148 /* UnknownKeyword */:
77751                 case 128 /* BooleanKeyword */:
77752                 case 143 /* StringKeyword */:
77753                 case 140 /* NumberKeyword */:
77754                 case 137 /* NeverKeyword */:
77755                 case 110 /* VoidKeyword */:
77756                 case 144 /* SymbolKeyword */:
77757                 case 171 /* ConstructorType */:
77758                 case 170 /* FunctionType */:
77759                 case 172 /* TypeQuery */:
77760                 case 169 /* TypeReference */:
77761                 case 178 /* UnionType */:
77762                 case 179 /* IntersectionType */:
77763                 case 180 /* ConditionalType */:
77764                 case 182 /* ParenthesizedType */:
77765                 case 183 /* ThisType */:
77766                 case 184 /* TypeOperator */:
77767                 case 185 /* IndexedAccessType */:
77768                 case 186 /* MappedType */:
77769                 case 187 /* LiteralType */:
77770                 // TypeScript type nodes are elided.
77771                 // falls through
77772                 case 167 /* IndexSignature */:
77773                 // TypeScript index signatures are elided.
77774                 // falls through
77775                 case 157 /* Decorator */:
77776                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
77777                 // falls through
77778                 case 247 /* TypeAliasDeclaration */:
77779                     // TypeScript type-only declarations are elided.
77780                     return undefined;
77781                 case 159 /* PropertyDeclaration */:
77782                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
77783                     return visitPropertyDeclaration(node);
77784                 case 252 /* NamespaceExportDeclaration */:
77785                     // TypeScript namespace export declarations are elided.
77786                     return undefined;
77787                 case 162 /* Constructor */:
77788                     return visitConstructor(node);
77789                 case 246 /* InterfaceDeclaration */:
77790                     // TypeScript interfaces are elided, but some comments may be preserved.
77791                     // See the implementation of `getLeadingComments` in comments.ts for more details.
77792                     return ts.createNotEmittedStatement(node);
77793                 case 245 /* ClassDeclaration */:
77794                     // This may be a class declaration with TypeScript syntax extensions.
77795                     //
77796                     // TypeScript class syntax extensions include:
77797                     // - decorators
77798                     // - optional `implements` heritage clause
77799                     // - parameter property assignments in the constructor
77800                     // - index signatures
77801                     // - method overload signatures
77802                     return visitClassDeclaration(node);
77803                 case 214 /* ClassExpression */:
77804                     // This may be a class expression with TypeScript syntax extensions.
77805                     //
77806                     // TypeScript class syntax extensions include:
77807                     // - decorators
77808                     // - optional `implements` heritage clause
77809                     // - parameter property assignments in the constructor
77810                     // - index signatures
77811                     // - method overload signatures
77812                     return visitClassExpression(node);
77813                 case 279 /* HeritageClause */:
77814                     // This may be a heritage clause with TypeScript syntax extensions.
77815                     //
77816                     // TypeScript heritage clause extensions include:
77817                     // - `implements` clause
77818                     return visitHeritageClause(node);
77819                 case 216 /* ExpressionWithTypeArguments */:
77820                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
77821                     return visitExpressionWithTypeArguments(node);
77822                 case 161 /* MethodDeclaration */:
77823                     // TypeScript method declarations may have decorators, modifiers
77824                     // or type annotations.
77825                     return visitMethodDeclaration(node);
77826                 case 163 /* GetAccessor */:
77827                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
77828                     return visitGetAccessor(node);
77829                 case 164 /* SetAccessor */:
77830                     // Set Accessors can have TypeScript modifiers and type annotations.
77831                     return visitSetAccessor(node);
77832                 case 244 /* FunctionDeclaration */:
77833                     // Typescript function declarations can have modifiers, decorators, and type annotations.
77834                     return visitFunctionDeclaration(node);
77835                 case 201 /* FunctionExpression */:
77836                     // TypeScript function expressions can have modifiers and type annotations.
77837                     return visitFunctionExpression(node);
77838                 case 202 /* ArrowFunction */:
77839                     // TypeScript arrow functions can have modifiers and type annotations.
77840                     return visitArrowFunction(node);
77841                 case 156 /* Parameter */:
77842                     // This may be a parameter declaration with TypeScript syntax extensions.
77843                     //
77844                     // TypeScript parameter declaration syntax extensions include:
77845                     // - decorators
77846                     // - accessibility modifiers
77847                     // - the question mark (?) token for optional parameters
77848                     // - type annotations
77849                     // - this parameters
77850                     return visitParameter(node);
77851                 case 200 /* ParenthesizedExpression */:
77852                     // ParenthesizedExpressions are TypeScript if their expression is a
77853                     // TypeAssertion or AsExpression
77854                     return visitParenthesizedExpression(node);
77855                 case 199 /* TypeAssertionExpression */:
77856                 case 217 /* AsExpression */:
77857                     // TypeScript type assertions are removed, but their subtrees are preserved.
77858                     return visitAssertionExpression(node);
77859                 case 196 /* CallExpression */:
77860                     return visitCallExpression(node);
77861                 case 197 /* NewExpression */:
77862                     return visitNewExpression(node);
77863                 case 198 /* TaggedTemplateExpression */:
77864                     return visitTaggedTemplateExpression(node);
77865                 case 218 /* NonNullExpression */:
77866                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
77867                     return visitNonNullExpression(node);
77868                 case 248 /* EnumDeclaration */:
77869                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
77870                     return visitEnumDeclaration(node);
77871                 case 225 /* VariableStatement */:
77872                     // TypeScript namespace exports for variable statements must be transformed.
77873                     return visitVariableStatement(node);
77874                 case 242 /* VariableDeclaration */:
77875                     return visitVariableDeclaration(node);
77876                 case 249 /* ModuleDeclaration */:
77877                     // TypeScript namespace declarations must be transformed.
77878                     return visitModuleDeclaration(node);
77879                 case 253 /* ImportEqualsDeclaration */:
77880                     // TypeScript namespace or external module import.
77881                     return visitImportEqualsDeclaration(node);
77882                 case 267 /* JsxSelfClosingElement */:
77883                     return visitJsxSelfClosingElement(node);
77884                 case 268 /* JsxOpeningElement */:
77885                     return visitJsxJsxOpeningElement(node);
77886                 default:
77887                     // node contains some other TypeScript syntax
77888                     return ts.visitEachChild(node, visitor, context);
77889             }
77890         }
77891         function visitSourceFile(node) {
77892             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
77893                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
77894                 !ts.isJsonSourceFile(node);
77895             return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
77896         }
77897         /**
77898          * Tests whether we should emit a __decorate call for a class declaration.
77899          */
77900         function shouldEmitDecorateCallForClass(node) {
77901             if (node.decorators && node.decorators.length > 0) {
77902                 return true;
77903             }
77904             var constructor = ts.getFirstConstructorWithBody(node);
77905             if (constructor) {
77906                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
77907             }
77908             return false;
77909         }
77910         /**
77911          * Tests whether we should emit a __decorate call for a parameter declaration.
77912          */
77913         function shouldEmitDecorateCallForParameter(parameter) {
77914             return parameter.decorators !== undefined && parameter.decorators.length > 0;
77915         }
77916         function getClassFacts(node, staticProperties) {
77917             var facts = 0 /* None */;
77918             if (ts.some(staticProperties))
77919                 facts |= 1 /* HasStaticInitializedProperties */;
77920             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
77921             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
77922                 facts |= 64 /* IsDerivedClass */;
77923             if (shouldEmitDecorateCallForClass(node))
77924                 facts |= 2 /* HasConstructorDecorators */;
77925             if (ts.childIsDecorated(node))
77926                 facts |= 4 /* HasMemberDecorators */;
77927             if (isExportOfNamespace(node))
77928                 facts |= 8 /* IsExportOfNamespace */;
77929             else if (isDefaultExternalModuleExport(node))
77930                 facts |= 32 /* IsDefaultExternalExport */;
77931             else if (isNamedExternalModuleExport(node))
77932                 facts |= 16 /* IsNamedExternalExport */;
77933             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
77934                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
77935             return facts;
77936         }
77937         function hasTypeScriptClassSyntax(node) {
77938             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
77939         }
77940         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
77941             return ts.some(node.decorators)
77942                 || ts.some(node.typeParameters)
77943                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
77944                 || ts.some(node.members, hasTypeScriptClassSyntax);
77945         }
77946         function visitClassDeclaration(node) {
77947             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
77948                 return ts.visitEachChild(node, visitor, context);
77949             }
77950             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
77951             var facts = getClassFacts(node, staticProperties);
77952             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77953                 context.startLexicalEnvironment();
77954             }
77955             var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
77956             var classStatement = facts & 2 /* HasConstructorDecorators */
77957                 ? createClassDeclarationHeadWithDecorators(node, name)
77958                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
77959             var statements = [classStatement];
77960             // Write any decorators of the node.
77961             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
77962             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
77963             addConstructorDecorationStatement(statements, node);
77964             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77965                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
77966                 // 'es2015' transformer can properly nest static initializers and decorators. The result
77967                 // looks something like:
77968                 //
77969                 //  var C = function () {
77970                 //      class C {
77971                 //      }
77972                 //      C.static_prop = 1;
77973                 //      return C;
77974                 //  }();
77975                 //
77976                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
77977                 var localName = ts.getInternalName(node);
77978                 // The following partially-emitted expression exists purely to align our sourcemap
77979                 // emit with the original emitter.
77980                 var outer = ts.createPartiallyEmittedExpression(localName);
77981                 outer.end = closingBraceLocation.end;
77982                 ts.setEmitFlags(outer, 1536 /* NoComments */);
77983                 var statement = ts.createReturn(outer);
77984                 statement.pos = closingBraceLocation.pos;
77985                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
77986                 statements.push(statement);
77987                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
77988                 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
77989                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
77990                 var varStatement = ts.createVariableStatement(
77991                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
77992                     ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
77993                     /*type*/ undefined, iife)
77994                 ]));
77995                 ts.setOriginalNode(varStatement, node);
77996                 ts.setCommentRange(varStatement, node);
77997                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
77998                 ts.startOnNewLine(varStatement);
77999                 statements = [varStatement];
78000             }
78001             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
78002             // Otherwise, if the class was exported at the top level and was decorated, emit an export
78003             // declaration or export default for the class.
78004             if (facts & 8 /* IsExportOfNamespace */) {
78005                 addExportMemberAssignment(statements, node);
78006             }
78007             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
78008                 if (facts & 32 /* IsDefaultExternalExport */) {
78009                     statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
78010                 }
78011                 else if (facts & 16 /* IsNamedExternalExport */) {
78012                     statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
78013                 }
78014             }
78015             if (statements.length > 1) {
78016                 // Add a DeclarationMarker as a marker for the end of the declaration
78017                 statements.push(ts.createEndOfDeclarationMarker(node));
78018                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
78019             }
78020             return ts.singleOrMany(statements);
78021         }
78022         /**
78023          * Transforms a non-decorated class declaration and appends the resulting statements.
78024          *
78025          * @param node A ClassDeclaration node.
78026          * @param name The name of the class.
78027          * @param facts Precomputed facts about the class.
78028          */
78029         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
78030             //  ${modifiers} class ${name} ${heritageClauses} {
78031             //      ${members}
78032             //  }
78033             // we do not emit modifiers on the declaration if we are emitting an IIFE
78034             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
78035                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
78036                 : undefined;
78037             var classDeclaration = ts.createClassDeclaration(
78038             /*decorators*/ undefined, modifiers, name, 
78039             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
78040             // To better align with the old emitter, we should not emit a trailing source map
78041             // entry if the class has static properties.
78042             var emitFlags = ts.getEmitFlags(node);
78043             if (facts & 1 /* HasStaticInitializedProperties */) {
78044                 emitFlags |= 32 /* NoTrailingSourceMap */;
78045             }
78046             ts.aggregateTransformFlags(classDeclaration);
78047             ts.setTextRange(classDeclaration, node);
78048             ts.setOriginalNode(classDeclaration, node);
78049             ts.setEmitFlags(classDeclaration, emitFlags);
78050             return classDeclaration;
78051         }
78052         /**
78053          * Transforms a decorated class declaration and appends the resulting statements. If
78054          * the class requires an alias to avoid issues with double-binding, the alias is returned.
78055          */
78056         function createClassDeclarationHeadWithDecorators(node, name) {
78057             // When we emit an ES6 class that has a class decorator, we must tailor the
78058             // emit to certain specific cases.
78059             //
78060             // In the simplest case, we emit the class declaration as a let declaration, and
78061             // evaluate decorators after the close of the class body:
78062             //
78063             //  [Example 1]
78064             //  ---------------------------------------------------------------------
78065             //  TypeScript                      | Javascript
78066             //  ---------------------------------------------------------------------
78067             //  @dec                            | let C = class C {
78068             //  class C {                       | }
78069             //  }                               | C = __decorate([dec], C);
78070             //  ---------------------------------------------------------------------
78071             //  @dec                            | let C = class C {
78072             //  export class C {                | }
78073             //  }                               | C = __decorate([dec], C);
78074             //                                  | export { C };
78075             //  ---------------------------------------------------------------------
78076             //
78077             // If a class declaration contains a reference to itself *inside* of the class body,
78078             // this introduces two bindings to the class: One outside of the class body, and one
78079             // inside of the class body. If we apply decorators as in [Example 1] above, there
78080             // is the possibility that the decorator `dec` will return a new value for the
78081             // constructor, which would result in the binding inside of the class no longer
78082             // pointing to the same reference as the binding outside of the class.
78083             //
78084             // As a result, we must instead rewrite all references to the class *inside* of the
78085             // class body to instead point to a local temporary alias for the class:
78086             //
78087             //  [Example 2]
78088             //  ---------------------------------------------------------------------
78089             //  TypeScript                      | Javascript
78090             //  ---------------------------------------------------------------------
78091             //  @dec                            | let C = C_1 = class C {
78092             //  class C {                       |   static x() { return C_1.y; }
78093             //    static x() { return C.y; }    | }
78094             //    static y = 1;                 | C.y = 1;
78095             //  }                               | C = C_1 = __decorate([dec], C);
78096             //                                  | var C_1;
78097             //  ---------------------------------------------------------------------
78098             //  @dec                            | let C = class C {
78099             //  export class C {                |   static x() { return C_1.y; }
78100             //    static x() { return C.y; }    | }
78101             //    static y = 1;                 | C.y = 1;
78102             //  }                               | C = C_1 = __decorate([dec], C);
78103             //                                  | export { C };
78104             //                                  | var C_1;
78105             //  ---------------------------------------------------------------------
78106             //
78107             // If a class declaration is the default export of a module, we instead emit
78108             // the export after the decorated declaration:
78109             //
78110             //  [Example 3]
78111             //  ---------------------------------------------------------------------
78112             //  TypeScript                      | Javascript
78113             //  ---------------------------------------------------------------------
78114             //  @dec                            | let default_1 = class {
78115             //  export default class {          | }
78116             //  }                               | default_1 = __decorate([dec], default_1);
78117             //                                  | export default default_1;
78118             //  ---------------------------------------------------------------------
78119             //  @dec                            | let C = class C {
78120             //  export default class C {        | }
78121             //  }                               | C = __decorate([dec], C);
78122             //                                  | export default C;
78123             //  ---------------------------------------------------------------------
78124             //
78125             // If the class declaration is the default export and a reference to itself
78126             // inside of the class body, we must emit both an alias for the class *and*
78127             // move the export after the declaration:
78128             //
78129             //  [Example 4]
78130             //  ---------------------------------------------------------------------
78131             //  TypeScript                      | Javascript
78132             //  ---------------------------------------------------------------------
78133             //  @dec                            | let C = class C {
78134             //  export default class C {        |   static x() { return C_1.y; }
78135             //    static x() { return C.y; }    | }
78136             //    static y = 1;                 | C.y = 1;
78137             //  }                               | C = C_1 = __decorate([dec], C);
78138             //                                  | export default C;
78139             //                                  | var C_1;
78140             //  ---------------------------------------------------------------------
78141             //
78142             var location = ts.moveRangePastDecorators(node);
78143             var classAlias = getClassAliasIfNeeded(node);
78144             var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78145             //  ... = class ${name} ${heritageClauses} {
78146             //      ${members}
78147             //  }
78148             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
78149             var members = transformClassMembers(node);
78150             var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
78151             ts.aggregateTransformFlags(classExpression);
78152             ts.setOriginalNode(classExpression, node);
78153             ts.setTextRange(classExpression, location);
78154             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
78155             //                                         or decoratedClassAlias if the class contain self-reference.
78156             var statement = ts.createVariableStatement(
78157             /*modifiers*/ undefined, ts.createVariableDeclarationList([
78158                 ts.createVariableDeclaration(declName, 
78159                 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
78160             ], 1 /* Let */));
78161             ts.setOriginalNode(statement, node);
78162             ts.setTextRange(statement, location);
78163             ts.setCommentRange(statement, node);
78164             return statement;
78165         }
78166         function visitClassExpression(node) {
78167             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
78168                 return ts.visitEachChild(node, visitor, context);
78169             }
78170             var classExpression = ts.createClassExpression(
78171             /*modifiers*/ undefined, node.name, 
78172             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
78173             ts.aggregateTransformFlags(classExpression);
78174             ts.setOriginalNode(classExpression, node);
78175             ts.setTextRange(classExpression, node);
78176             return classExpression;
78177         }
78178         /**
78179          * Transforms the members of a class.
78180          *
78181          * @param node The current class.
78182          */
78183         function transformClassMembers(node) {
78184             var members = [];
78185             var constructor = ts.getFirstConstructorWithBody(node);
78186             var parametersWithPropertyAssignments = constructor &&
78187                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78188             if (parametersWithPropertyAssignments) {
78189                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
78190                     var parameter = parametersWithPropertyAssignments_1[_i];
78191                     if (ts.isIdentifier(parameter.name)) {
78192                         members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
78193                         /*decorators*/ undefined, 
78194                         /*modifiers*/ undefined, parameter.name, 
78195                         /*questionOrExclamationToken*/ undefined, 
78196                         /*type*/ undefined, 
78197                         /*initializer*/ undefined)), parameter));
78198                     }
78199                 }
78200             }
78201             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
78202             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
78203         }
78204         /**
78205          * Gets either the static or instance members of a class that are decorated, or have
78206          * parameters that are decorated.
78207          *
78208          * @param node The class containing the member.
78209          * @param isStatic A value indicating whether to retrieve static or instance members of
78210          *                 the class.
78211          */
78212         function getDecoratedClassElements(node, isStatic) {
78213             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
78214         }
78215         /**
78216          * Determines whether a class member is a static member of a class that is decorated, or
78217          * has parameters that are decorated.
78218          *
78219          * @param member The class member.
78220          */
78221         function isStaticDecoratedClassElement(member, parent) {
78222             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
78223         }
78224         /**
78225          * Determines whether a class member is an instance member of a class that is decorated,
78226          * or has parameters that are decorated.
78227          *
78228          * @param member The class member.
78229          */
78230         function isInstanceDecoratedClassElement(member, parent) {
78231             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
78232         }
78233         /**
78234          * Determines whether a class member is either a static or an instance member of a class
78235          * that is decorated, or has parameters that are decorated.
78236          *
78237          * @param member The class member.
78238          */
78239         function isDecoratedClassElement(member, isStatic, parent) {
78240             return ts.nodeOrChildIsDecorated(member, parent)
78241                 && isStatic === ts.hasModifier(member, 32 /* Static */);
78242         }
78243         /**
78244          * Gets an array of arrays of decorators for the parameters of a function-like node.
78245          * The offset into the result array should correspond to the offset of the parameter.
78246          *
78247          * @param node The function-like node.
78248          */
78249         function getDecoratorsOfParameters(node) {
78250             var decorators;
78251             if (node) {
78252                 var parameters = node.parameters;
78253                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
78254                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
78255                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
78256                 for (var i = 0; i < numParameters; i++) {
78257                     var parameter = parameters[i + firstParameterOffset];
78258                     if (decorators || parameter.decorators) {
78259                         if (!decorators) {
78260                             decorators = new Array(numParameters);
78261                         }
78262                         decorators[i] = parameter.decorators;
78263                     }
78264                 }
78265             }
78266             return decorators;
78267         }
78268         /**
78269          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
78270          * parameters of the constructor of the class.
78271          *
78272          * @param node The class node.
78273          */
78274         function getAllDecoratorsOfConstructor(node) {
78275             var decorators = node.decorators;
78276             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
78277             if (!decorators && !parameters) {
78278                 return undefined;
78279             }
78280             return {
78281                 decorators: decorators,
78282                 parameters: parameters
78283             };
78284         }
78285         /**
78286          * Gets an AllDecorators object containing the decorators for the member and its parameters.
78287          *
78288          * @param node The class node that contains the member.
78289          * @param member The class member.
78290          */
78291         function getAllDecoratorsOfClassElement(node, member) {
78292             switch (member.kind) {
78293                 case 163 /* GetAccessor */:
78294                 case 164 /* SetAccessor */:
78295                     return getAllDecoratorsOfAccessors(node, member);
78296                 case 161 /* MethodDeclaration */:
78297                     return getAllDecoratorsOfMethod(member);
78298                 case 159 /* PropertyDeclaration */:
78299                     return getAllDecoratorsOfProperty(member);
78300                 default:
78301                     return undefined;
78302             }
78303         }
78304         /**
78305          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
78306          *
78307          * @param node The class node that contains the accessor.
78308          * @param accessor The class accessor member.
78309          */
78310         function getAllDecoratorsOfAccessors(node, accessor) {
78311             if (!accessor.body) {
78312                 return undefined;
78313             }
78314             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
78315             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
78316             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
78317                 return undefined;
78318             }
78319             var decorators = firstAccessorWithDecorators.decorators;
78320             var parameters = getDecoratorsOfParameters(setAccessor);
78321             if (!decorators && !parameters) {
78322                 return undefined;
78323             }
78324             return { decorators: decorators, parameters: parameters };
78325         }
78326         /**
78327          * Gets an AllDecorators object containing the decorators for the method and its parameters.
78328          *
78329          * @param method The class method member.
78330          */
78331         function getAllDecoratorsOfMethod(method) {
78332             if (!method.body) {
78333                 return undefined;
78334             }
78335             var decorators = method.decorators;
78336             var parameters = getDecoratorsOfParameters(method);
78337             if (!decorators && !parameters) {
78338                 return undefined;
78339             }
78340             return { decorators: decorators, parameters: parameters };
78341         }
78342         /**
78343          * Gets an AllDecorators object containing the decorators for the property.
78344          *
78345          * @param property The class property member.
78346          */
78347         function getAllDecoratorsOfProperty(property) {
78348             var decorators = property.decorators;
78349             if (!decorators) {
78350                 return undefined;
78351             }
78352             return { decorators: decorators };
78353         }
78354         /**
78355          * Transforms all of the decorators for a declaration into an array of expressions.
78356          *
78357          * @param node The declaration node.
78358          * @param allDecorators An object containing all of the decorators for the declaration.
78359          */
78360         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
78361             if (!allDecorators) {
78362                 return undefined;
78363             }
78364             var decoratorExpressions = [];
78365             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
78366             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
78367             addTypeMetadata(node, container, decoratorExpressions);
78368             return decoratorExpressions;
78369         }
78370         /**
78371          * Generates statements used to apply decorators to either the static or instance members
78372          * of a class.
78373          *
78374          * @param node The class node.
78375          * @param isStatic A value indicating whether to generate statements for static or
78376          *                 instance members.
78377          */
78378         function addClassElementDecorationStatements(statements, node, isStatic) {
78379             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
78380         }
78381         /**
78382          * Generates expressions used to apply decorators to either the static or instance members
78383          * of a class.
78384          *
78385          * @param node The class node.
78386          * @param isStatic A value indicating whether to generate expressions for static or
78387          *                 instance members.
78388          */
78389         function generateClassElementDecorationExpressions(node, isStatic) {
78390             var members = getDecoratedClassElements(node, isStatic);
78391             var expressions;
78392             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
78393                 var member = members_6[_i];
78394                 var expression = generateClassElementDecorationExpression(node, member);
78395                 if (expression) {
78396                     if (!expressions) {
78397                         expressions = [expression];
78398                     }
78399                     else {
78400                         expressions.push(expression);
78401                     }
78402                 }
78403             }
78404             return expressions;
78405         }
78406         /**
78407          * Generates an expression used to evaluate class element decorators at runtime.
78408          *
78409          * @param node The class node that contains the member.
78410          * @param member The class member.
78411          */
78412         function generateClassElementDecorationExpression(node, member) {
78413             var allDecorators = getAllDecoratorsOfClassElement(node, member);
78414             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
78415             if (!decoratorExpressions) {
78416                 return undefined;
78417             }
78418             // Emit the call to __decorate. Given the following:
78419             //
78420             //   class C {
78421             //     @dec method(@dec2 x) {}
78422             //     @dec get accessor() {}
78423             //     @dec prop;
78424             //   }
78425             //
78426             // The emit for a method is:
78427             //
78428             //   __decorate([
78429             //       dec,
78430             //       __param(0, dec2),
78431             //       __metadata("design:type", Function),
78432             //       __metadata("design:paramtypes", [Object]),
78433             //       __metadata("design:returntype", void 0)
78434             //   ], C.prototype, "method", null);
78435             //
78436             // The emit for an accessor is:
78437             //
78438             //   __decorate([
78439             //       dec
78440             //   ], C.prototype, "accessor", null);
78441             //
78442             // The emit for a property is:
78443             //
78444             //   __decorate([
78445             //       dec
78446             //   ], C.prototype, "prop");
78447             //
78448             var prefix = getClassMemberPrefix(node, member);
78449             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
78450             var descriptor = languageVersion > 0 /* ES3 */
78451                 ? member.kind === 159 /* PropertyDeclaration */
78452                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
78453                     // should not invoke `Object.getOwnPropertyDescriptor`.
78454                     ? ts.createVoidZero()
78455                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
78456                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
78457                     : ts.createNull()
78458                 : undefined;
78459             var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
78460             ts.setEmitFlags(helper, 1536 /* NoComments */);
78461             return helper;
78462         }
78463         /**
78464          * Generates a __decorate helper call for a class constructor.
78465          *
78466          * @param node The class node.
78467          */
78468         function addConstructorDecorationStatement(statements, node) {
78469             var expression = generateConstructorDecorationExpression(node);
78470             if (expression) {
78471                 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
78472             }
78473         }
78474         /**
78475          * Generates a __decorate helper call for a class constructor.
78476          *
78477          * @param node The class node.
78478          */
78479         function generateConstructorDecorationExpression(node) {
78480             var allDecorators = getAllDecoratorsOfConstructor(node);
78481             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
78482             if (!decoratorExpressions) {
78483                 return undefined;
78484             }
78485             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
78486             var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78487             var decorate = createDecorateHelper(context, decoratorExpressions, localName);
78488             var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
78489             ts.setEmitFlags(expression, 1536 /* NoComments */);
78490             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
78491             return expression;
78492         }
78493         /**
78494          * Transforms a decorator into an expression.
78495          *
78496          * @param decorator The decorator node.
78497          */
78498         function transformDecorator(decorator) {
78499             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
78500         }
78501         /**
78502          * Transforms the decorators of a parameter.
78503          *
78504          * @param decorators The decorators for the parameter at the provided offset.
78505          * @param parameterOffset The offset of the parameter.
78506          */
78507         function transformDecoratorsOfParameter(decorators, parameterOffset) {
78508             var expressions;
78509             if (decorators) {
78510                 expressions = [];
78511                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
78512                     var decorator = decorators_1[_i];
78513                     var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
78514                     /*location*/ decorator.expression);
78515                     ts.setEmitFlags(helper, 1536 /* NoComments */);
78516                     expressions.push(helper);
78517                 }
78518             }
78519             return expressions;
78520         }
78521         /**
78522          * Adds optional type metadata for a declaration.
78523          *
78524          * @param node The declaration node.
78525          * @param decoratorExpressions The destination array to which to add new decorator expressions.
78526          */
78527         function addTypeMetadata(node, container, decoratorExpressions) {
78528             if (USE_NEW_TYPE_METADATA_FORMAT) {
78529                 addNewTypeMetadata(node, container, decoratorExpressions);
78530             }
78531             else {
78532                 addOldTypeMetadata(node, container, decoratorExpressions);
78533             }
78534         }
78535         function addOldTypeMetadata(node, container, decoratorExpressions) {
78536             if (compilerOptions.emitDecoratorMetadata) {
78537                 if (shouldAddTypeMetadata(node)) {
78538                     decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
78539                 }
78540                 if (shouldAddParamTypesMetadata(node)) {
78541                     decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
78542                 }
78543                 if (shouldAddReturnTypeMetadata(node)) {
78544                     decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
78545                 }
78546             }
78547         }
78548         function addNewTypeMetadata(node, container, decoratorExpressions) {
78549             if (compilerOptions.emitDecoratorMetadata) {
78550                 var properties = void 0;
78551                 if (shouldAddTypeMetadata(node)) {
78552                     (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
78553                 }
78554                 if (shouldAddParamTypesMetadata(node)) {
78555                     (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
78556                 }
78557                 if (shouldAddReturnTypeMetadata(node)) {
78558                     (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
78559                 }
78560                 if (properties) {
78561                     decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
78562                 }
78563             }
78564         }
78565         /**
78566          * Determines whether to emit the "design:type" metadata based on the node's kind.
78567          * The caller should have already tested whether the node has decorators and whether the
78568          * emitDecoratorMetadata compiler option is set.
78569          *
78570          * @param node The node to test.
78571          */
78572         function shouldAddTypeMetadata(node) {
78573             var kind = node.kind;
78574             return kind === 161 /* MethodDeclaration */
78575                 || kind === 163 /* GetAccessor */
78576                 || kind === 164 /* SetAccessor */
78577                 || kind === 159 /* PropertyDeclaration */;
78578         }
78579         /**
78580          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
78581          * The caller should have already tested whether the node has decorators and whether the
78582          * emitDecoratorMetadata compiler option is set.
78583          *
78584          * @param node The node to test.
78585          */
78586         function shouldAddReturnTypeMetadata(node) {
78587             return node.kind === 161 /* MethodDeclaration */;
78588         }
78589         /**
78590          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
78591          * The caller should have already tested whether the node has decorators and whether the
78592          * emitDecoratorMetadata compiler option is set.
78593          *
78594          * @param node The node to test.
78595          */
78596         function shouldAddParamTypesMetadata(node) {
78597             switch (node.kind) {
78598                 case 245 /* ClassDeclaration */:
78599                 case 214 /* ClassExpression */:
78600                     return ts.getFirstConstructorWithBody(node) !== undefined;
78601                 case 161 /* MethodDeclaration */:
78602                 case 163 /* GetAccessor */:
78603                 case 164 /* SetAccessor */:
78604                     return true;
78605             }
78606             return false;
78607         }
78608         function getAccessorTypeNode(node) {
78609             var accessors = resolver.getAllAccessorDeclarations(node);
78610             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
78611                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
78612         }
78613         /**
78614          * Serializes the type of a node for use with decorator type metadata.
78615          *
78616          * @param node The node that should have its type serialized.
78617          */
78618         function serializeTypeOfNode(node) {
78619             switch (node.kind) {
78620                 case 159 /* PropertyDeclaration */:
78621                 case 156 /* Parameter */:
78622                     return serializeTypeNode(node.type);
78623                 case 164 /* SetAccessor */:
78624                 case 163 /* GetAccessor */:
78625                     return serializeTypeNode(getAccessorTypeNode(node));
78626                 case 245 /* ClassDeclaration */:
78627                 case 214 /* ClassExpression */:
78628                 case 161 /* MethodDeclaration */:
78629                     return ts.createIdentifier("Function");
78630                 default:
78631                     return ts.createVoidZero();
78632             }
78633         }
78634         /**
78635          * Serializes the types of the parameters of a node for use with decorator type metadata.
78636          *
78637          * @param node The node that should have its parameter types serialized.
78638          */
78639         function serializeParameterTypesOfNode(node, container) {
78640             var valueDeclaration = ts.isClassLike(node)
78641                 ? ts.getFirstConstructorWithBody(node)
78642                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
78643                     ? node
78644                     : undefined;
78645             var expressions = [];
78646             if (valueDeclaration) {
78647                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
78648                 var numParameters = parameters.length;
78649                 for (var i = 0; i < numParameters; i++) {
78650                     var parameter = parameters[i];
78651                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
78652                         continue;
78653                     }
78654                     if (parameter.dotDotDotToken) {
78655                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
78656                     }
78657                     else {
78658                         expressions.push(serializeTypeOfNode(parameter));
78659                     }
78660                 }
78661             }
78662             return ts.createArrayLiteral(expressions);
78663         }
78664         function getParametersOfDecoratedDeclaration(node, container) {
78665             if (container && node.kind === 163 /* GetAccessor */) {
78666                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
78667                 if (setAccessor) {
78668                     return setAccessor.parameters;
78669                 }
78670             }
78671             return node.parameters;
78672         }
78673         /**
78674          * Serializes the return type of a node for use with decorator type metadata.
78675          *
78676          * @param node The node that should have its return type serialized.
78677          */
78678         function serializeReturnTypeOfNode(node) {
78679             if (ts.isFunctionLike(node) && node.type) {
78680                 return serializeTypeNode(node.type);
78681             }
78682             else if (ts.isAsyncFunction(node)) {
78683                 return ts.createIdentifier("Promise");
78684             }
78685             return ts.createVoidZero();
78686         }
78687         /**
78688          * Serializes a type node for use with decorator type metadata.
78689          *
78690          * Types are serialized in the following fashion:
78691          * - Void types point to "undefined" (e.g. "void 0")
78692          * - Function and Constructor types point to the global "Function" constructor.
78693          * - Interface types with a call or construct signature types point to the global
78694          *   "Function" constructor.
78695          * - Array and Tuple types point to the global "Array" constructor.
78696          * - Type predicates and booleans point to the global "Boolean" constructor.
78697          * - String literal types and strings point to the global "String" constructor.
78698          * - Enum and number types point to the global "Number" constructor.
78699          * - Symbol types point to the global "Symbol" constructor.
78700          * - Type references to classes (or class-like variables) point to the constructor for the class.
78701          * - Anything else points to the global "Object" constructor.
78702          *
78703          * @param node The type node to serialize.
78704          */
78705         function serializeTypeNode(node) {
78706             if (node === undefined) {
78707                 return ts.createIdentifier("Object");
78708             }
78709             switch (node.kind) {
78710                 case 110 /* VoidKeyword */:
78711                 case 146 /* UndefinedKeyword */:
78712                 case 100 /* NullKeyword */:
78713                 case 137 /* NeverKeyword */:
78714                     return ts.createVoidZero();
78715                 case 182 /* ParenthesizedType */:
78716                     return serializeTypeNode(node.type);
78717                 case 170 /* FunctionType */:
78718                 case 171 /* ConstructorType */:
78719                     return ts.createIdentifier("Function");
78720                 case 174 /* ArrayType */:
78721                 case 175 /* TupleType */:
78722                     return ts.createIdentifier("Array");
78723                 case 168 /* TypePredicate */:
78724                 case 128 /* BooleanKeyword */:
78725                     return ts.createIdentifier("Boolean");
78726                 case 143 /* StringKeyword */:
78727                     return ts.createIdentifier("String");
78728                 case 141 /* ObjectKeyword */:
78729                     return ts.createIdentifier("Object");
78730                 case 187 /* LiteralType */:
78731                     switch (node.literal.kind) {
78732                         case 10 /* StringLiteral */:
78733                             return ts.createIdentifier("String");
78734                         case 207 /* PrefixUnaryExpression */:
78735                         case 8 /* NumericLiteral */:
78736                             return ts.createIdentifier("Number");
78737                         case 9 /* BigIntLiteral */:
78738                             return getGlobalBigIntNameWithFallback();
78739                         case 106 /* TrueKeyword */:
78740                         case 91 /* FalseKeyword */:
78741                             return ts.createIdentifier("Boolean");
78742                         default:
78743                             return ts.Debug.failBadSyntaxKind(node.literal);
78744                     }
78745                 case 140 /* NumberKeyword */:
78746                     return ts.createIdentifier("Number");
78747                 case 151 /* BigIntKeyword */:
78748                     return getGlobalBigIntNameWithFallback();
78749                 case 144 /* SymbolKeyword */:
78750                     return languageVersion < 2 /* ES2015 */
78751                         ? getGlobalSymbolNameWithFallback()
78752                         : ts.createIdentifier("Symbol");
78753                 case 169 /* TypeReference */:
78754                     return serializeTypeReferenceNode(node);
78755                 case 179 /* IntersectionType */:
78756                 case 178 /* UnionType */:
78757                     return serializeTypeList(node.types);
78758                 case 180 /* ConditionalType */:
78759                     return serializeTypeList([node.trueType, node.falseType]);
78760                 case 184 /* TypeOperator */:
78761                     if (node.operator === 138 /* ReadonlyKeyword */) {
78762                         return serializeTypeNode(node.type);
78763                     }
78764                     break;
78765                 case 172 /* TypeQuery */:
78766                 case 185 /* IndexedAccessType */:
78767                 case 186 /* MappedType */:
78768                 case 173 /* TypeLiteral */:
78769                 case 125 /* AnyKeyword */:
78770                 case 148 /* UnknownKeyword */:
78771                 case 183 /* ThisType */:
78772                 case 188 /* ImportType */:
78773                     break;
78774                 // handle JSDoc types from an invalid parse
78775                 case 295 /* JSDocAllType */:
78776                 case 296 /* JSDocUnknownType */:
78777                 case 300 /* JSDocFunctionType */:
78778                 case 301 /* JSDocVariadicType */:
78779                 case 302 /* JSDocNamepathType */:
78780                     break;
78781                 case 297 /* JSDocNullableType */:
78782                 case 298 /* JSDocNonNullableType */:
78783                 case 299 /* JSDocOptionalType */:
78784                     return serializeTypeNode(node.type);
78785                 default:
78786                     return ts.Debug.failBadSyntaxKind(node);
78787             }
78788             return ts.createIdentifier("Object");
78789         }
78790         function serializeTypeList(types) {
78791             // Note when updating logic here also update getEntityNameForDecoratorMetadata
78792             // so that aliases can be marked as referenced
78793             var serializedUnion;
78794             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
78795                 var typeNode = types_21[_i];
78796                 while (typeNode.kind === 182 /* ParenthesizedType */) {
78797                     typeNode = typeNode.type; // Skip parens if need be
78798                 }
78799                 if (typeNode.kind === 137 /* NeverKeyword */) {
78800                     continue; // Always elide `never` from the union/intersection if possible
78801                 }
78802                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
78803                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
78804                 }
78805                 var serializedIndividual = serializeTypeNode(typeNode);
78806                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
78807                     // One of the individual is global object, return immediately
78808                     return serializedIndividual;
78809                 }
78810                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
78811                 // anything more complex and we will just default to Object
78812                 else if (serializedUnion) {
78813                     // Different types
78814                     if (!ts.isIdentifier(serializedUnion) ||
78815                         !ts.isIdentifier(serializedIndividual) ||
78816                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
78817                         return ts.createIdentifier("Object");
78818                     }
78819                 }
78820                 else {
78821                     // Initialize the union type
78822                     serializedUnion = serializedIndividual;
78823                 }
78824             }
78825             // If we were able to find common type, use it
78826             return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
78827         }
78828         /**
78829          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
78830          * decorator type metadata.
78831          *
78832          * @param node The type reference node.
78833          */
78834         function serializeTypeReferenceNode(node) {
78835             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
78836             switch (kind) {
78837                 case ts.TypeReferenceSerializationKind.Unknown:
78838                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
78839                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
78840                         return ts.createIdentifier("Object");
78841                     }
78842                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
78843                     var temp = ts.createTempVariable(hoistVariableDeclaration);
78844                     return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
78845                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
78846                     return serializeEntityNameAsExpression(node.typeName);
78847                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
78848                     return ts.createVoidZero();
78849                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
78850                     return getGlobalBigIntNameWithFallback();
78851                 case ts.TypeReferenceSerializationKind.BooleanType:
78852                     return ts.createIdentifier("Boolean");
78853                 case ts.TypeReferenceSerializationKind.NumberLikeType:
78854                     return ts.createIdentifier("Number");
78855                 case ts.TypeReferenceSerializationKind.StringLikeType:
78856                     return ts.createIdentifier("String");
78857                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
78858                     return ts.createIdentifier("Array");
78859                 case ts.TypeReferenceSerializationKind.ESSymbolType:
78860                     return languageVersion < 2 /* ES2015 */
78861                         ? getGlobalSymbolNameWithFallback()
78862                         : ts.createIdentifier("Symbol");
78863                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
78864                     return ts.createIdentifier("Function");
78865                 case ts.TypeReferenceSerializationKind.Promise:
78866                     return ts.createIdentifier("Promise");
78867                 case ts.TypeReferenceSerializationKind.ObjectType:
78868                     return ts.createIdentifier("Object");
78869                 default:
78870                     return ts.Debug.assertNever(kind);
78871             }
78872         }
78873         function createCheckedValue(left, right) {
78874             return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
78875         }
78876         /**
78877          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
78878          *
78879          * @param node The entity name to serialize.
78880          */
78881         function serializeEntityNameAsExpressionFallback(node) {
78882             if (node.kind === 75 /* Identifier */) {
78883                 // A -> typeof A !== undefined && A
78884                 var copied = serializeEntityNameAsExpression(node);
78885                 return createCheckedValue(copied, copied);
78886             }
78887             if (node.left.kind === 75 /* Identifier */) {
78888                 // A.B -> typeof A !== undefined && A.B
78889                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
78890             }
78891             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
78892             var left = serializeEntityNameAsExpressionFallback(node.left);
78893             var temp = ts.createTempVariable(hoistVariableDeclaration);
78894             return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
78895         }
78896         /**
78897          * Serializes an entity name as an expression for decorator type metadata.
78898          *
78899          * @param node The entity name to serialize.
78900          */
78901         function serializeEntityNameAsExpression(node) {
78902             switch (node.kind) {
78903                 case 75 /* Identifier */:
78904                     // Create a clone of the name with a new parent, and treat it as if it were
78905                     // a source tree node for the purposes of the checker.
78906                     var name = ts.getMutableClone(node);
78907                     name.flags &= ~8 /* Synthesized */;
78908                     name.original = undefined;
78909                     name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
78910                     return name;
78911                 case 153 /* QualifiedName */:
78912                     return serializeQualifiedNameAsExpression(node);
78913             }
78914         }
78915         /**
78916          * Serializes an qualified name as an expression for decorator type metadata.
78917          *
78918          * @param node The qualified name to serialize.
78919          * @param useFallback A value indicating whether to use logical operators to test for the
78920          *                    qualified name at runtime.
78921          */
78922         function serializeQualifiedNameAsExpression(node) {
78923             return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
78924         }
78925         /**
78926          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
78927          * available.
78928          */
78929         function getGlobalSymbolNameWithFallback() {
78930             return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
78931         }
78932         /**
78933          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
78934          * available.
78935          */
78936         function getGlobalBigIntNameWithFallback() {
78937             return languageVersion < 99 /* ESNext */
78938                 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
78939                 : ts.createIdentifier("BigInt");
78940         }
78941         /**
78942          * Gets an expression that represents a property name (for decorated properties or enums).
78943          * For a computed property, a name is generated for the node.
78944          *
78945          * @param member The member whose name should be converted into an expression.
78946          */
78947         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
78948             var name = member.name;
78949             if (ts.isPrivateIdentifier(name)) {
78950                 return ts.createIdentifier("");
78951             }
78952             else if (ts.isComputedPropertyName(name)) {
78953                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
78954                     ? ts.getGeneratedNameForNode(name)
78955                     : name.expression;
78956             }
78957             else if (ts.isIdentifier(name)) {
78958                 return ts.createLiteral(ts.idText(name));
78959             }
78960             else {
78961                 return ts.getSynthesizedClone(name);
78962             }
78963         }
78964         /**
78965          * Visits the property name of a class element, for use when emitting property
78966          * initializers. For a computed property on a node with decorators, a temporary
78967          * value is stored for later use.
78968          *
78969          * @param member The member whose name should be visited.
78970          */
78971         function visitPropertyNameOfClassElement(member) {
78972             var name = member.name;
78973             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
78974             // The names are used more than once when:
78975             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
78976             //   - the property has a decorator.
78977             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
78978                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
78979                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
78980                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
78981                     var generatedName = ts.getGeneratedNameForNode(name);
78982                     hoistVariableDeclaration(generatedName);
78983                     return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
78984                 }
78985             }
78986             return ts.visitNode(name, visitor, ts.isPropertyName);
78987         }
78988         /**
78989          * Transforms a HeritageClause with TypeScript syntax.
78990          *
78991          * This function will only be called when one of the following conditions are met:
78992          * - The node is a non-`extends` heritage clause that should be elided.
78993          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
78994          *
78995          * @param node The HeritageClause to transform.
78996          */
78997         function visitHeritageClause(node) {
78998             if (node.token === 113 /* ImplementsKeyword */) {
78999                 // implements clauses are elided
79000                 return undefined;
79001             }
79002             return ts.visitEachChild(node, visitor, context);
79003         }
79004         /**
79005          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
79006          *
79007          * This function will only be called when one of the following conditions are met:
79008          * - The node contains type arguments that should be elided.
79009          *
79010          * @param node The ExpressionWithTypeArguments to transform.
79011          */
79012         function visitExpressionWithTypeArguments(node) {
79013             return ts.updateExpressionWithTypeArguments(node, 
79014             /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
79015         }
79016         /**
79017          * Determines whether to emit a function-like declaration. We should not emit the
79018          * declaration if it does not have a body.
79019          *
79020          * @param node The declaration node.
79021          */
79022         function shouldEmitFunctionLikeDeclaration(node) {
79023             return !ts.nodeIsMissing(node.body);
79024         }
79025         function visitPropertyDeclaration(node) {
79026             if (node.flags & 8388608 /* Ambient */) {
79027                 return undefined;
79028             }
79029             var updated = ts.updateProperty(node, 
79030             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
79031             /*questionOrExclamationToken*/ undefined, 
79032             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
79033             if (updated !== node) {
79034                 // While we emit the source map for the node after skipping decorators and modifiers,
79035                 // we need to emit the comments for the original range.
79036                 ts.setCommentRange(updated, node);
79037                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
79038             }
79039             return updated;
79040         }
79041         function visitConstructor(node) {
79042             if (!shouldEmitFunctionLikeDeclaration(node)) {
79043                 return undefined;
79044             }
79045             return ts.updateConstructor(node, 
79046             /*decorators*/ undefined, 
79047             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
79048         }
79049         function transformConstructorBody(body, constructor) {
79050             var parametersWithPropertyAssignments = constructor &&
79051                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
79052             if (!ts.some(parametersWithPropertyAssignments)) {
79053                 return ts.visitFunctionBody(body, visitor, context);
79054             }
79055             var statements = [];
79056             var indexOfFirstStatement = 0;
79057             resumeLexicalEnvironment();
79058             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
79059             // Add parameters with property assignments. Transforms this:
79060             //
79061             //  constructor (public x, public y) {
79062             //  }
79063             //
79064             // Into this:
79065             //
79066             //  constructor (x, y) {
79067             //      this.x = x;
79068             //      this.y = y;
79069             //  }
79070             //
79071             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
79072             // Add the existing statements, skipping the initial super call.
79073             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
79074             // End the lexical environment.
79075             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
79076             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
79077             ts.setTextRange(block, /*location*/ body);
79078             ts.setOriginalNode(block, body);
79079             return block;
79080         }
79081         /**
79082          * Transforms a parameter into a property assignment statement.
79083          *
79084          * @param node The parameter declaration.
79085          */
79086         function transformParameterWithPropertyAssignment(node) {
79087             var name = node.name;
79088             if (!ts.isIdentifier(name)) {
79089                 return undefined;
79090             }
79091             var propertyName = ts.getMutableClone(name);
79092             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
79093             var localName = ts.getMutableClone(name);
79094             ts.setEmitFlags(localName, 1536 /* NoComments */);
79095             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))));
79096         }
79097         function visitMethodDeclaration(node) {
79098             if (!shouldEmitFunctionLikeDeclaration(node)) {
79099                 return undefined;
79100             }
79101             var updated = ts.updateMethod(node, 
79102             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
79103             /*questionToken*/ undefined, 
79104             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79105             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
79106             if (updated !== node) {
79107                 // While we emit the source map for the node after skipping decorators and modifiers,
79108                 // we need to emit the comments for the original range.
79109                 ts.setCommentRange(updated, node);
79110                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
79111             }
79112             return updated;
79113         }
79114         /**
79115          * Determines whether to emit an accessor declaration. We should not emit the
79116          * declaration if it does not have a body and is abstract.
79117          *
79118          * @param node The declaration node.
79119          */
79120         function shouldEmitAccessorDeclaration(node) {
79121             return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
79122         }
79123         function visitGetAccessor(node) {
79124             if (!shouldEmitAccessorDeclaration(node)) {
79125                 return undefined;
79126             }
79127             var updated = ts.updateGetAccessor(node, 
79128             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
79129             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79130             if (updated !== node) {
79131                 // While we emit the source map for the node after skipping decorators and modifiers,
79132                 // we need to emit the comments for the original range.
79133                 ts.setCommentRange(updated, node);
79134                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
79135             }
79136             return updated;
79137         }
79138         function visitSetAccessor(node) {
79139             if (!shouldEmitAccessorDeclaration(node)) {
79140                 return undefined;
79141             }
79142             var updated = ts.updateSetAccessor(node, 
79143             /*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([]));
79144             if (updated !== node) {
79145                 // While we emit the source map for the node after skipping decorators and modifiers,
79146                 // we need to emit the comments for the original range.
79147                 ts.setCommentRange(updated, node);
79148                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
79149             }
79150             return updated;
79151         }
79152         function visitFunctionDeclaration(node) {
79153             if (!shouldEmitFunctionLikeDeclaration(node)) {
79154                 return ts.createNotEmittedStatement(node);
79155             }
79156             var updated = ts.updateFunctionDeclaration(node, 
79157             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79158             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79159             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79160             if (isExportOfNamespace(node)) {
79161                 var statements = [updated];
79162                 addExportMemberAssignment(statements, node);
79163                 return statements;
79164             }
79165             return updated;
79166         }
79167         function visitFunctionExpression(node) {
79168             if (!shouldEmitFunctionLikeDeclaration(node)) {
79169                 return ts.createOmittedExpression();
79170             }
79171             var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79172             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79173             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79174             return updated;
79175         }
79176         function visitArrowFunction(node) {
79177             var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
79178             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79179             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
79180             return updated;
79181         }
79182         function visitParameter(node) {
79183             if (ts.parameterIsThisKeyword(node)) {
79184                 return undefined;
79185             }
79186             var updated = ts.updateParameter(node, 
79187             /*decorators*/ undefined, 
79188             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
79189             /*questionToken*/ undefined, 
79190             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79191             if (updated !== node) {
79192                 // While we emit the source map for the node after skipping decorators and modifiers,
79193                 // we need to emit the comments for the original range.
79194                 ts.setCommentRange(updated, node);
79195                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
79196                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
79197                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
79198             }
79199             return updated;
79200         }
79201         function visitVariableStatement(node) {
79202             if (isExportOfNamespace(node)) {
79203                 var variables = ts.getInitializedVariables(node.declarationList);
79204                 if (variables.length === 0) {
79205                     // elide statement if there are no initialized variables.
79206                     return undefined;
79207                 }
79208                 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
79209             }
79210             else {
79211                 return ts.visitEachChild(node, visitor, context);
79212             }
79213         }
79214         function transformInitializedVariable(node) {
79215             var name = node.name;
79216             if (ts.isBindingPattern(name)) {
79217                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
79218                 /*needsValue*/ false, createNamespaceExportExpression);
79219             }
79220             else {
79221                 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
79222                 /*location*/ node);
79223             }
79224         }
79225         function visitVariableDeclaration(node) {
79226             return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
79227             /*exclaimationToken*/ undefined, 
79228             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79229         }
79230         function visitParenthesizedExpression(node) {
79231             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
79232             if (ts.isAssertionExpression(innerExpression)) {
79233                 // Make sure we consider all nested cast expressions, e.g.:
79234                 // (<any><number><any>-A).x;
79235                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79236                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
79237                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
79238                 // the parentheses, however, could cause change in the semantics of the generated
79239                 // code if the casted expression has a lower precedence than the rest of the
79240                 // expression.
79241                 //
79242                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
79243                 // preserve the position information of the original expression.
79244                 //
79245                 // Due to the auto-parenthesization rules used by the visitor and factory functions
79246                 // we can safely elide the parentheses here, as a new synthetic
79247                 // ParenthesizedExpression will be inserted if we remove parentheses too
79248                 // aggressively.
79249                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
79250                 // correctly for return and throw, we must keep the parenthesis
79251                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
79252                     return ts.updateParen(node, expression);
79253                 }
79254                 return ts.createPartiallyEmittedExpression(expression, node);
79255             }
79256             return ts.visitEachChild(node, visitor, context);
79257         }
79258         function visitAssertionExpression(node) {
79259             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79260             return ts.createPartiallyEmittedExpression(expression, node);
79261         }
79262         function visitNonNullExpression(node) {
79263             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
79264             return ts.createPartiallyEmittedExpression(expression, node);
79265         }
79266         function visitCallExpression(node) {
79267             return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79268             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79269         }
79270         function visitNewExpression(node) {
79271             return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79272             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79273         }
79274         function visitTaggedTemplateExpression(node) {
79275             return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
79276             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
79277         }
79278         function visitJsxSelfClosingElement(node) {
79279             return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79280             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79281         }
79282         function visitJsxJsxOpeningElement(node) {
79283             return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79284             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79285         }
79286         /**
79287          * Determines whether to emit an enum declaration.
79288          *
79289          * @param node The enum declaration node.
79290          */
79291         function shouldEmitEnumDeclaration(node) {
79292             return !ts.isEnumConst(node)
79293                 || compilerOptions.preserveConstEnums
79294                 || compilerOptions.isolatedModules;
79295         }
79296         /**
79297          * Visits an enum declaration.
79298          *
79299          * This function will be called any time a TypeScript enum is encountered.
79300          *
79301          * @param node The enum declaration node.
79302          */
79303         function visitEnumDeclaration(node) {
79304             if (!shouldEmitEnumDeclaration(node)) {
79305                 return ts.createNotEmittedStatement(node);
79306             }
79307             var statements = [];
79308             // We request to be advised when the printer is about to print this node. This allows
79309             // us to set up the correct state for later substitutions.
79310             var emitFlags = 2 /* AdviseOnEmitNode */;
79311             // If needed, we should emit a variable declaration for the enum. If we emit
79312             // a leading variable declaration, we should not emit leading comments for the
79313             // enum body.
79314             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79315             if (varAdded) {
79316                 // We should still emit the comments if we are emitting a system module.
79317                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79318                     emitFlags |= 512 /* NoLeadingComments */;
79319                 }
79320             }
79321             // `parameterName` is the declaration name used inside of the enum.
79322             var parameterName = getNamespaceParameterName(node);
79323             // `containerName` is the expression used inside of the enum for assignments.
79324             var containerName = getNamespaceContainerName(node);
79325             // `exportName` is the expression used within this node's container for any exported references.
79326             var exportName = ts.hasModifier(node, 1 /* Export */)
79327                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79328                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79329             //  x || (x = {})
79330             //  exports.x || (exports.x = {})
79331             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79332             if (hasNamespaceQualifiedExportName(node)) {
79333                 // `localName` is the expression used within this node's containing scope for any local references.
79334                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79335                 //  x = (exports.x || (exports.x = {}))
79336                 moduleArg = ts.createAssignment(localName, moduleArg);
79337             }
79338             //  (function (x) {
79339             //      x[x["y"] = 0] = "y";
79340             //      ...
79341             //  })(x || (x = {}));
79342             var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79343             /*modifiers*/ undefined, 
79344             /*asteriskToken*/ undefined, 
79345             /*name*/ undefined, 
79346             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79347             /*type*/ undefined, transformEnumBody(node, containerName)), 
79348             /*typeArguments*/ undefined, [moduleArg]));
79349             ts.setOriginalNode(enumStatement, node);
79350             if (varAdded) {
79351                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79352                 ts.setSyntheticLeadingComments(enumStatement, undefined);
79353                 ts.setSyntheticTrailingComments(enumStatement, undefined);
79354             }
79355             ts.setTextRange(enumStatement, node);
79356             ts.addEmitFlags(enumStatement, emitFlags);
79357             statements.push(enumStatement);
79358             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
79359             // the end of the declaration.
79360             statements.push(ts.createEndOfDeclarationMarker(node));
79361             return statements;
79362         }
79363         /**
79364          * Transforms the body of an enum declaration.
79365          *
79366          * @param node The enum declaration node.
79367          */
79368         function transformEnumBody(node, localName) {
79369             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
79370             currentNamespaceContainerName = localName;
79371             var statements = [];
79372             startLexicalEnvironment();
79373             var members = ts.map(node.members, transformEnumMember);
79374             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79375             ts.addRange(statements, members);
79376             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
79377             return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
79378             /*multiLine*/ true);
79379         }
79380         /**
79381          * Transforms an enum member into a statement.
79382          *
79383          * @param member The enum member node.
79384          */
79385         function transformEnumMember(member) {
79386             // enums don't support computed properties
79387             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
79388             // old emitter always generate 'expression' part of the name as-is.
79389             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
79390             var valueExpression = transformEnumMemberDeclarationValue(member);
79391             var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
79392             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
79393                 innerAssignment :
79394                 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
79395             return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
79396         }
79397         /**
79398          * Transforms the value of an enum member.
79399          *
79400          * @param member The enum member node.
79401          */
79402         function transformEnumMemberDeclarationValue(member) {
79403             var value = resolver.getConstantValue(member);
79404             if (value !== undefined) {
79405                 return ts.createLiteral(value);
79406             }
79407             else {
79408                 enableSubstitutionForNonQualifiedEnumMembers();
79409                 if (member.initializer) {
79410                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
79411                 }
79412                 else {
79413                     return ts.createVoidZero();
79414                 }
79415             }
79416         }
79417         /**
79418          * Determines whether to elide a module declaration.
79419          *
79420          * @param node The module declaration node.
79421          */
79422         function shouldEmitModuleDeclaration(nodeIn) {
79423             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
79424             if (!node) {
79425                 // If we can't find a parse tree node, assume the node is instantiated.
79426                 return true;
79427             }
79428             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
79429         }
79430         /**
79431          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
79432          * or `exports.x`).
79433          */
79434         function hasNamespaceQualifiedExportName(node) {
79435             return isExportOfNamespace(node)
79436                 || (isExternalModuleExport(node)
79437                     && moduleKind !== ts.ModuleKind.ES2015
79438                     && moduleKind !== ts.ModuleKind.ES2020
79439                     && moduleKind !== ts.ModuleKind.ESNext
79440                     && moduleKind !== ts.ModuleKind.System);
79441         }
79442         /**
79443          * Records that a declaration was emitted in the current scope, if it was the first
79444          * declaration for the provided symbol.
79445          */
79446         function recordEmittedDeclarationInScope(node) {
79447             if (!currentScopeFirstDeclarationsOfName) {
79448                 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
79449             }
79450             var name = declaredNameInScope(node);
79451             if (!currentScopeFirstDeclarationsOfName.has(name)) {
79452                 currentScopeFirstDeclarationsOfName.set(name, node);
79453             }
79454         }
79455         /**
79456          * Determines whether a declaration is the first declaration with
79457          * the same name emitted in the current scope.
79458          */
79459         function isFirstEmittedDeclarationInScope(node) {
79460             if (currentScopeFirstDeclarationsOfName) {
79461                 var name = declaredNameInScope(node);
79462                 return currentScopeFirstDeclarationsOfName.get(name) === node;
79463             }
79464             return true;
79465         }
79466         function declaredNameInScope(node) {
79467             ts.Debug.assertNode(node.name, ts.isIdentifier);
79468             return node.name.escapedText;
79469         }
79470         /**
79471          * Adds a leading VariableStatement for a enum or module declaration.
79472          */
79473         function addVarForEnumOrModuleDeclaration(statements, node) {
79474             // Emit a variable statement for the module. We emit top-level enums as a `var`
79475             // declaration to avoid static errors in global scripts scripts due to redeclaration.
79476             // enums in any other scope are emitted as a `let` declaration.
79477             var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79478                 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
79479             ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
79480             ts.setOriginalNode(statement, node);
79481             recordEmittedDeclarationInScope(node);
79482             if (isFirstEmittedDeclarationInScope(node)) {
79483                 // Adjust the source map emit to match the old emitter.
79484                 if (node.kind === 248 /* EnumDeclaration */) {
79485                     ts.setSourceMapRange(statement.declarationList, node);
79486                 }
79487                 else {
79488                     ts.setSourceMapRange(statement, node);
79489                 }
79490                 // Trailing comments for module declaration should be emitted after the function closure
79491                 // instead of the variable statement:
79492                 //
79493                 //     /** Module comment*/
79494                 //     module m1 {
79495                 //         function foo4Export() {
79496                 //         }
79497                 //     } // trailing comment module
79498                 //
79499                 // Should emit:
79500                 //
79501                 //     /** Module comment*/
79502                 //     var m1;
79503                 //     (function (m1) {
79504                 //         function foo4Export() {
79505                 //         }
79506                 //     })(m1 || (m1 = {})); // trailing comment module
79507                 //
79508                 ts.setCommentRange(statement, node);
79509                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79510                 statements.push(statement);
79511                 return true;
79512             }
79513             else {
79514                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
79515                 // declaration we do not emit a leading variable declaration. To preserve the
79516                 // begin/end semantics of the declararation and to properly handle exports
79517                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
79518                 var mergeMarker = ts.createMergeDeclarationMarker(statement);
79519                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79520                 statements.push(mergeMarker);
79521                 return false;
79522             }
79523         }
79524         /**
79525          * Visits a module declaration node.
79526          *
79527          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
79528          *
79529          * @param node The module declaration node.
79530          */
79531         function visitModuleDeclaration(node) {
79532             if (!shouldEmitModuleDeclaration(node)) {
79533                 return ts.createNotEmittedStatement(node);
79534             }
79535             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
79536             enableSubstitutionForNamespaceExports();
79537             var statements = [];
79538             // We request to be advised when the printer is about to print this node. This allows
79539             // us to set up the correct state for later substitutions.
79540             var emitFlags = 2 /* AdviseOnEmitNode */;
79541             // If needed, we should emit a variable declaration for the module. If we emit
79542             // a leading variable declaration, we should not emit leading comments for the
79543             // module body.
79544             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79545             if (varAdded) {
79546                 // We should still emit the comments if we are emitting a system module.
79547                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79548                     emitFlags |= 512 /* NoLeadingComments */;
79549                 }
79550             }
79551             // `parameterName` is the declaration name used inside of the namespace.
79552             var parameterName = getNamespaceParameterName(node);
79553             // `containerName` is the expression used inside of the namespace for exports.
79554             var containerName = getNamespaceContainerName(node);
79555             // `exportName` is the expression used within this node's container for any exported references.
79556             var exportName = ts.hasModifier(node, 1 /* Export */)
79557                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79558                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79559             //  x || (x = {})
79560             //  exports.x || (exports.x = {})
79561             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79562             if (hasNamespaceQualifiedExportName(node)) {
79563                 // `localName` is the expression used within this node's containing scope for any local references.
79564                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79565                 //  x = (exports.x || (exports.x = {}))
79566                 moduleArg = ts.createAssignment(localName, moduleArg);
79567             }
79568             //  (function (x_1) {
79569             //      x_1.y = ...;
79570             //  })(x || (x = {}));
79571             var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79572             /*modifiers*/ undefined, 
79573             /*asteriskToken*/ undefined, 
79574             /*name*/ undefined, 
79575             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79576             /*type*/ undefined, transformModuleBody(node, containerName)), 
79577             /*typeArguments*/ undefined, [moduleArg]));
79578             ts.setOriginalNode(moduleStatement, node);
79579             if (varAdded) {
79580                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79581                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
79582                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
79583             }
79584             ts.setTextRange(moduleStatement, node);
79585             ts.addEmitFlags(moduleStatement, emitFlags);
79586             statements.push(moduleStatement);
79587             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
79588             // the end of the declaration.
79589             statements.push(ts.createEndOfDeclarationMarker(node));
79590             return statements;
79591         }
79592         /**
79593          * Transforms the body of a module declaration.
79594          *
79595          * @param node The module declaration node.
79596          */
79597         function transformModuleBody(node, namespaceLocalName) {
79598             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
79599             var savedCurrentNamespace = currentNamespace;
79600             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
79601             currentNamespaceContainerName = namespaceLocalName;
79602             currentNamespace = node;
79603             currentScopeFirstDeclarationsOfName = undefined;
79604             var statements = [];
79605             startLexicalEnvironment();
79606             var statementsLocation;
79607             var blockLocation;
79608             if (node.body) {
79609                 if (node.body.kind === 250 /* ModuleBlock */) {
79610                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
79611                     statementsLocation = node.body.statements;
79612                     blockLocation = node.body;
79613                 }
79614                 else {
79615                     var result = visitModuleDeclaration(node.body);
79616                     if (result) {
79617                         if (ts.isArray(result)) {
79618                             ts.addRange(statements, result);
79619                         }
79620                         else {
79621                             statements.push(result);
79622                         }
79623                     }
79624                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
79625                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
79626                 }
79627             }
79628             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79629             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
79630             currentNamespace = savedCurrentNamespace;
79631             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
79632             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
79633             /*location*/ statementsLocation), 
79634             /*multiLine*/ true);
79635             ts.setTextRange(block, blockLocation);
79636             // namespace hello.hi.world {
79637             //      function foo() {}
79638             //
79639             //      // TODO, blah
79640             // }
79641             //
79642             // should be emitted as
79643             //
79644             // var hello;
79645             // (function (hello) {
79646             //     var hi;
79647             //     (function (hi) {
79648             //         var world;
79649             //         (function (world) {
79650             //             function foo() { }
79651             //             // TODO, blah
79652             //         })(world = hi.world || (hi.world = {}));
79653             //     })(hi = hello.hi || (hello.hi = {}));
79654             // })(hello || (hello = {}));
79655             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
79656             if (!node.body || node.body.kind !== 250 /* ModuleBlock */) {
79657                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
79658             }
79659             return block;
79660         }
79661         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
79662             if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
79663                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
79664                 return recursiveInnerModule || moduleDeclaration.body;
79665             }
79666         }
79667         /**
79668          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
79669          *
79670          * @param node The import declaration node.
79671          */
79672         function visitImportDeclaration(node) {
79673             if (!node.importClause) {
79674                 // Do not elide a side-effect only import declaration.
79675                 //  import "foo";
79676                 return node;
79677             }
79678             if (node.importClause.isTypeOnly) {
79679                 // Always elide type-only imports
79680                 return undefined;
79681             }
79682             // Elide the declaration if the import clause was elided.
79683             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
79684             return importClause ||
79685                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
79686                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
79687                 ? ts.updateImportDeclaration(node, 
79688                 /*decorators*/ undefined, 
79689                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
79690                 : undefined;
79691         }
79692         /**
79693          * Visits an import clause, eliding it if it is not referenced.
79694          *
79695          * @param node The import clause node.
79696          */
79697         function visitImportClause(node) {
79698             if (node.isTypeOnly) {
79699                 return undefined;
79700             }
79701             // Elide the import clause if we elide both its name and its named bindings.
79702             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
79703             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
79704             return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
79705         }
79706         /**
79707          * Visits named import bindings, eliding it if it is not referenced.
79708          *
79709          * @param node The named import bindings node.
79710          */
79711         function visitNamedImportBindings(node) {
79712             if (node.kind === 256 /* NamespaceImport */) {
79713                 // Elide a namespace import if it is not referenced.
79714                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79715             }
79716             else {
79717                 // Elide named imports if all of its import specifiers are elided.
79718                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
79719                 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
79720             }
79721         }
79722         /**
79723          * Visits an import specifier, eliding it if it is not referenced.
79724          *
79725          * @param node The import specifier node.
79726          */
79727         function visitImportSpecifier(node) {
79728             // Elide an import specifier if it is not referenced.
79729             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79730         }
79731         /**
79732          * Visits an export assignment, eliding it if it does not contain a clause that resolves
79733          * to a value.
79734          *
79735          * @param node The export assignment node.
79736          */
79737         function visitExportAssignment(node) {
79738             // Elide the export assignment if it does not reference a value.
79739             return resolver.isValueAliasDeclaration(node)
79740                 ? ts.visitEachChild(node, visitor, context)
79741                 : undefined;
79742         }
79743         /**
79744          * Visits an export declaration, eliding it if it does not contain a clause that resolves
79745          * to a value.
79746          *
79747          * @param node The export declaration node.
79748          */
79749         function visitExportDeclaration(node) {
79750             if (node.isTypeOnly) {
79751                 return undefined;
79752             }
79753             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
79754                 // never elide `export <whatever> from <whereever>` declarations -
79755                 // they should be kept for sideffects/untyped exports, even when the
79756                 // type checker doesn't know about any exports
79757                 return node;
79758             }
79759             if (!resolver.isValueAliasDeclaration(node)) {
79760                 // Elide the export declaration if it does not export a value.
79761                 return undefined;
79762             }
79763             // Elide the export declaration if all of its named exports are elided.
79764             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
79765             return exportClause
79766                 ? ts.updateExportDeclaration(node, 
79767                 /*decorators*/ undefined, 
79768                 /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
79769                 : undefined;
79770         }
79771         /**
79772          * Visits named exports, eliding it if it does not contain an export specifier that
79773          * resolves to a value.
79774          *
79775          * @param node The named exports node.
79776          */
79777         function visitNamedExports(node) {
79778             // Elide the named exports if all of its export specifiers were elided.
79779             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
79780             return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
79781         }
79782         function visitNamespaceExports(node) {
79783             return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
79784         }
79785         function visitNamedExportBindings(node) {
79786             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
79787         }
79788         /**
79789          * Visits an export specifier, eliding it if it does not resolve to a value.
79790          *
79791          * @param node The export specifier node.
79792          */
79793         function visitExportSpecifier(node) {
79794             // Elide an export specifier if it does not reference a value.
79795             return resolver.isValueAliasDeclaration(node) ? node : undefined;
79796         }
79797         /**
79798          * Determines whether to emit an import equals declaration.
79799          *
79800          * @param node The import equals declaration node.
79801          */
79802         function shouldEmitImportEqualsDeclaration(node) {
79803             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
79804             // - current file is not external module
79805             // - import declaration is top level and target is value imported by entity name
79806             return resolver.isReferencedAliasDeclaration(node)
79807                 || (!ts.isExternalModule(currentSourceFile)
79808                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
79809         }
79810         /**
79811          * Visits an import equals declaration.
79812          *
79813          * @param node The import equals declaration node.
79814          */
79815         function visitImportEqualsDeclaration(node) {
79816             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
79817                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
79818                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
79819                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
79820                     return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
79821                     /*decorators*/ undefined, 
79822                     /*modifiers*/ undefined, 
79823                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
79824                 }
79825                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
79826             }
79827             if (!shouldEmitImportEqualsDeclaration(node)) {
79828                 return undefined;
79829             }
79830             var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
79831             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
79832             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
79833                 //  export var ${name} = ${moduleReference};
79834                 //  var ${name} = ${moduleReference};
79835                 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79836                     ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
79837                     /*type*/ undefined, moduleReference), node)
79838                 ])), node), node);
79839             }
79840             else {
79841                 // exports.${name} = ${moduleReference};
79842                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
79843             }
79844         }
79845         /**
79846          * Gets a value indicating whether the node is exported from a namespace.
79847          *
79848          * @param node The node to test.
79849          */
79850         function isExportOfNamespace(node) {
79851             return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
79852         }
79853         /**
79854          * Gets a value indicating whether the node is exported from an external module.
79855          *
79856          * @param node The node to test.
79857          */
79858         function isExternalModuleExport(node) {
79859             return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
79860         }
79861         /**
79862          * Gets a value indicating whether the node is a named export from an external module.
79863          *
79864          * @param node The node to test.
79865          */
79866         function isNamedExternalModuleExport(node) {
79867             return isExternalModuleExport(node)
79868                 && !ts.hasModifier(node, 512 /* Default */);
79869         }
79870         /**
79871          * Gets a value indicating whether the node is the default export of an external module.
79872          *
79873          * @param node The node to test.
79874          */
79875         function isDefaultExternalModuleExport(node) {
79876             return isExternalModuleExport(node)
79877                 && ts.hasModifier(node, 512 /* Default */);
79878         }
79879         /**
79880          * Creates a statement for the provided expression. This is used in calls to `map`.
79881          */
79882         function expressionToStatement(expression) {
79883             return ts.createExpressionStatement(expression);
79884         }
79885         function addExportMemberAssignment(statements, node) {
79886             var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
79887             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
79888             var statement = ts.createExpressionStatement(expression);
79889             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
79890             statements.push(statement);
79891         }
79892         function createNamespaceExport(exportName, exportValue, location) {
79893             return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
79894         }
79895         function createNamespaceExportExpression(exportName, exportValue, location) {
79896             return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
79897         }
79898         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
79899             return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
79900         }
79901         /**
79902          * Gets the declaration name used inside of a namespace or enum.
79903          */
79904         function getNamespaceParameterName(node) {
79905             var name = ts.getGeneratedNameForNode(node);
79906             ts.setSourceMapRange(name, node.name);
79907             return name;
79908         }
79909         /**
79910          * Gets the expression used to refer to a namespace or enum within the body
79911          * of its declaration.
79912          */
79913         function getNamespaceContainerName(node) {
79914             return ts.getGeneratedNameForNode(node);
79915         }
79916         /**
79917          * Gets a local alias for a class declaration if it is a decorated class with an internal
79918          * reference to the static side of the class. This is necessary to avoid issues with
79919          * double-binding semantics for the class name.
79920          */
79921         function getClassAliasIfNeeded(node) {
79922             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
79923                 enableSubstitutionForClassAliases();
79924                 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
79925                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
79926                 hoistVariableDeclaration(classAlias);
79927                 return classAlias;
79928             }
79929         }
79930         function getClassPrototype(node) {
79931             return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
79932         }
79933         function getClassMemberPrefix(node, member) {
79934             return ts.hasModifier(member, 32 /* Static */)
79935                 ? ts.getDeclarationName(node)
79936                 : getClassPrototype(node);
79937         }
79938         function enableSubstitutionForNonQualifiedEnumMembers() {
79939             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
79940                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79941                 context.enableSubstitution(75 /* Identifier */);
79942             }
79943         }
79944         function enableSubstitutionForClassAliases() {
79945             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
79946                 enabledSubstitutions |= 1 /* ClassAliases */;
79947                 // We need to enable substitutions for identifiers. This allows us to
79948                 // substitute class names inside of a class declaration.
79949                 context.enableSubstitution(75 /* Identifier */);
79950                 // Keep track of class aliases.
79951                 classAliases = [];
79952             }
79953         }
79954         function enableSubstitutionForNamespaceExports() {
79955             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
79956                 enabledSubstitutions |= 2 /* NamespaceExports */;
79957                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
79958                 // substitute the names of exported members of a namespace.
79959                 context.enableSubstitution(75 /* Identifier */);
79960                 context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
79961                 // We need to be notified when entering and exiting namespaces.
79962                 context.enableEmitNotification(249 /* ModuleDeclaration */);
79963             }
79964         }
79965         function isTransformedModuleDeclaration(node) {
79966             return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
79967         }
79968         function isTransformedEnumDeclaration(node) {
79969             return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
79970         }
79971         /**
79972          * Hook for node emit.
79973          *
79974          * @param hint A hint as to the intended usage of the node.
79975          * @param node The node to emit.
79976          * @param emit A callback used to emit the node in the printer.
79977          */
79978         function onEmitNode(hint, node, emitCallback) {
79979             var savedApplicableSubstitutions = applicableSubstitutions;
79980             var savedCurrentSourceFile = currentSourceFile;
79981             if (ts.isSourceFile(node)) {
79982                 currentSourceFile = node;
79983             }
79984             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
79985                 applicableSubstitutions |= 2 /* NamespaceExports */;
79986             }
79987             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
79988                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79989             }
79990             previousOnEmitNode(hint, node, emitCallback);
79991             applicableSubstitutions = savedApplicableSubstitutions;
79992             currentSourceFile = savedCurrentSourceFile;
79993         }
79994         /**
79995          * Hooks node substitutions.
79996          *
79997          * @param hint A hint as to the intended usage of the node.
79998          * @param node The node to substitute.
79999          */
80000         function onSubstituteNode(hint, node) {
80001             node = previousOnSubstituteNode(hint, node);
80002             if (hint === 1 /* Expression */) {
80003                 return substituteExpression(node);
80004             }
80005             else if (ts.isShorthandPropertyAssignment(node)) {
80006                 return substituteShorthandPropertyAssignment(node);
80007             }
80008             return node;
80009         }
80010         function substituteShorthandPropertyAssignment(node) {
80011             if (enabledSubstitutions & 2 /* NamespaceExports */) {
80012                 var name = node.name;
80013                 var exportedName = trySubstituteNamespaceExportedName(name);
80014                 if (exportedName) {
80015                     // A shorthand property with an assignment initializer is probably part of a
80016                     // destructuring assignment
80017                     if (node.objectAssignmentInitializer) {
80018                         var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
80019                         return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
80020                     }
80021                     return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
80022                 }
80023             }
80024             return node;
80025         }
80026         function substituteExpression(node) {
80027             switch (node.kind) {
80028                 case 75 /* Identifier */:
80029                     return substituteExpressionIdentifier(node);
80030                 case 194 /* PropertyAccessExpression */:
80031                     return substitutePropertyAccessExpression(node);
80032                 case 195 /* ElementAccessExpression */:
80033                     return substituteElementAccessExpression(node);
80034             }
80035             return node;
80036         }
80037         function substituteExpressionIdentifier(node) {
80038             return trySubstituteClassAlias(node)
80039                 || trySubstituteNamespaceExportedName(node)
80040                 || node;
80041         }
80042         function trySubstituteClassAlias(node) {
80043             if (enabledSubstitutions & 1 /* ClassAliases */) {
80044                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80045                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80046                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80047                     // behavior of class names in ES6.
80048                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80049                     // constructor references in static property initializers.
80050                     var declaration = resolver.getReferencedValueDeclaration(node);
80051                     if (declaration) {
80052                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80053                         if (classAlias) {
80054                             var clone_1 = ts.getSynthesizedClone(classAlias);
80055                             ts.setSourceMapRange(clone_1, node);
80056                             ts.setCommentRange(clone_1, node);
80057                             return clone_1;
80058                         }
80059                     }
80060                 }
80061             }
80062             return undefined;
80063         }
80064         function trySubstituteNamespaceExportedName(node) {
80065             // If this is explicitly a local name, do not substitute.
80066             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
80067                 // If we are nested within a namespace declaration, we may need to qualifiy
80068                 // an identifier that is exported from a merged namespace.
80069                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
80070                 if (container && container.kind !== 290 /* SourceFile */) {
80071                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
80072                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
80073                     if (substitute) {
80074                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
80075                         /*location*/ node);
80076                     }
80077                 }
80078             }
80079             return undefined;
80080         }
80081         function substitutePropertyAccessExpression(node) {
80082             return substituteConstantValue(node);
80083         }
80084         function substituteElementAccessExpression(node) {
80085             return substituteConstantValue(node);
80086         }
80087         function substituteConstantValue(node) {
80088             var constantValue = tryGetConstEnumValue(node);
80089             if (constantValue !== undefined) {
80090                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
80091                 ts.setConstantValue(node, constantValue);
80092                 var substitute = ts.createLiteral(constantValue);
80093                 if (!compilerOptions.removeComments) {
80094                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
80095                     var propertyName = ts.isPropertyAccessExpression(originalNode)
80096                         ? ts.declarationNameToString(originalNode.name)
80097                         : ts.getTextOfNode(originalNode.argumentExpression);
80098                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
80099                 }
80100                 return substitute;
80101             }
80102             return node;
80103         }
80104         function tryGetConstEnumValue(node) {
80105             if (compilerOptions.isolatedModules) {
80106                 return undefined;
80107             }
80108             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
80109         }
80110     }
80111     ts.transformTypeScript = transformTypeScript;
80112     function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
80113         var argumentsArray = [];
80114         argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
80115         argumentsArray.push(target);
80116         if (memberName) {
80117             argumentsArray.push(memberName);
80118             if (descriptor) {
80119                 argumentsArray.push(descriptor);
80120             }
80121         }
80122         context.requestEmitHelper(ts.decorateHelper);
80123         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"), 
80124         /*typeArguments*/ undefined, argumentsArray), location);
80125     }
80126     ts.decorateHelper = {
80127         name: "typescript:decorate",
80128         importName: "__decorate",
80129         scoped: false,
80130         priority: 2,
80131         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            };"
80132     };
80133     function createMetadataHelper(context, metadataKey, metadataValue) {
80134         context.requestEmitHelper(ts.metadataHelper);
80135         return ts.createCall(ts.getUnscopedHelperName("__metadata"), 
80136         /*typeArguments*/ undefined, [
80137             ts.createLiteral(metadataKey),
80138             metadataValue
80139         ]);
80140     }
80141     ts.metadataHelper = {
80142         name: "typescript:metadata",
80143         importName: "__metadata",
80144         scoped: false,
80145         priority: 3,
80146         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            };"
80147     };
80148     function createParamHelper(context, expression, parameterOffset, location) {
80149         context.requestEmitHelper(ts.paramHelper);
80150         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"), 
80151         /*typeArguments*/ undefined, [
80152             ts.createLiteral(parameterOffset),
80153             expression
80154         ]), location);
80155     }
80156     ts.paramHelper = {
80157         name: "typescript:param",
80158         importName: "__param",
80159         scoped: false,
80160         priority: 4,
80161         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
80162     };
80163 })(ts || (ts = {}));
80164 /*@internal*/
80165 var ts;
80166 (function (ts) {
80167     var ClassPropertySubstitutionFlags;
80168     (function (ClassPropertySubstitutionFlags) {
80169         /**
80170          * Enables substitutions for class expressions with static fields
80171          * which have initializers that reference the class name.
80172          */
80173         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
80174     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
80175     var PrivateIdentifierPlacement;
80176     (function (PrivateIdentifierPlacement) {
80177         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
80178     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
80179     /**
80180      * Transforms ECMAScript Class Syntax.
80181      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
80182      * For now, this transforms public field declarations using TypeScript class semantics,
80183      * where declarations are elided and initializers are transformed as assignments in the constructor.
80184      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
80185      */
80186     function transformClassFields(context) {
80187         var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
80188         var resolver = context.getEmitResolver();
80189         var compilerOptions = context.getCompilerOptions();
80190         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80191         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
80192         var previousOnSubstituteNode = context.onSubstituteNode;
80193         context.onSubstituteNode = onSubstituteNode;
80194         var enabledSubstitutions;
80195         var classAliases;
80196         /**
80197          * Tracks what computed name expressions originating from elided names must be inlined
80198          * at the next execution site, in document order
80199          */
80200         var pendingExpressions;
80201         /**
80202          * Tracks what computed name expression statements and static property initializers must be
80203          * emitted at the next execution site, in document order (for decorated classes).
80204          */
80205         var pendingStatements;
80206         var privateIdentifierEnvironmentStack = [];
80207         var currentPrivateIdentifierEnvironment;
80208         return ts.chainBundle(transformSourceFile);
80209         function transformSourceFile(node) {
80210             var options = context.getCompilerOptions();
80211             if (node.isDeclarationFile
80212                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
80213                 return node;
80214             }
80215             var visited = ts.visitEachChild(node, visitor, context);
80216             ts.addEmitHelpers(visited, context.readEmitHelpers());
80217             return visited;
80218         }
80219         function visitor(node) {
80220             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
80221                 return node;
80222             switch (node.kind) {
80223                 case 214 /* ClassExpression */:
80224                 case 245 /* ClassDeclaration */:
80225                     return visitClassLike(node);
80226                 case 159 /* PropertyDeclaration */:
80227                     return visitPropertyDeclaration(node);
80228                 case 225 /* VariableStatement */:
80229                     return visitVariableStatement(node);
80230                 case 154 /* ComputedPropertyName */:
80231                     return visitComputedPropertyName(node);
80232                 case 194 /* PropertyAccessExpression */:
80233                     return visitPropertyAccessExpression(node);
80234                 case 207 /* PrefixUnaryExpression */:
80235                     return visitPrefixUnaryExpression(node);
80236                 case 208 /* PostfixUnaryExpression */:
80237                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
80238                 case 196 /* CallExpression */:
80239                     return visitCallExpression(node);
80240                 case 209 /* BinaryExpression */:
80241                     return visitBinaryExpression(node);
80242                 case 76 /* PrivateIdentifier */:
80243                     return visitPrivateIdentifier(node);
80244                 case 226 /* ExpressionStatement */:
80245                     return visitExpressionStatement(node);
80246                 case 230 /* ForStatement */:
80247                     return visitForStatement(node);
80248                 case 198 /* TaggedTemplateExpression */:
80249                     return visitTaggedTemplateExpression(node);
80250             }
80251             return ts.visitEachChild(node, visitor, context);
80252         }
80253         function visitorDestructuringTarget(node) {
80254             switch (node.kind) {
80255                 case 193 /* ObjectLiteralExpression */:
80256                 case 192 /* ArrayLiteralExpression */:
80257                     return visitAssignmentPattern(node);
80258                 default:
80259                     return visitor(node);
80260             }
80261         }
80262         /**
80263          * If we visit a private name, this means it is an undeclared private name.
80264          * Replace it with an empty identifier to indicate a problem with the code.
80265          */
80266         function visitPrivateIdentifier(node) {
80267             if (!shouldTransformPrivateFields) {
80268                 return node;
80269             }
80270             return ts.setOriginalNode(ts.createIdentifier(""), node);
80271         }
80272         /**
80273          * Visits the members of a class that has fields.
80274          *
80275          * @param node The node to visit.
80276          */
80277         function classElementVisitor(node) {
80278             switch (node.kind) {
80279                 case 162 /* Constructor */:
80280                     // Constructors for classes using class fields are transformed in
80281                     // `visitClassDeclaration` or `visitClassExpression`.
80282                     return undefined;
80283                 case 163 /* GetAccessor */:
80284                 case 164 /* SetAccessor */:
80285                 case 161 /* MethodDeclaration */:
80286                     // Visit the name of the member (if it's a computed property name).
80287                     return ts.visitEachChild(node, classElementVisitor, context);
80288                 case 159 /* PropertyDeclaration */:
80289                     return visitPropertyDeclaration(node);
80290                 case 154 /* ComputedPropertyName */:
80291                     return visitComputedPropertyName(node);
80292                 case 222 /* SemicolonClassElement */:
80293                     return node;
80294                 default:
80295                     return visitor(node);
80296             }
80297         }
80298         function visitVariableStatement(node) {
80299             var savedPendingStatements = pendingStatements;
80300             pendingStatements = [];
80301             var visitedNode = ts.visitEachChild(node, visitor, context);
80302             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
80303                 visitedNode;
80304             pendingStatements = savedPendingStatements;
80305             return statement;
80306         }
80307         function visitComputedPropertyName(name) {
80308             var node = ts.visitEachChild(name, visitor, context);
80309             if (ts.some(pendingExpressions)) {
80310                 var expressions = pendingExpressions;
80311                 expressions.push(name.expression);
80312                 pendingExpressions = [];
80313                 node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
80314             }
80315             return node;
80316         }
80317         function visitPropertyDeclaration(node) {
80318             ts.Debug.assert(!ts.some(node.decorators));
80319             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80320                 // Initializer is elided as the field is initialized in transformConstructor.
80321                 return ts.updateProperty(node, 
80322                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
80323                 /*questionOrExclamationToken*/ undefined, 
80324                 /*type*/ undefined, 
80325                 /*initializer*/ undefined);
80326             }
80327             // Create a temporary variable to store a computed property name (if necessary).
80328             // If it's not inlineable, then we emit an expression after the class which assigns
80329             // the property name to the temporary variable.
80330             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
80331             if (expr && !ts.isSimpleInlineableExpression(expr)) {
80332                 (pendingExpressions || (pendingExpressions = [])).push(expr);
80333             }
80334             return undefined;
80335         }
80336         function createPrivateIdentifierAccess(info, receiver) {
80337             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80338             switch (info.placement) {
80339                 case 0 /* InstanceField */:
80340                     return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
80341                 default: return ts.Debug.fail("Unexpected private identifier placement");
80342             }
80343         }
80344         function visitPropertyAccessExpression(node) {
80345             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80346                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
80347                 if (privateIdentifierInfo) {
80348                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
80349                 }
80350             }
80351             return ts.visitEachChild(node, visitor, context);
80352         }
80353         function visitPrefixUnaryExpression(node) {
80354             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80355                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80356                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80357                     40 /* MinusToken */ : undefined;
80358                 var info = void 0;
80359                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80360                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80361                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80362                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80363                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
80364                 }
80365             }
80366             return ts.visitEachChild(node, visitor, context);
80367         }
80368         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
80369             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80370                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80371                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80372                     40 /* MinusToken */ : undefined;
80373                 var info = void 0;
80374                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80375                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80376                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80377                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80378                     // Create a temporary variable to store the value returned by the expression.
80379                     var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
80380                     return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
80381                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
80382                         returnValue
80383                     ])), node);
80384                 }
80385             }
80386             return ts.visitEachChild(node, visitor, context);
80387         }
80388         function visitForStatement(node) {
80389             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
80390                 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));
80391             }
80392             return ts.visitEachChild(node, visitor, context);
80393         }
80394         function visitExpressionStatement(node) {
80395             if (ts.isPostfixUnaryExpression(node.expression)) {
80396                 return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
80397             }
80398             return ts.visitEachChild(node, visitor, context);
80399         }
80400         function createCopiableReceiverExpr(receiver) {
80401             var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
80402             if (ts.isSimpleInlineableExpression(receiver)) {
80403                 return { readExpression: clone, initializeExpression: undefined };
80404             }
80405             var readExpression = ts.createTempVariable(hoistVariableDeclaration);
80406             var initializeExpression = ts.createAssignment(readExpression, clone);
80407             return { readExpression: readExpression, initializeExpression: initializeExpression };
80408         }
80409         function visitCallExpression(node) {
80410             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
80411                 // Transform call expressions of private names to properly bind the `this` parameter.
80412                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80413                 return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"), 
80414                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
80415             }
80416             return ts.visitEachChild(node, visitor, context);
80417         }
80418         function visitTaggedTemplateExpression(node) {
80419             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
80420                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
80421                 var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80422                 return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"), 
80423                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
80424             }
80425             return ts.visitEachChild(node, visitor, context);
80426         }
80427         function visitBinaryExpression(node) {
80428             if (shouldTransformPrivateFields) {
80429                 if (ts.isDestructuringAssignment(node)) {
80430                     var savedPendingExpressions = pendingExpressions;
80431                     pendingExpressions = undefined;
80432                     node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
80433                     var expr = ts.some(pendingExpressions) ?
80434                         ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
80435                         node;
80436                     pendingExpressions = savedPendingExpressions;
80437                     return expr;
80438                 }
80439                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
80440                     var info = accessPrivateIdentifier(node.left.name);
80441                     if (info) {
80442                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
80443                     }
80444                 }
80445             }
80446             return ts.visitEachChild(node, visitor, context);
80447         }
80448         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
80449             switch (info.placement) {
80450                 case 0 /* InstanceField */: {
80451                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
80452                 }
80453                 default: return ts.Debug.fail("Unexpected private identifier placement");
80454             }
80455         }
80456         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
80457             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80458             right = ts.visitNode(right, visitor, ts.isExpression);
80459             if (ts.isCompoundAssignment(operator)) {
80460                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80461                 return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
80462             }
80463             else {
80464                 return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
80465             }
80466         }
80467         /**
80468          * Set up the environment for a class.
80469          */
80470         function visitClassLike(node) {
80471             var savedPendingExpressions = pendingExpressions;
80472             pendingExpressions = undefined;
80473             if (shouldTransformPrivateFields) {
80474                 startPrivateIdentifierEnvironment();
80475             }
80476             var result = ts.isClassDeclaration(node) ?
80477                 visitClassDeclaration(node) :
80478                 visitClassExpression(node);
80479             if (shouldTransformPrivateFields) {
80480                 endPrivateIdentifierEnvironment();
80481             }
80482             pendingExpressions = savedPendingExpressions;
80483             return result;
80484         }
80485         function doesClassElementNeedTransform(node) {
80486             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
80487         }
80488         function visitClassDeclaration(node) {
80489             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80490                 return ts.visitEachChild(node, visitor, context);
80491             }
80492             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80493             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80494             var statements = [
80495                 ts.updateClassDeclaration(node, 
80496                 /*decorators*/ undefined, node.modifiers, node.name, 
80497                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
80498             ];
80499             // Write any pending expressions from elided or moved computed property names
80500             if (ts.some(pendingExpressions)) {
80501                 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80502             }
80503             // Emit static property assignment. Because classDeclaration is lexically evaluated,
80504             // it is safe to emit static property assignment after classDeclaration
80505             // From ES6 specification:
80506             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
80507             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
80508             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80509             if (ts.some(staticProperties)) {
80510                 addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
80511             }
80512             return statements;
80513         }
80514         function visitClassExpression(node) {
80515             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80516                 return ts.visitEachChild(node, visitor, context);
80517             }
80518             // If this class expression is a transformation of a decorated class declaration,
80519             // then we want to output the pendingExpressions as statements, not as inlined
80520             // expressions with the class statement.
80521             //
80522             // In this case, we use pendingStatements to produce the same output as the
80523             // class declaration transformation. The VariableStatement visitor will insert
80524             // these statements after the class expression variable statement.
80525             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
80526             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80527             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80528             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80529             var classExpression = ts.updateClassExpression(node, node.modifiers, node.name, 
80530             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
80531             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
80532                 if (isDecoratedClassDeclaration) {
80533                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
80534                     // Write any pending expressions from elided or moved computed property names
80535                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
80536                         pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80537                     }
80538                     if (pendingStatements && ts.some(staticProperties)) {
80539                         addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
80540                     }
80541                     return classExpression;
80542                 }
80543                 else {
80544                     var expressions = [];
80545                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
80546                     var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
80547                     if (isClassWithConstructorReference) {
80548                         // record an alias as the class name is not in scope for statics.
80549                         enableSubstitutionForClassAliases();
80550                         var alias = ts.getSynthesizedClone(temp);
80551                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
80552                         classAliases[ts.getOriginalNodeId(node)] = alias;
80553                     }
80554                     // To preserve the behavior of the old emitter, we explicitly indent
80555                     // the body of a class with static initializers.
80556                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
80557                     expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
80558                     // Add any pending expressions leftover from elided or relocated computed property names
80559                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
80560                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
80561                     expressions.push(ts.startOnNewLine(temp));
80562                     return ts.inlineExpressions(expressions);
80563                 }
80564             }
80565             return classExpression;
80566         }
80567         function transformClassMembers(node, isDerivedClass) {
80568             if (shouldTransformPrivateFields) {
80569                 // Declare private names.
80570                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80571                     var member = _a[_i];
80572                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
80573                         addPrivateIdentifierToEnvironment(member.name);
80574                     }
80575                 }
80576             }
80577             var members = [];
80578             var constructor = transformConstructor(node, isDerivedClass);
80579             if (constructor) {
80580                 members.push(constructor);
80581             }
80582             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80583             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
80584         }
80585         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
80586             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
80587                 return false;
80588             }
80589             if (context.getCompilerOptions().useDefineForClassFields) {
80590                 // If we are using define semantics and targeting ESNext or higher,
80591                 // then we don't need to transform any class properties.
80592                 return languageVersion < 99 /* ESNext */;
80593             }
80594             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
80595         }
80596         function transformConstructor(node, isDerivedClass) {
80597             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
80598             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
80599             if (!ts.some(properties)) {
80600                 return constructor;
80601             }
80602             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
80603             var body = transformConstructorBody(node, constructor, isDerivedClass);
80604             if (!body) {
80605                 return undefined;
80606             }
80607             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
80608             /*decorators*/ undefined, 
80609             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
80610         }
80611         function transformConstructorBody(node, constructor, isDerivedClass) {
80612             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
80613             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
80614             if (!useDefineForClassFields) {
80615                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
80616             }
80617             // Only generate synthetic constructor when there are property initializers to move.
80618             if (!constructor && !ts.some(properties)) {
80619                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
80620             }
80621             resumeLexicalEnvironment();
80622             var indexOfFirstStatement = 0;
80623             var statements = [];
80624             if (!constructor && isDerivedClass) {
80625                 // Add a synthetic `super` call:
80626                 //
80627                 //  super(...arguments);
80628                 //
80629                 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
80630                 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
80631             }
80632             if (constructor) {
80633                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
80634             }
80635             // Add the property initializers. Transforms this:
80636             //
80637             //  public x = 1;
80638             //
80639             // Into this:
80640             //
80641             //  constructor() {
80642             //      this.x = 1;
80643             //  }
80644             //
80645             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
80646                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
80647                 if (afterParameterProperties === -1) {
80648                     afterParameterProperties = constructor.body.statements.length;
80649                 }
80650                 if (afterParameterProperties > indexOfFirstStatement) {
80651                     if (!useDefineForClassFields) {
80652                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
80653                     }
80654                     indexOfFirstStatement = afterParameterProperties;
80655                 }
80656             }
80657             addPropertyStatements(statements, properties, ts.createThis());
80658             // Add existing statements, skipping the initial super call.
80659             if (constructor) {
80660                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
80661             }
80662             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
80663             return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
80664             /*location*/ constructor ? constructor.body.statements : node.members), 
80665             /*multiLine*/ true), 
80666             /*location*/ constructor ? constructor.body : undefined);
80667         }
80668         /**
80669          * Generates assignment statements for property initializers.
80670          *
80671          * @param properties An array of property declarations to transform.
80672          * @param receiver The receiver on which each property should be assigned.
80673          */
80674         function addPropertyStatements(statements, properties, receiver) {
80675             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
80676                 var property = properties_8[_i];
80677                 var expression = transformProperty(property, receiver);
80678                 if (!expression) {
80679                     continue;
80680                 }
80681                 var statement = ts.createExpressionStatement(expression);
80682                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
80683                 ts.setCommentRange(statement, property);
80684                 ts.setOriginalNode(statement, property);
80685                 statements.push(statement);
80686             }
80687         }
80688         /**
80689          * Generates assignment expressions for property initializers.
80690          *
80691          * @param properties An array of property declarations to transform.
80692          * @param receiver The receiver on which each property should be assigned.
80693          */
80694         function generateInitializedPropertyExpressions(properties, receiver) {
80695             var expressions = [];
80696             for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
80697                 var property = properties_9[_i];
80698                 var expression = transformProperty(property, receiver);
80699                 if (!expression) {
80700                     continue;
80701                 }
80702                 ts.startOnNewLine(expression);
80703                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
80704                 ts.setCommentRange(expression, property);
80705                 ts.setOriginalNode(expression, property);
80706                 expressions.push(expression);
80707             }
80708             return expressions;
80709         }
80710         /**
80711          * Transforms a property initializer into an assignment statement.
80712          *
80713          * @param property The property declaration.
80714          * @param receiver The object receiving the property assignment.
80715          */
80716         function transformProperty(property, receiver) {
80717             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
80718             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
80719             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
80720                 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
80721                 : property.name;
80722             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
80723                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
80724                 if (privateIdentifierInfo) {
80725                     switch (privateIdentifierInfo.placement) {
80726                         case 0 /* InstanceField */: {
80727                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
80728                         }
80729                     }
80730                 }
80731                 else {
80732                     ts.Debug.fail("Undeclared private name for property declaration.");
80733                 }
80734             }
80735             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80736                 return undefined;
80737             }
80738             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80739                 return undefined;
80740             }
80741             var propertyOriginalNode = ts.getOriginalNode(property);
80742             var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
80743                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
80744                     : ts.createVoidZero();
80745             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
80746                 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
80747                 return ts.createAssignment(memberAccess, initializer);
80748             }
80749             else {
80750                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
80751                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
80752                         : propertyName;
80753                 var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
80754                 return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
80755             }
80756         }
80757         function enableSubstitutionForClassAliases() {
80758             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
80759                 enabledSubstitutions |= 1 /* ClassAliases */;
80760                 // We need to enable substitutions for identifiers. This allows us to
80761                 // substitute class names inside of a class declaration.
80762                 context.enableSubstitution(75 /* Identifier */);
80763                 // Keep track of class aliases.
80764                 classAliases = [];
80765             }
80766         }
80767         /**
80768          * Hooks node substitutions.
80769          *
80770          * @param hint The context for the emitter.
80771          * @param node The node to substitute.
80772          */
80773         function onSubstituteNode(hint, node) {
80774             node = previousOnSubstituteNode(hint, node);
80775             if (hint === 1 /* Expression */) {
80776                 return substituteExpression(node);
80777             }
80778             return node;
80779         }
80780         function substituteExpression(node) {
80781             switch (node.kind) {
80782                 case 75 /* Identifier */:
80783                     return substituteExpressionIdentifier(node);
80784             }
80785             return node;
80786         }
80787         function substituteExpressionIdentifier(node) {
80788             return trySubstituteClassAlias(node) || node;
80789         }
80790         function trySubstituteClassAlias(node) {
80791             if (enabledSubstitutions & 1 /* ClassAliases */) {
80792                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80793                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80794                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80795                     // behavior of class names in ES6.
80796                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80797                     // constructor references in static property initializers.
80798                     var declaration = resolver.getReferencedValueDeclaration(node);
80799                     if (declaration) {
80800                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80801                         if (classAlias) {
80802                             var clone_2 = ts.getSynthesizedClone(classAlias);
80803                             ts.setSourceMapRange(clone_2, node);
80804                             ts.setCommentRange(clone_2, node);
80805                             return clone_2;
80806                         }
80807                     }
80808                 }
80809             }
80810             return undefined;
80811         }
80812         /**
80813          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
80814          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
80815          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
80816          */
80817         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
80818             if (ts.isComputedPropertyName(name)) {
80819                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
80820                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
80821                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
80822                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
80823                 if (!alreadyTransformed && !inlinable && shouldHoist) {
80824                     var generatedName = ts.getGeneratedNameForNode(name);
80825                     hoistVariableDeclaration(generatedName);
80826                     return ts.createAssignment(generatedName, expression);
80827                 }
80828                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
80829             }
80830         }
80831         function startPrivateIdentifierEnvironment() {
80832             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
80833             currentPrivateIdentifierEnvironment = undefined;
80834         }
80835         function endPrivateIdentifierEnvironment() {
80836             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
80837         }
80838         function addPrivateIdentifierToEnvironment(name) {
80839             var text = ts.getTextOfPropertyName(name);
80840             var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
80841             weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80842             hoistVariableDeclaration(weakMapName);
80843             (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
80844                 .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
80845             (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"), 
80846             /*typeArguments*/ undefined, [])));
80847         }
80848         function accessPrivateIdentifier(name) {
80849             if (currentPrivateIdentifierEnvironment) {
80850                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
80851                 if (info) {
80852                     return info;
80853                 }
80854             }
80855             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
80856                 var env = privateIdentifierEnvironmentStack[i];
80857                 if (!env) {
80858                     continue;
80859                 }
80860                 var info = env.get(name.escapedText);
80861                 if (info) {
80862                     return info;
80863                 }
80864             }
80865             return undefined;
80866         }
80867         function wrapPrivateIdentifierForDestructuringTarget(node) {
80868             var parameter = ts.getGeneratedNameForNode(node);
80869             var info = accessPrivateIdentifier(node.name);
80870             if (!info) {
80871                 return ts.visitEachChild(node, visitor, context);
80872             }
80873             var receiver = node.expression;
80874             // We cannot copy `this` or `super` into the function because they will be bound
80875             // differently inside the function.
80876             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
80877                 receiver = ts.createTempVariable(hoistVariableDeclaration);
80878                 receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80879                 (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
80880             }
80881             return ts.createPropertyAccess(
80882             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
80883             ts.createParen(ts.createObjectLiteral([
80884                 ts.createSetAccessor(
80885                 /*decorators*/ undefined, 
80886                 /*modifiers*/ undefined, "value", [ts.createParameter(
80887                     /*decorators*/ undefined, 
80888                     /*modifiers*/ undefined, 
80889                     /*dotDotDotToken*/ undefined, parameter, 
80890                     /*questionToken*/ undefined, 
80891                     /*type*/ undefined, 
80892                     /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
80893             ])), "value");
80894         }
80895         function visitArrayAssignmentTarget(node) {
80896             var target = ts.getTargetOfBindingOrAssignmentElement(node);
80897             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80898                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80899                 if (ts.isAssignmentExpression(node)) {
80900                     return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
80901                 }
80902                 else if (ts.isSpreadElement(node)) {
80903                     return ts.updateSpread(node, wrapped);
80904                 }
80905                 else {
80906                     return wrapped;
80907                 }
80908             }
80909             return ts.visitNode(node, visitorDestructuringTarget);
80910         }
80911         function visitObjectAssignmentTarget(node) {
80912             if (ts.isPropertyAssignment(node)) {
80913                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
80914                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80915                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
80916                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80917                     return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
80918                 }
80919                 return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
80920             }
80921             return ts.visitNode(node, visitor);
80922         }
80923         function visitAssignmentPattern(node) {
80924             if (ts.isArrayLiteralExpression(node)) {
80925                 // Transforms private names in destructuring assignment array bindings.
80926                 //
80927                 // Source:
80928                 // ([ this.#myProp ] = [ "hello" ]);
80929                 //
80930                 // Transformation:
80931                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
80932                 return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
80933             }
80934             else {
80935                 // Transforms private names in destructuring assignment object bindings.
80936                 //
80937                 // Source:
80938                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
80939                 //
80940                 // Transformation:
80941                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
80942                 return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
80943             }
80944         }
80945     }
80946     ts.transformClassFields = transformClassFields;
80947     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
80948         return ts.createCall(ts.createPropertyAccess(weakMapName, "set"), 
80949         /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
80950     }
80951     ts.classPrivateFieldGetHelper = {
80952         name: "typescript:classPrivateFieldGet",
80953         scoped: false,
80954         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            };"
80955     };
80956     function createClassPrivateFieldGetHelper(context, receiver, privateField) {
80957         context.requestEmitHelper(ts.classPrivateFieldGetHelper);
80958         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
80959     }
80960     ts.classPrivateFieldSetHelper = {
80961         name: "typescript:classPrivateFieldSet",
80962         scoped: false,
80963         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            };"
80964     };
80965     function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
80966         context.requestEmitHelper(ts.classPrivateFieldSetHelper);
80967         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
80968     }
80969 })(ts || (ts = {}));
80970 /*@internal*/
80971 var ts;
80972 (function (ts) {
80973     var ES2017SubstitutionFlags;
80974     (function (ES2017SubstitutionFlags) {
80975         /** Enables substitutions for async methods with `super` calls. */
80976         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
80977     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
80978     var ContextFlags;
80979     (function (ContextFlags) {
80980         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
80981         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
80982     })(ContextFlags || (ContextFlags = {}));
80983     function transformES2017(context) {
80984         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80985         var resolver = context.getEmitResolver();
80986         var compilerOptions = context.getCompilerOptions();
80987         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80988         /**
80989          * Keeps track of whether expression substitution has been enabled for specific edge cases.
80990          * They are persisted between each SourceFile transformation and should not be reset.
80991          */
80992         var enabledSubstitutions;
80993         /**
80994          * This keeps track of containers where `super` is valid, for use with
80995          * just-in-time substitution for `super` expressions inside of async methods.
80996          */
80997         var enclosingSuperContainerFlags = 0;
80998         var enclosingFunctionParameterNames;
80999         /**
81000          * Keeps track of property names accessed on super (`super.x`) within async functions.
81001          */
81002         var capturedSuperProperties;
81003         /** Whether the async function contains an element access on super (`super[x]`). */
81004         var hasSuperElementAccess;
81005         /** A set of node IDs for generated super accessors (variable statements). */
81006         var substitutedSuperAccessors = [];
81007         var contextFlags = 0;
81008         // Save the previous transformation hooks.
81009         var previousOnEmitNode = context.onEmitNode;
81010         var previousOnSubstituteNode = context.onSubstituteNode;
81011         // Set new transformation hooks.
81012         context.onEmitNode = onEmitNode;
81013         context.onSubstituteNode = onSubstituteNode;
81014         return ts.chainBundle(transformSourceFile);
81015         function transformSourceFile(node) {
81016             if (node.isDeclarationFile) {
81017                 return node;
81018             }
81019             setContextFlag(1 /* NonTopLevel */, false);
81020             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
81021             var visited = ts.visitEachChild(node, visitor, context);
81022             ts.addEmitHelpers(visited, context.readEmitHelpers());
81023             return visited;
81024         }
81025         function setContextFlag(flag, val) {
81026             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
81027         }
81028         function inContext(flags) {
81029             return (contextFlags & flags) !== 0;
81030         }
81031         function inTopLevelContext() {
81032             return !inContext(1 /* NonTopLevel */);
81033         }
81034         function inHasLexicalThisContext() {
81035             return inContext(2 /* HasLexicalThis */);
81036         }
81037         function doWithContext(flags, cb, value) {
81038             var contextFlagsToSet = flags & ~contextFlags;
81039             if (contextFlagsToSet) {
81040                 setContextFlag(contextFlagsToSet, /*val*/ true);
81041                 var result = cb(value);
81042                 setContextFlag(contextFlagsToSet, /*val*/ false);
81043                 return result;
81044             }
81045             return cb(value);
81046         }
81047         function visitDefault(node) {
81048             return ts.visitEachChild(node, visitor, context);
81049         }
81050         function visitor(node) {
81051             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
81052                 return node;
81053             }
81054             switch (node.kind) {
81055                 case 126 /* AsyncKeyword */:
81056                     // ES2017 async modifier should be elided for targets < ES2017
81057                     return undefined;
81058                 case 206 /* AwaitExpression */:
81059                     return visitAwaitExpression(node);
81060                 case 161 /* MethodDeclaration */:
81061                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
81062                 case 244 /* FunctionDeclaration */:
81063                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
81064                 case 201 /* FunctionExpression */:
81065                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
81066                 case 202 /* ArrowFunction */:
81067                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
81068                 case 194 /* PropertyAccessExpression */:
81069                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81070                         capturedSuperProperties.set(node.name.escapedText, true);
81071                     }
81072                     return ts.visitEachChild(node, visitor, context);
81073                 case 195 /* ElementAccessExpression */:
81074                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81075                         hasSuperElementAccess = true;
81076                     }
81077                     return ts.visitEachChild(node, visitor, context);
81078                 case 163 /* GetAccessor */:
81079                 case 164 /* SetAccessor */:
81080                 case 162 /* Constructor */:
81081                 case 245 /* ClassDeclaration */:
81082                 case 214 /* ClassExpression */:
81083                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
81084                 default:
81085                     return ts.visitEachChild(node, visitor, context);
81086             }
81087         }
81088         function asyncBodyVisitor(node) {
81089             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
81090                 switch (node.kind) {
81091                     case 225 /* VariableStatement */:
81092                         return visitVariableStatementInAsyncBody(node);
81093                     case 230 /* ForStatement */:
81094                         return visitForStatementInAsyncBody(node);
81095                     case 231 /* ForInStatement */:
81096                         return visitForInStatementInAsyncBody(node);
81097                     case 232 /* ForOfStatement */:
81098                         return visitForOfStatementInAsyncBody(node);
81099                     case 280 /* CatchClause */:
81100                         return visitCatchClauseInAsyncBody(node);
81101                     case 223 /* Block */:
81102                     case 237 /* SwitchStatement */:
81103                     case 251 /* CaseBlock */:
81104                     case 277 /* CaseClause */:
81105                     case 278 /* DefaultClause */:
81106                     case 240 /* TryStatement */:
81107                     case 228 /* DoStatement */:
81108                     case 229 /* WhileStatement */:
81109                     case 227 /* IfStatement */:
81110                     case 236 /* WithStatement */:
81111                     case 238 /* LabeledStatement */:
81112                         return ts.visitEachChild(node, asyncBodyVisitor, context);
81113                     default:
81114                         return ts.Debug.assertNever(node, "Unhandled node.");
81115                 }
81116             }
81117             return visitor(node);
81118         }
81119         function visitCatchClauseInAsyncBody(node) {
81120             var catchClauseNames = ts.createUnderscoreEscapedMap();
81121             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
81122             // names declared in a catch variable are block scoped
81123             var catchClauseUnshadowedNames;
81124             catchClauseNames.forEach(function (_, escapedName) {
81125                 if (enclosingFunctionParameterNames.has(escapedName)) {
81126                     if (!catchClauseUnshadowedNames) {
81127                         catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
81128                     }
81129                     catchClauseUnshadowedNames.delete(escapedName);
81130                 }
81131             });
81132             if (catchClauseUnshadowedNames) {
81133                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81134                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
81135                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
81136                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81137                 return result;
81138             }
81139             else {
81140                 return ts.visitEachChild(node, asyncBodyVisitor, context);
81141             }
81142         }
81143         function visitVariableStatementInAsyncBody(node) {
81144             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
81145                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
81146                 return expression ? ts.createExpressionStatement(expression) : undefined;
81147             }
81148             return ts.visitEachChild(node, visitor, context);
81149         }
81150         function visitForInStatementInAsyncBody(node) {
81151             return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
81152                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
81153                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81154         }
81155         function visitForOfStatementInAsyncBody(node) {
81156             return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
81157                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
81158                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81159         }
81160         function visitForStatementInAsyncBody(node) {
81161             var initializer = node.initializer; // TODO: GH#18217
81162             return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
81163                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
81164                 : 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));
81165         }
81166         /**
81167          * Visits an AwaitExpression node.
81168          *
81169          * This function will be called any time a ES2017 await expression is encountered.
81170          *
81171          * @param node The node to visit.
81172          */
81173         function visitAwaitExpression(node) {
81174             // do not downlevel a top-level await as it is module syntax...
81175             if (inTopLevelContext()) {
81176                 return ts.visitEachChild(node, visitor, context);
81177             }
81178             return ts.setOriginalNode(ts.setTextRange(ts.createYield(
81179             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
81180         }
81181         /**
81182          * Visits a MethodDeclaration node.
81183          *
81184          * This function will be called when one of the following conditions are met:
81185          * - The node is marked as async
81186          *
81187          * @param node The node to visit.
81188          */
81189         function visitMethodDeclaration(node) {
81190             return ts.updateMethod(node, 
81191             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81192             /*questionToken*/ undefined, 
81193             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81194             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81195                 ? transformAsyncFunctionBody(node)
81196                 : ts.visitFunctionBody(node.body, visitor, context));
81197         }
81198         /**
81199          * Visits a FunctionDeclaration node.
81200          *
81201          * This function will be called when one of the following conditions are met:
81202          * - The node is marked async
81203          *
81204          * @param node The node to visit.
81205          */
81206         function visitFunctionDeclaration(node) {
81207             return ts.updateFunctionDeclaration(node, 
81208             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81209             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81210             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81211                 ? transformAsyncFunctionBody(node)
81212                 : ts.visitFunctionBody(node.body, visitor, context));
81213         }
81214         /**
81215          * Visits a FunctionExpression node.
81216          *
81217          * This function will be called when one of the following conditions are met:
81218          * - The node is marked async
81219          *
81220          * @param node The node to visit.
81221          */
81222         function visitFunctionExpression(node) {
81223             return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81224             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81225             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81226                 ? transformAsyncFunctionBody(node)
81227                 : ts.visitFunctionBody(node.body, visitor, context));
81228         }
81229         /**
81230          * Visits an ArrowFunction.
81231          *
81232          * This function will be called when one of the following conditions are met:
81233          * - The node is marked async
81234          *
81235          * @param node The node to visit.
81236          */
81237         function visitArrowFunction(node) {
81238             return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
81239             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81240             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
81241                 ? transformAsyncFunctionBody(node)
81242                 : ts.visitFunctionBody(node.body, visitor, context));
81243         }
81244         function recordDeclarationName(_a, names) {
81245             var name = _a.name;
81246             if (ts.isIdentifier(name)) {
81247                 names.set(name.escapedText, true);
81248             }
81249             else {
81250                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81251                     var element = _b[_i];
81252                     if (!ts.isOmittedExpression(element)) {
81253                         recordDeclarationName(element, names);
81254                     }
81255                 }
81256             }
81257         }
81258         function isVariableDeclarationListWithCollidingName(node) {
81259             return !!node
81260                 && ts.isVariableDeclarationList(node)
81261                 && !(node.flags & 3 /* BlockScoped */)
81262                 && node.declarations.some(collidesWithParameterName);
81263         }
81264         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
81265             hoistVariableDeclarationList(node);
81266             var variables = ts.getInitializedVariables(node);
81267             if (variables.length === 0) {
81268                 if (hasReceiver) {
81269                     return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
81270                 }
81271                 return undefined;
81272             }
81273             return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
81274         }
81275         function hoistVariableDeclarationList(node) {
81276             ts.forEach(node.declarations, hoistVariable);
81277         }
81278         function hoistVariable(_a) {
81279             var name = _a.name;
81280             if (ts.isIdentifier(name)) {
81281                 hoistVariableDeclaration(name);
81282             }
81283             else {
81284                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81285                     var element = _b[_i];
81286                     if (!ts.isOmittedExpression(element)) {
81287                         hoistVariable(element);
81288                     }
81289                 }
81290             }
81291         }
81292         function transformInitializedVariable(node) {
81293             var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
81294             return ts.visitNode(converted, visitor, ts.isExpression);
81295         }
81296         function collidesWithParameterName(_a) {
81297             var name = _a.name;
81298             if (ts.isIdentifier(name)) {
81299                 return enclosingFunctionParameterNames.has(name.escapedText);
81300             }
81301             else {
81302                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81303                     var element = _b[_i];
81304                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
81305                         return true;
81306                     }
81307                 }
81308             }
81309             return false;
81310         }
81311         function transformAsyncFunctionBody(node) {
81312             resumeLexicalEnvironment();
81313             var original = ts.getOriginalNode(node, ts.isFunctionLike);
81314             var nodeType = original.type;
81315             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
81316             var isArrowFunction = node.kind === 202 /* ArrowFunction */;
81317             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
81318             // An async function is emit as an outer function that calls an inner
81319             // generator function. To preserve lexical bindings, we pass the current
81320             // `this` and `arguments` objects to `__awaiter`. The generator function
81321             // passed to `__awaiter` is executed inside of the callback to the
81322             // promise constructor.
81323             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81324             enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
81325             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
81326                 var parameter = _a[_i];
81327                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
81328             }
81329             var savedCapturedSuperProperties = capturedSuperProperties;
81330             var savedHasSuperElementAccess = hasSuperElementAccess;
81331             if (!isArrowFunction) {
81332                 capturedSuperProperties = ts.createUnderscoreEscapedMap();
81333                 hasSuperElementAccess = false;
81334             }
81335             var result;
81336             if (!isArrowFunction) {
81337                 var statements = [];
81338                 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81339                 statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
81340                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
81341                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
81342                 // This step isn't needed if we eventually transform this to ES5.
81343                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
81344                 if (emitSuperHelpers) {
81345                     enableSubstitutionForAsyncMethodsWithSuper();
81346                     if (ts.hasEntries(capturedSuperProperties)) {
81347                         var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
81348                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
81349                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
81350                     }
81351                 }
81352                 var block = ts.createBlock(statements, /*multiLine*/ true);
81353                 ts.setTextRange(block, node.body);
81354                 if (emitSuperHelpers && hasSuperElementAccess) {
81355                     // Emit helpers for super element access expressions (`super[x]`).
81356                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
81357                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
81358                     }
81359                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
81360                         ts.addEmitHelper(block, ts.asyncSuperHelper);
81361                     }
81362                 }
81363                 result = block;
81364             }
81365             else {
81366                 var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
81367                 var declarations = endLexicalEnvironment();
81368                 if (ts.some(declarations)) {
81369                     var block = ts.convertToFunctionBody(expression);
81370                     result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
81371                 }
81372                 else {
81373                     result = expression;
81374                 }
81375             }
81376             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81377             if (!isArrowFunction) {
81378                 capturedSuperProperties = savedCapturedSuperProperties;
81379                 hasSuperElementAccess = savedHasSuperElementAccess;
81380             }
81381             return result;
81382         }
81383         function transformAsyncFunctionBodyWorker(body, start) {
81384             if (ts.isBlock(body)) {
81385                 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
81386             }
81387             else {
81388                 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
81389             }
81390         }
81391         function getPromiseConstructor(type) {
81392             var typeName = type && ts.getEntityNameFromTypeNode(type);
81393             if (typeName && ts.isEntityName(typeName)) {
81394                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
81395                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
81396                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
81397                     return typeName;
81398                 }
81399             }
81400             return undefined;
81401         }
81402         function enableSubstitutionForAsyncMethodsWithSuper() {
81403             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
81404                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
81405                 // We need to enable substitutions for call, property access, and element access
81406                 // if we need to rewrite super calls.
81407                 context.enableSubstitution(196 /* CallExpression */);
81408                 context.enableSubstitution(194 /* PropertyAccessExpression */);
81409                 context.enableSubstitution(195 /* ElementAccessExpression */);
81410                 // We need to be notified when entering and exiting declarations that bind super.
81411                 context.enableEmitNotification(245 /* ClassDeclaration */);
81412                 context.enableEmitNotification(161 /* MethodDeclaration */);
81413                 context.enableEmitNotification(163 /* GetAccessor */);
81414                 context.enableEmitNotification(164 /* SetAccessor */);
81415                 context.enableEmitNotification(162 /* Constructor */);
81416                 // We need to be notified when entering the generated accessor arrow functions.
81417                 context.enableEmitNotification(225 /* VariableStatement */);
81418             }
81419         }
81420         /**
81421          * Hook for node emit.
81422          *
81423          * @param hint A hint as to the intended usage of the node.
81424          * @param node The node to emit.
81425          * @param emit A callback used to emit the node in the printer.
81426          */
81427         function onEmitNode(hint, node, emitCallback) {
81428             // If we need to support substitutions for `super` in an async method,
81429             // we should track it here.
81430             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
81431                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
81432                 if (superContainerFlags !== enclosingSuperContainerFlags) {
81433                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81434                     enclosingSuperContainerFlags = superContainerFlags;
81435                     previousOnEmitNode(hint, node, emitCallback);
81436                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81437                     return;
81438                 }
81439             }
81440             // Disable substitution in the generated super accessor itself.
81441             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
81442                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81443                 enclosingSuperContainerFlags = 0;
81444                 previousOnEmitNode(hint, node, emitCallback);
81445                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81446                 return;
81447             }
81448             previousOnEmitNode(hint, node, emitCallback);
81449         }
81450         /**
81451          * Hooks node substitutions.
81452          *
81453          * @param hint A hint as to the intended usage of the node.
81454          * @param node The node to substitute.
81455          */
81456         function onSubstituteNode(hint, node) {
81457             node = previousOnSubstituteNode(hint, node);
81458             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
81459                 return substituteExpression(node);
81460             }
81461             return node;
81462         }
81463         function substituteExpression(node) {
81464             switch (node.kind) {
81465                 case 194 /* PropertyAccessExpression */:
81466                     return substitutePropertyAccessExpression(node);
81467                 case 195 /* ElementAccessExpression */:
81468                     return substituteElementAccessExpression(node);
81469                 case 196 /* CallExpression */:
81470                     return substituteCallExpression(node);
81471             }
81472             return node;
81473         }
81474         function substitutePropertyAccessExpression(node) {
81475             if (node.expression.kind === 102 /* SuperKeyword */) {
81476                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
81477             }
81478             return node;
81479         }
81480         function substituteElementAccessExpression(node) {
81481             if (node.expression.kind === 102 /* SuperKeyword */) {
81482                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
81483             }
81484             return node;
81485         }
81486         function substituteCallExpression(node) {
81487             var expression = node.expression;
81488             if (ts.isSuperProperty(expression)) {
81489                 var argumentExpression = ts.isPropertyAccessExpression(expression)
81490                     ? substitutePropertyAccessExpression(expression)
81491                     : substituteElementAccessExpression(expression);
81492                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
81493                 /*typeArguments*/ undefined, __spreadArrays([
81494                     ts.createThis()
81495                 ], node.arguments));
81496             }
81497             return node;
81498         }
81499         function isSuperContainer(node) {
81500             var kind = node.kind;
81501             return kind === 245 /* ClassDeclaration */
81502                 || kind === 162 /* Constructor */
81503                 || kind === 161 /* MethodDeclaration */
81504                 || kind === 163 /* GetAccessor */
81505                 || kind === 164 /* SetAccessor */;
81506         }
81507         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
81508             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
81509                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81510                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
81511             }
81512             else {
81513                 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81514                 /*typeArguments*/ undefined, [argumentExpression]), location);
81515             }
81516         }
81517     }
81518     ts.transformES2017 = transformES2017;
81519     /** Creates a variable named `_super` with accessor properties for the given property names. */
81520     function createSuperAccessVariableStatement(resolver, node, names) {
81521         // Create a variable declaration with a getter/setter (if binding) definition for each name:
81522         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
81523         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
81524         var accessors = [];
81525         names.forEach(function (_, key) {
81526             var name = ts.unescapeLeadingUnderscores(key);
81527             var getterAndSetter = [];
81528             getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
81529             /* modifiers */ undefined, 
81530             /* typeParameters */ undefined, 
81531             /* parameters */ [], 
81532             /* type */ undefined, 
81533             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
81534             if (hasBinding) {
81535                 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
81536                 /* modifiers */ undefined, 
81537                 /* typeParameters */ undefined, 
81538                 /* parameters */ [
81539                     ts.createParameter(
81540                     /* decorators */ undefined, 
81541                     /* modifiers */ undefined, 
81542                     /* dotDotDotToken */ undefined, "v", 
81543                     /* questionToken */ undefined, 
81544                     /* type */ undefined, 
81545                     /* initializer */ undefined)
81546                 ], 
81547                 /* type */ undefined, 
81548                 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
81549             }
81550             accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
81551         });
81552         return ts.createVariableStatement(
81553         /* modifiers */ undefined, ts.createVariableDeclarationList([
81554             ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), 
81555             /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), 
81556             /* typeArguments */ undefined, [
81557                 ts.createNull(),
81558                 ts.createObjectLiteral(accessors, /* multiline */ true)
81559             ]))
81560         ], 2 /* Const */));
81561     }
81562     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
81563     ts.awaiterHelper = {
81564         name: "typescript:awaiter",
81565         importName: "__awaiter",
81566         scoped: false,
81567         priority: 5,
81568         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            };"
81569     };
81570     function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
81571         context.requestEmitHelper(ts.awaiterHelper);
81572         var generatorFunc = ts.createFunctionExpression(
81573         /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), 
81574         /*name*/ undefined, 
81575         /*typeParameters*/ undefined, 
81576         /*parameters*/ [], 
81577         /*type*/ undefined, body);
81578         // Mark this node as originally an async function
81579         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
81580         return ts.createCall(ts.getUnscopedHelperName("__awaiter"), 
81581         /*typeArguments*/ undefined, [
81582             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
81583             hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
81584             promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
81585             generatorFunc
81586         ]);
81587     }
81588     ts.asyncSuperHelper = {
81589         name: "typescript:async-super",
81590         scoped: true,
81591         text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
81592     };
81593     ts.advancedAsyncSuperHelper = {
81594         name: "typescript:advanced-async-super",
81595         scoped: true,
81596         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")
81597     };
81598 })(ts || (ts = {}));
81599 /*@internal*/
81600 var ts;
81601 (function (ts) {
81602     var ESNextSubstitutionFlags;
81603     (function (ESNextSubstitutionFlags) {
81604         /** Enables substitutions for async methods with `super` calls. */
81605         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
81606     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
81607     // Facts we track as we traverse the tree
81608     var HierarchyFacts;
81609     (function (HierarchyFacts) {
81610         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
81611         //
81612         // Ancestor facts
81613         //
81614         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
81615         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
81616         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
81617         //
81618         // Ancestor masks
81619         //
81620         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
81621         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
81622         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
81623         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
81624         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
81625         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
81626         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
81627         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
81628         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
81629         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
81630     })(HierarchyFacts || (HierarchyFacts = {}));
81631     function transformES2018(context) {
81632         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
81633         var resolver = context.getEmitResolver();
81634         var compilerOptions = context.getCompilerOptions();
81635         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
81636         var previousOnEmitNode = context.onEmitNode;
81637         context.onEmitNode = onEmitNode;
81638         var previousOnSubstituteNode = context.onSubstituteNode;
81639         context.onSubstituteNode = onSubstituteNode;
81640         var exportedVariableStatement = false;
81641         var enabledSubstitutions;
81642         var enclosingFunctionFlags;
81643         var enclosingSuperContainerFlags = 0;
81644         var hierarchyFacts = 0;
81645         var currentSourceFile;
81646         var taggedTemplateStringDeclarations;
81647         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
81648         var capturedSuperProperties;
81649         /** Whether the async function contains an element access on super (`super[x]`). */
81650         var hasSuperElementAccess;
81651         /** A set of node IDs for generated super accessors. */
81652         var substitutedSuperAccessors = [];
81653         return ts.chainBundle(transformSourceFile);
81654         function affectsSubtree(excludeFacts, includeFacts) {
81655             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
81656         }
81657         /**
81658          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
81659          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
81660          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
81661          */
81662         function enterSubtree(excludeFacts, includeFacts) {
81663             var ancestorFacts = hierarchyFacts;
81664             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
81665             return ancestorFacts;
81666         }
81667         /**
81668          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
81669          * subtree.
81670          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
81671          */
81672         function exitSubtree(ancestorFacts) {
81673             hierarchyFacts = ancestorFacts;
81674         }
81675         function recordTaggedTemplateString(temp) {
81676             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
81677         }
81678         function transformSourceFile(node) {
81679             if (node.isDeclarationFile) {
81680                 return node;
81681             }
81682             currentSourceFile = node;
81683             var visited = visitSourceFile(node);
81684             ts.addEmitHelpers(visited, context.readEmitHelpers());
81685             currentSourceFile = undefined;
81686             taggedTemplateStringDeclarations = undefined;
81687             return visited;
81688         }
81689         function visitor(node) {
81690             return visitorWorker(node, /*noDestructuringValue*/ false);
81691         }
81692         function visitorNoDestructuringValue(node) {
81693             return visitorWorker(node, /*noDestructuringValue*/ true);
81694         }
81695         function visitorNoAsyncModifier(node) {
81696             if (node.kind === 126 /* AsyncKeyword */) {
81697                 return undefined;
81698             }
81699             return node;
81700         }
81701         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
81702             if (affectsSubtree(excludeFacts, includeFacts)) {
81703                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
81704                 var result = cb(value);
81705                 exitSubtree(ancestorFacts);
81706                 return result;
81707             }
81708             return cb(value);
81709         }
81710         function visitDefault(node) {
81711             return ts.visitEachChild(node, visitor, context);
81712         }
81713         function visitorWorker(node, noDestructuringValue) {
81714             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
81715                 return node;
81716             }
81717             switch (node.kind) {
81718                 case 206 /* AwaitExpression */:
81719                     return visitAwaitExpression(node);
81720                 case 212 /* YieldExpression */:
81721                     return visitYieldExpression(node);
81722                 case 235 /* ReturnStatement */:
81723                     return visitReturnStatement(node);
81724                 case 238 /* LabeledStatement */:
81725                     return visitLabeledStatement(node);
81726                 case 193 /* ObjectLiteralExpression */:
81727                     return visitObjectLiteralExpression(node);
81728                 case 209 /* BinaryExpression */:
81729                     return visitBinaryExpression(node, noDestructuringValue);
81730                 case 280 /* CatchClause */:
81731                     return visitCatchClause(node);
81732                 case 225 /* VariableStatement */:
81733                     return visitVariableStatement(node);
81734                 case 242 /* VariableDeclaration */:
81735                     return visitVariableDeclaration(node);
81736                 case 228 /* DoStatement */:
81737                 case 229 /* WhileStatement */:
81738                 case 231 /* ForInStatement */:
81739                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81740                 case 232 /* ForOfStatement */:
81741                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
81742                 case 230 /* ForStatement */:
81743                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81744                 case 205 /* VoidExpression */:
81745                     return visitVoidExpression(node);
81746                 case 162 /* Constructor */:
81747                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81748                 case 161 /* MethodDeclaration */:
81749                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81750                 case 163 /* GetAccessor */:
81751                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81752                 case 164 /* SetAccessor */:
81753                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81754                 case 244 /* FunctionDeclaration */:
81755                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81756                 case 201 /* FunctionExpression */:
81757                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81758                 case 202 /* ArrowFunction */:
81759                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
81760                 case 156 /* Parameter */:
81761                     return visitParameter(node);
81762                 case 226 /* ExpressionStatement */:
81763                     return visitExpressionStatement(node);
81764                 case 200 /* ParenthesizedExpression */:
81765                     return visitParenthesizedExpression(node, noDestructuringValue);
81766                 case 198 /* TaggedTemplateExpression */:
81767                     return visitTaggedTemplateExpression(node);
81768                 case 194 /* PropertyAccessExpression */:
81769                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81770                         capturedSuperProperties.set(node.name.escapedText, true);
81771                     }
81772                     return ts.visitEachChild(node, visitor, context);
81773                 case 195 /* ElementAccessExpression */:
81774                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81775                         hasSuperElementAccess = true;
81776                     }
81777                     return ts.visitEachChild(node, visitor, context);
81778                 case 245 /* ClassDeclaration */:
81779                 case 214 /* ClassExpression */:
81780                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81781                 default:
81782                     return ts.visitEachChild(node, visitor, context);
81783             }
81784         }
81785         function visitAwaitExpression(node) {
81786             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81787                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
81788                 /*location*/ node), node);
81789             }
81790             return ts.visitEachChild(node, visitor, context);
81791         }
81792         function visitYieldExpression(node) {
81793             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81794                 if (node.asteriskToken) {
81795                     var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81796                     return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
81797                 }
81798                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
81799                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
81800                     : ts.createVoidZero())), node), node);
81801             }
81802             return ts.visitEachChild(node, visitor, context);
81803         }
81804         function visitReturnStatement(node) {
81805             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81806                 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
81807             }
81808             return ts.visitEachChild(node, visitor, context);
81809         }
81810         function visitLabeledStatement(node) {
81811             if (enclosingFunctionFlags & 2 /* Async */) {
81812                 var statement = ts.unwrapInnermostStatementOfLabel(node);
81813                 if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
81814                     return visitForOfStatement(statement, node);
81815                 }
81816                 return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node);
81817             }
81818             return ts.visitEachChild(node, visitor, context);
81819         }
81820         function chunkObjectLiteralElements(elements) {
81821             var chunkObject;
81822             var objects = [];
81823             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
81824                 var e = elements_4[_i];
81825                 if (e.kind === 283 /* SpreadAssignment */) {
81826                     if (chunkObject) {
81827                         objects.push(ts.createObjectLiteral(chunkObject));
81828                         chunkObject = undefined;
81829                     }
81830                     var target = e.expression;
81831                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
81832                 }
81833                 else {
81834                     chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
81835                         ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
81836                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
81837                 }
81838             }
81839             if (chunkObject) {
81840                 objects.push(ts.createObjectLiteral(chunkObject));
81841             }
81842             return objects;
81843         }
81844         function visitObjectLiteralExpression(node) {
81845             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81846                 // spread elements emit like so:
81847                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
81848                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
81849                 // If the first element is a spread element, then the first argument to __assign is {}:
81850                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
81851                 //
81852                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
81853                 // example:
81854                 //      var k = { a: 1, b: 2 };
81855                 //      var o = { a: 3, ...k, b: k.a++ };
81856                 //      // expected: { a: 1, b: 1 }
81857                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
81858                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
81859                 //
81860                 // This also occurs for spread elements, not just property assignments:
81861                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
81862                 //      var l = { c: 3 };
81863                 //      var o = { ...k, ...l };
81864                 //      // expected: { a: 1, b: 2, z: 9 }
81865                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
81866                 // end up with `{ a: 1, b: 2, c: 3 }`
81867                 var objects = chunkObjectLiteralElements(node.properties);
81868                 if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
81869                     objects.unshift(ts.createObjectLiteral());
81870                 }
81871                 var expression = objects[0];
81872                 if (objects.length > 1) {
81873                     for (var i = 1; i < objects.length; i++) {
81874                         expression = createAssignHelper(context, [expression, objects[i]]);
81875                     }
81876                     return expression;
81877                 }
81878                 else {
81879                     return createAssignHelper(context, objects);
81880                 }
81881             }
81882             return ts.visitEachChild(node, visitor, context);
81883         }
81884         function visitExpressionStatement(node) {
81885             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81886         }
81887         function visitParenthesizedExpression(node, noDestructuringValue) {
81888             return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
81889         }
81890         function visitSourceFile(node) {
81891             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
81892                 0 /* StrictModeSourceFileIncludes */ :
81893                 1 /* SourceFileIncludes */);
81894             exportedVariableStatement = false;
81895             var visited = ts.visitEachChild(node, visitor, context);
81896             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
81897                 ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))
81898             ]);
81899             var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements));
81900             exitSubtree(ancestorFacts);
81901             return result;
81902         }
81903         function visitTaggedTemplateExpression(node) {
81904             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
81905         }
81906         /**
81907          * Visits a BinaryExpression that contains a destructuring assignment.
81908          *
81909          * @param node A BinaryExpression node.
81910          */
81911         function visitBinaryExpression(node, noDestructuringValue) {
81912             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81913                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
81914             }
81915             else if (node.operatorToken.kind === 27 /* CommaToken */) {
81916                 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
81917             }
81918             return ts.visitEachChild(node, visitor, context);
81919         }
81920         function visitCatchClause(node) {
81921             if (node.variableDeclaration &&
81922                 ts.isBindingPattern(node.variableDeclaration.name) &&
81923                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81924                 var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
81925                 var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
81926                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
81927                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
81928                 if (ts.some(visitedBindings)) {
81929                     block = ts.updateBlock(block, __spreadArrays([
81930                         ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
81931                     ], block.statements));
81932                 }
81933                 return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
81934             }
81935             return ts.visitEachChild(node, visitor, context);
81936         }
81937         function visitVariableStatement(node) {
81938             if (ts.hasModifier(node, 1 /* Export */)) {
81939                 var savedExportedVariableStatement = exportedVariableStatement;
81940                 exportedVariableStatement = true;
81941                 var visited = ts.visitEachChild(node, visitor, context);
81942                 exportedVariableStatement = savedExportedVariableStatement;
81943                 return visited;
81944             }
81945             return ts.visitEachChild(node, visitor, context);
81946         }
81947         /**
81948          * Visits a VariableDeclaration node with a binding pattern.
81949          *
81950          * @param node A VariableDeclaration node.
81951          */
81952         function visitVariableDeclaration(node) {
81953             if (exportedVariableStatement) {
81954                 var savedExportedVariableStatement = exportedVariableStatement;
81955                 exportedVariableStatement = false;
81956                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
81957                 exportedVariableStatement = savedExportedVariableStatement;
81958                 return visited;
81959             }
81960             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
81961         }
81962         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
81963             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
81964             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81965                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
81966                 /*rval*/ undefined, exportedVariableStatement);
81967             }
81968             return ts.visitEachChild(node, visitor, context);
81969         }
81970         function visitForStatement(node) {
81971             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));
81972         }
81973         function visitVoidExpression(node) {
81974             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81975         }
81976         /**
81977          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
81978          *
81979          * @param node A ForOfStatement.
81980          */
81981         function visitForOfStatement(node, outermostLabeledStatement) {
81982             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81983             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81984                 node = transformForOfStatementWithObjectRest(node);
81985             }
81986             var result = node.awaitModifier ?
81987                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
81988                 ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
81989             exitSubtree(ancestorFacts);
81990             return result;
81991         }
81992         function transformForOfStatementWithObjectRest(node) {
81993             var initializerWithoutParens = ts.skipParentheses(node.initializer);
81994             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
81995                 var bodyLocation = void 0;
81996                 var statementsLocation = void 0;
81997                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
81998                 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
81999                 if (ts.isBlock(node.statement)) {
82000                     ts.addRange(statements, node.statement.statements);
82001                     bodyLocation = node.statement;
82002                     statementsLocation = node.statement.statements;
82003                 }
82004                 else if (node.statement) {
82005                     ts.append(statements, node.statement);
82006                     bodyLocation = node.statement;
82007                     statementsLocation = node.statement;
82008                 }
82009                 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
82010                     ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
82011                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
82012                 /*multiLine*/ true), bodyLocation));
82013             }
82014             return node;
82015         }
82016         function convertForOfStatementHead(node, boundValue) {
82017             var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
82018             var bodyLocation;
82019             var statementsLocation;
82020             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
82021             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
82022             if (ts.isBlock(statement)) {
82023                 ts.addRange(statements, statement.statements);
82024                 bodyLocation = statement;
82025                 statementsLocation = statement.statements;
82026             }
82027             else {
82028                 statements.push(statement);
82029             }
82030             return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
82031             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
82032         }
82033         function createDownlevelAwait(expression) {
82034             return enclosingFunctionFlags & 1 /* Generator */
82035                 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
82036                 : ts.createAwait(expression);
82037         }
82038         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
82039             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82040             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
82041             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
82042             var errorRecord = ts.createUniqueName("e");
82043             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
82044             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
82045             var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
82046             var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
82047             var getDone = ts.createPropertyAccess(result, "done");
82048             var getValue = ts.createPropertyAccess(result, "value");
82049             var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
82050             hoistVariableDeclaration(errorRecord);
82051             hoistVariableDeclaration(returnMethod);
82052             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
82053             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
82054                 ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) :
82055                 callValues;
82056             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
82057             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
82058                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
82059                 ts.createVariableDeclaration(result)
82060             ]), node.expression), 2097152 /* NoHoisting */), 
82061             /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
82062             /*incrementor*/ undefined, 
82063             /*statement*/ convertForOfStatementHead(node, getValue)), 
82064             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
82065             return ts.createTry(ts.createBlock([
82066                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
82067             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
82068                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
82069                     ts.createPropertyAssignment("error", catchVariable)
82070                 ])))
82071             ]), 1 /* SingleLine */)), ts.createBlock([
82072                 ts.createTry(
82073                 /*tryBlock*/ ts.createBlock([
82074                     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 */)
82075                 ]), 
82076                 /*catchClause*/ undefined, 
82077                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
82078                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
82079                 ]), 1 /* SingleLine */))
82080             ]));
82081         }
82082         function visitParameter(node) {
82083             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82084                 // Binding patterns are converted into a generated name and are
82085                 // evaluated inside the function body.
82086                 return ts.updateParameter(node, 
82087                 /*decorators*/ undefined, 
82088                 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
82089                 /*questionToken*/ undefined, 
82090                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
82091             }
82092             return ts.visitEachChild(node, visitor, context);
82093         }
82094         function visitConstructorDeclaration(node) {
82095             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82096             enclosingFunctionFlags = 0 /* Normal */;
82097             var updated = ts.updateConstructor(node, 
82098             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
82099             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82100             return updated;
82101         }
82102         function visitGetAccessorDeclaration(node) {
82103             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82104             enclosingFunctionFlags = 0 /* Normal */;
82105             var updated = ts.updateGetAccessor(node, 
82106             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
82107             /*type*/ undefined, transformFunctionBody(node));
82108             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82109             return updated;
82110         }
82111         function visitSetAccessorDeclaration(node) {
82112             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82113             enclosingFunctionFlags = 0 /* Normal */;
82114             var updated = ts.updateSetAccessor(node, 
82115             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
82116             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82117             return updated;
82118         }
82119         function visitMethodDeclaration(node) {
82120             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82121             enclosingFunctionFlags = ts.getFunctionFlags(node);
82122             var updated = ts.updateMethod(node, 
82123             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
82124                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82125                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82126                 ? undefined
82127                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
82128             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82129             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82130                 ? transformAsyncGeneratorFunctionBody(node)
82131                 : transformFunctionBody(node));
82132             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82133             return updated;
82134         }
82135         function visitFunctionDeclaration(node) {
82136             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82137             enclosingFunctionFlags = ts.getFunctionFlags(node);
82138             var updated = ts.updateFunctionDeclaration(node, 
82139             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
82140                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82141                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82142                 ? undefined
82143                 : node.asteriskToken, node.name, 
82144             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82145             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82146                 ? transformAsyncGeneratorFunctionBody(node)
82147                 : transformFunctionBody(node));
82148             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82149             return updated;
82150         }
82151         function visitArrowFunction(node) {
82152             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82153             enclosingFunctionFlags = ts.getFunctionFlags(node);
82154             var updated = ts.updateArrowFunction(node, node.modifiers, 
82155             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82156             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
82157             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82158             return updated;
82159         }
82160         function visitFunctionExpression(node) {
82161             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82162             enclosingFunctionFlags = ts.getFunctionFlags(node);
82163             var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
82164                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82165                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82166                 ? undefined
82167                 : node.asteriskToken, node.name, 
82168             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82169             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82170                 ? transformAsyncGeneratorFunctionBody(node)
82171                 : transformFunctionBody(node));
82172             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82173             return updated;
82174         }
82175         function transformAsyncGeneratorFunctionBody(node) {
82176             resumeLexicalEnvironment();
82177             var statements = [];
82178             var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
82179             appendObjectRestAssignmentsIfNeeded(statements, node);
82180             var savedCapturedSuperProperties = capturedSuperProperties;
82181             var savedHasSuperElementAccess = hasSuperElementAccess;
82182             capturedSuperProperties = ts.createUnderscoreEscapedMap();
82183             hasSuperElementAccess = false;
82184             var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
82185             /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
82186             /*typeParameters*/ undefined, 
82187             /*parameters*/ [], 
82188             /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
82189             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
82190             // This step isn't needed if we eventually transform this to ES5.
82191             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
82192             if (emitSuperHelpers) {
82193                 enableSubstitutionForAsyncMethodsWithSuper();
82194                 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
82195                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
82196                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
82197             }
82198             statements.push(returnStatement);
82199             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82200             var block = ts.updateBlock(node.body, statements);
82201             if (emitSuperHelpers && hasSuperElementAccess) {
82202                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
82203                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
82204                 }
82205                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
82206                     ts.addEmitHelper(block, ts.asyncSuperHelper);
82207                 }
82208             }
82209             capturedSuperProperties = savedCapturedSuperProperties;
82210             hasSuperElementAccess = savedHasSuperElementAccess;
82211             return block;
82212         }
82213         function transformFunctionBody(node) {
82214             resumeLexicalEnvironment();
82215             var statementOffset = 0;
82216             var statements = [];
82217             var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
82218             if (ts.isBlock(body)) {
82219                 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
82220             }
82221             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
82222             var leadingStatements = endLexicalEnvironment();
82223             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
82224                 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
82225                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
82226                 ts.addRange(statements, block.statements.slice(statementOffset));
82227                 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
82228             }
82229             return body;
82230         }
82231         function appendObjectRestAssignmentsIfNeeded(statements, node) {
82232             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
82233                 var parameter = _a[_i];
82234                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82235                     var temp = ts.getGeneratedNameForNode(parameter);
82236                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
82237                     /*doNotRecordTempVariablesInLine*/ false, 
82238                     /*skipInitializer*/ true);
82239                     if (ts.some(declarations)) {
82240                         var statement = ts.createVariableStatement(
82241                         /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
82242                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
82243                         statements = ts.append(statements, statement);
82244                     }
82245                 }
82246             }
82247             return statements;
82248         }
82249         function enableSubstitutionForAsyncMethodsWithSuper() {
82250             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
82251                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
82252                 // We need to enable substitutions for call, property access, and element access
82253                 // if we need to rewrite super calls.
82254                 context.enableSubstitution(196 /* CallExpression */);
82255                 context.enableSubstitution(194 /* PropertyAccessExpression */);
82256                 context.enableSubstitution(195 /* ElementAccessExpression */);
82257                 // We need to be notified when entering and exiting declarations that bind super.
82258                 context.enableEmitNotification(245 /* ClassDeclaration */);
82259                 context.enableEmitNotification(161 /* MethodDeclaration */);
82260                 context.enableEmitNotification(163 /* GetAccessor */);
82261                 context.enableEmitNotification(164 /* SetAccessor */);
82262                 context.enableEmitNotification(162 /* Constructor */);
82263                 // We need to be notified when entering the generated accessor arrow functions.
82264                 context.enableEmitNotification(225 /* VariableStatement */);
82265             }
82266         }
82267         /**
82268          * Called by the printer just before a node is printed.
82269          *
82270          * @param hint A hint as to the intended usage of the node.
82271          * @param node The node to be printed.
82272          * @param emitCallback The callback used to emit the node.
82273          */
82274         function onEmitNode(hint, node, emitCallback) {
82275             // If we need to support substitutions for `super` in an async method,
82276             // we should track it here.
82277             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
82278                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
82279                 if (superContainerFlags !== enclosingSuperContainerFlags) {
82280                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82281                     enclosingSuperContainerFlags = superContainerFlags;
82282                     previousOnEmitNode(hint, node, emitCallback);
82283                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82284                     return;
82285                 }
82286             }
82287             // Disable substitution in the generated super accessor itself.
82288             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
82289                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82290                 enclosingSuperContainerFlags = 0;
82291                 previousOnEmitNode(hint, node, emitCallback);
82292                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82293                 return;
82294             }
82295             previousOnEmitNode(hint, node, emitCallback);
82296         }
82297         /**
82298          * Hooks node substitutions.
82299          *
82300          * @param hint The context for the emitter.
82301          * @param node The node to substitute.
82302          */
82303         function onSubstituteNode(hint, node) {
82304             node = previousOnSubstituteNode(hint, node);
82305             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
82306                 return substituteExpression(node);
82307             }
82308             return node;
82309         }
82310         function substituteExpression(node) {
82311             switch (node.kind) {
82312                 case 194 /* PropertyAccessExpression */:
82313                     return substitutePropertyAccessExpression(node);
82314                 case 195 /* ElementAccessExpression */:
82315                     return substituteElementAccessExpression(node);
82316                 case 196 /* CallExpression */:
82317                     return substituteCallExpression(node);
82318             }
82319             return node;
82320         }
82321         function substitutePropertyAccessExpression(node) {
82322             if (node.expression.kind === 102 /* SuperKeyword */) {
82323                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
82324             }
82325             return node;
82326         }
82327         function substituteElementAccessExpression(node) {
82328             if (node.expression.kind === 102 /* SuperKeyword */) {
82329                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
82330             }
82331             return node;
82332         }
82333         function substituteCallExpression(node) {
82334             var expression = node.expression;
82335             if (ts.isSuperProperty(expression)) {
82336                 var argumentExpression = ts.isPropertyAccessExpression(expression)
82337                     ? substitutePropertyAccessExpression(expression)
82338                     : substituteElementAccessExpression(expression);
82339                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
82340                 /*typeArguments*/ undefined, __spreadArrays([
82341                     ts.createThis()
82342                 ], node.arguments));
82343             }
82344             return node;
82345         }
82346         function isSuperContainer(node) {
82347             var kind = node.kind;
82348             return kind === 245 /* ClassDeclaration */
82349                 || kind === 162 /* Constructor */
82350                 || kind === 161 /* MethodDeclaration */
82351                 || kind === 163 /* GetAccessor */
82352                 || kind === 164 /* SetAccessor */;
82353         }
82354         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
82355             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
82356                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), 
82357                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
82358             }
82359             else {
82360                 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), 
82361                 /*typeArguments*/ undefined, [argumentExpression]), location);
82362             }
82363         }
82364     }
82365     ts.transformES2018 = transformES2018;
82366     ts.assignHelper = {
82367         name: "typescript:assign",
82368         importName: "__assign",
82369         scoped: false,
82370         priority: 1,
82371         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            };"
82372     };
82373     function createAssignHelper(context, attributesSegments) {
82374         if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
82375             return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
82376         }
82377         context.requestEmitHelper(ts.assignHelper);
82378         return ts.createCall(ts.getUnscopedHelperName("__assign"), 
82379         /*typeArguments*/ undefined, attributesSegments);
82380     }
82381     ts.createAssignHelper = createAssignHelper;
82382     ts.awaitHelper = {
82383         name: "typescript:await",
82384         importName: "__await",
82385         scoped: false,
82386         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
82387     };
82388     function createAwaitHelper(context, expression) {
82389         context.requestEmitHelper(ts.awaitHelper);
82390         return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
82391     }
82392     ts.asyncGeneratorHelper = {
82393         name: "typescript:asyncGenerator",
82394         importName: "__asyncGenerator",
82395         scoped: false,
82396         dependencies: [ts.awaitHelper],
82397         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            };"
82398     };
82399     function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
82400         context.requestEmitHelper(ts.asyncGeneratorHelper);
82401         // Mark this node as originally an async function
82402         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
82403         return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), 
82404         /*typeArguments*/ undefined, [
82405             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
82406             ts.createIdentifier("arguments"),
82407             generatorFunc
82408         ]);
82409     }
82410     ts.asyncDelegator = {
82411         name: "typescript:asyncDelegator",
82412         importName: "__asyncDelegator",
82413         scoped: false,
82414         dependencies: [ts.awaitHelper],
82415         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            };"
82416     };
82417     function createAsyncDelegatorHelper(context, expression, location) {
82418         context.requestEmitHelper(ts.asyncDelegator);
82419         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), 
82420         /*typeArguments*/ undefined, [expression]), location);
82421     }
82422     ts.asyncValues = {
82423         name: "typescript:asyncValues",
82424         importName: "__asyncValues",
82425         scoped: false,
82426         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            };"
82427     };
82428     function createAsyncValuesHelper(context, expression, location) {
82429         context.requestEmitHelper(ts.asyncValues);
82430         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"), 
82431         /*typeArguments*/ undefined, [expression]), location);
82432     }
82433 })(ts || (ts = {}));
82434 /*@internal*/
82435 var ts;
82436 (function (ts) {
82437     function transformES2019(context) {
82438         return ts.chainBundle(transformSourceFile);
82439         function transformSourceFile(node) {
82440             if (node.isDeclarationFile) {
82441                 return node;
82442             }
82443             return ts.visitEachChild(node, visitor, context);
82444         }
82445         function visitor(node) {
82446             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
82447                 return node;
82448             }
82449             switch (node.kind) {
82450                 case 280 /* CatchClause */:
82451                     return visitCatchClause(node);
82452                 default:
82453                     return ts.visitEachChild(node, visitor, context);
82454             }
82455         }
82456         function visitCatchClause(node) {
82457             if (!node.variableDeclaration) {
82458                 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
82459             }
82460             return ts.visitEachChild(node, visitor, context);
82461         }
82462     }
82463     ts.transformES2019 = transformES2019;
82464 })(ts || (ts = {}));
82465 /*@internal*/
82466 var ts;
82467 (function (ts) {
82468     function transformES2020(context) {
82469         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82470         return ts.chainBundle(transformSourceFile);
82471         function transformSourceFile(node) {
82472             if (node.isDeclarationFile) {
82473                 return node;
82474             }
82475             return ts.visitEachChild(node, visitor, context);
82476         }
82477         function visitor(node) {
82478             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
82479                 return node;
82480             }
82481             switch (node.kind) {
82482                 case 194 /* PropertyAccessExpression */:
82483                 case 195 /* ElementAccessExpression */:
82484                 case 196 /* CallExpression */:
82485                     if (node.flags & 32 /* OptionalChain */) {
82486                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
82487                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
82488                         return updated;
82489                     }
82490                     return ts.visitEachChild(node, visitor, context);
82491                 case 209 /* BinaryExpression */:
82492                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
82493                         return transformNullishCoalescingExpression(node);
82494                     }
82495                     return ts.visitEachChild(node, visitor, context);
82496                 case 203 /* DeleteExpression */:
82497                     return visitDeleteExpression(node);
82498                 default:
82499                     return ts.visitEachChild(node, visitor, context);
82500             }
82501         }
82502         function flattenChain(chain) {
82503             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82504             var links = [chain];
82505             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
82506                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
82507                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82508                 links.unshift(chain);
82509             }
82510             return { expression: chain.expression, chain: links };
82511         }
82512         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
82513             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
82514             if (ts.isSyntheticReference(expression)) {
82515                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
82516                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
82517                 return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
82518             }
82519             return ts.updateParen(node, expression);
82520         }
82521         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
82522             if (ts.isOptionalChain(node)) {
82523                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82524                 return visitOptionalExpression(node, captureThisArg, isDelete);
82525             }
82526             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82527             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
82528             var thisArg;
82529             if (captureThisArg) {
82530                 if (shouldCaptureInTempVariable(expression)) {
82531                     thisArg = ts.createTempVariable(hoistVariableDeclaration);
82532                     expression = ts.createAssignment(thisArg, expression);
82533                     // if (inParameterInitializer) tempVariableInParameter = true;
82534                 }
82535                 else {
82536                     thisArg = expression;
82537                 }
82538             }
82539             expression = node.kind === 194 /* PropertyAccessExpression */
82540                 ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
82541                 : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
82542             return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
82543         }
82544         function visitNonOptionalCallExpression(node, captureThisArg) {
82545             if (ts.isOptionalChain(node)) {
82546                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82547                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
82548             }
82549             return ts.visitEachChild(node, visitor, context);
82550         }
82551         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
82552             switch (node.kind) {
82553                 case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
82554                 case 194 /* PropertyAccessExpression */:
82555                 case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
82556                 case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
82557                 default: return ts.visitNode(node, visitor, ts.isExpression);
82558             }
82559         }
82560         function visitOptionalExpression(node, captureThisArg, isDelete) {
82561             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
82562             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
82563             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
82564             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
82565             var capturedLeft = leftExpression;
82566             if (shouldCaptureInTempVariable(leftExpression)) {
82567                 capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
82568                 leftExpression = ts.createAssignment(capturedLeft, leftExpression);
82569                 // if (inParameterInitializer) tempVariableInParameter = true;
82570             }
82571             var rightExpression = capturedLeft;
82572             var thisArg;
82573             for (var i = 0; i < chain.length; i++) {
82574                 var segment = chain[i];
82575                 switch (segment.kind) {
82576                     case 194 /* PropertyAccessExpression */:
82577                     case 195 /* ElementAccessExpression */:
82578                         if (i === chain.length - 1 && captureThisArg) {
82579                             if (shouldCaptureInTempVariable(rightExpression)) {
82580                                 thisArg = ts.createTempVariable(hoistVariableDeclaration);
82581                                 rightExpression = ts.createAssignment(thisArg, rightExpression);
82582                                 // if (inParameterInitializer) tempVariableInParameter = true;
82583                             }
82584                             else {
82585                                 thisArg = rightExpression;
82586                             }
82587                         }
82588                         rightExpression = segment.kind === 194 /* PropertyAccessExpression */
82589                             ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
82590                             : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
82591                         break;
82592                     case 196 /* CallExpression */:
82593                         if (i === 0 && leftThisArg) {
82594                             rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82595                         }
82596                         else {
82597                             rightExpression = ts.createCall(rightExpression, 
82598                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82599                         }
82600                         break;
82601                 }
82602                 ts.setOriginalNode(rightExpression, segment);
82603             }
82604             var target = isDelete
82605                 ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
82606                 : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
82607             return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
82608         }
82609         function createNotNullCondition(left, right, invert) {
82610             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()));
82611         }
82612         function transformNullishCoalescingExpression(node) {
82613             var left = ts.visitNode(node.left, visitor, ts.isExpression);
82614             var right = left;
82615             if (shouldCaptureInTempVariable(left)) {
82616                 right = ts.createTempVariable(hoistVariableDeclaration);
82617                 left = ts.createAssignment(right, left);
82618                 // if (inParameterInitializer) tempVariableInParameter = true;
82619             }
82620             return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
82621         }
82622         function shouldCaptureInTempVariable(expression) {
82623             // don't capture identifiers and `this` in a temporary variable
82624             // `super` cannot be captured as it's no real variable
82625             return !ts.isIdentifier(expression) &&
82626                 expression.kind !== 104 /* ThisKeyword */ &&
82627                 expression.kind !== 102 /* SuperKeyword */;
82628         }
82629         function visitDeleteExpression(node) {
82630             return ts.isOptionalChain(ts.skipParentheses(node.expression))
82631                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
82632                 : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
82633         }
82634     }
82635     ts.transformES2020 = transformES2020;
82636 })(ts || (ts = {}));
82637 /*@internal*/
82638 var ts;
82639 (function (ts) {
82640     function transformESNext(context) {
82641         return ts.chainBundle(transformSourceFile);
82642         function transformSourceFile(node) {
82643             if (node.isDeclarationFile) {
82644                 return node;
82645             }
82646             return ts.visitEachChild(node, visitor, context);
82647         }
82648         function visitor(node) {
82649             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
82650                 return node;
82651             }
82652             switch (node.kind) {
82653                 default:
82654                     return ts.visitEachChild(node, visitor, context);
82655             }
82656         }
82657     }
82658     ts.transformESNext = transformESNext;
82659 })(ts || (ts = {}));
82660 /*@internal*/
82661 var ts;
82662 (function (ts) {
82663     function transformJsx(context) {
82664         var compilerOptions = context.getCompilerOptions();
82665         var currentSourceFile;
82666         return ts.chainBundle(transformSourceFile);
82667         /**
82668          * Transform JSX-specific syntax in a SourceFile.
82669          *
82670          * @param node A SourceFile node.
82671          */
82672         function transformSourceFile(node) {
82673             if (node.isDeclarationFile) {
82674                 return node;
82675             }
82676             currentSourceFile = node;
82677             var visited = ts.visitEachChild(node, visitor, context);
82678             ts.addEmitHelpers(visited, context.readEmitHelpers());
82679             return visited;
82680         }
82681         function visitor(node) {
82682             if (node.transformFlags & 2 /* ContainsJsx */) {
82683                 return visitorWorker(node);
82684             }
82685             else {
82686                 return node;
82687             }
82688         }
82689         function visitorWorker(node) {
82690             switch (node.kind) {
82691                 case 266 /* JsxElement */:
82692                     return visitJsxElement(node, /*isChild*/ false);
82693                 case 267 /* JsxSelfClosingElement */:
82694                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
82695                 case 270 /* JsxFragment */:
82696                     return visitJsxFragment(node, /*isChild*/ false);
82697                 case 276 /* JsxExpression */:
82698                     return visitJsxExpression(node);
82699                 default:
82700                     return ts.visitEachChild(node, visitor, context);
82701             }
82702         }
82703         function transformJsxChildToExpression(node) {
82704             switch (node.kind) {
82705                 case 11 /* JsxText */:
82706                     return visitJsxText(node);
82707                 case 276 /* JsxExpression */:
82708                     return visitJsxExpression(node);
82709                 case 266 /* JsxElement */:
82710                     return visitJsxElement(node, /*isChild*/ true);
82711                 case 267 /* JsxSelfClosingElement */:
82712                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
82713                 case 270 /* JsxFragment */:
82714                     return visitJsxFragment(node, /*isChild*/ true);
82715                 default:
82716                     return ts.Debug.failBadSyntaxKind(node);
82717             }
82718         }
82719         function visitJsxElement(node, isChild) {
82720             return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
82721         }
82722         function visitJsxSelfClosingElement(node, isChild) {
82723             return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
82724         }
82725         function visitJsxFragment(node, isChild) {
82726             return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
82727         }
82728         function visitJsxOpeningLikeElement(node, children, isChild, location) {
82729             var tagName = getTagName(node);
82730             var objectProperties;
82731             var attrs = node.attributes.properties;
82732             if (attrs.length === 0) {
82733                 // When there are no attributes, React wants "null"
82734                 objectProperties = ts.createNull();
82735             }
82736             else {
82737                 // Map spans of JsxAttribute nodes into object literals and spans
82738                 // of JsxSpreadAttribute nodes into expressions.
82739                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
82740                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
82741                     : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
82742                 if (ts.isJsxSpreadAttribute(attrs[0])) {
82743                     // We must always emit at least one object literal before a spread
82744                     // argument.
82745                     segments.unshift(ts.createObjectLiteral());
82746                 }
82747                 // Either emit one big object literal (no spread attribs), or
82748                 // a call to the __assign helper.
82749                 objectProperties = ts.singleOrUndefined(segments);
82750                 if (!objectProperties) {
82751                     objectProperties = ts.createAssignHelper(context, segments);
82752                 }
82753             }
82754             var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82755             tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
82756             if (isChild) {
82757                 ts.startOnNewLine(element);
82758             }
82759             return element;
82760         }
82761         function visitJsxOpeningFragment(node, children, isChild, location) {
82762             var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82763             ts.mapDefined(children, transformJsxChildToExpression), node, location);
82764             if (isChild) {
82765                 ts.startOnNewLine(element);
82766             }
82767             return element;
82768         }
82769         function transformJsxSpreadAttributeToExpression(node) {
82770             return ts.visitNode(node.expression, visitor, ts.isExpression);
82771         }
82772         function transformJsxAttributeToObjectLiteralElement(node) {
82773             var name = getAttributeName(node);
82774             var expression = transformJsxAttributeInitializer(node.initializer);
82775             return ts.createPropertyAssignment(name, expression);
82776         }
82777         function transformJsxAttributeInitializer(node) {
82778             if (node === undefined) {
82779                 return ts.createTrue();
82780             }
82781             else if (node.kind === 10 /* StringLiteral */) {
82782                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
82783                 // Need to be escaped to be handled correctly in a normal string
82784                 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
82785                 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
82786                 return ts.setTextRange(literal, node);
82787             }
82788             else if (node.kind === 276 /* JsxExpression */) {
82789                 if (node.expression === undefined) {
82790                     return ts.createTrue();
82791                 }
82792                 return visitJsxExpression(node);
82793             }
82794             else {
82795                 return ts.Debug.failBadSyntaxKind(node);
82796             }
82797         }
82798         function visitJsxText(node) {
82799             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
82800             return fixed === undefined ? undefined : ts.createLiteral(fixed);
82801         }
82802         /**
82803          * JSX trims whitespace at the end and beginning of lines, except that the
82804          * start/end of a tag is considered a start/end of a line only if that line is
82805          * on the same line as the closing tag. See examples in
82806          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
82807          * 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
82808          *
82809          * An equivalent algorithm would be:
82810          * - If there is only one line, return it.
82811          * - If there is only whitespace (but multiple lines), return `undefined`.
82812          * - Split the text into lines.
82813          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
82814          * - Decode entities on each line (individually).
82815          * - Remove empty lines and join the rest with " ".
82816          */
82817         function fixupWhitespaceAndDecodeEntities(text) {
82818             var acc;
82819             // First non-whitespace character on this line.
82820             var firstNonWhitespace = 0;
82821             // Last non-whitespace character on this line.
82822             var lastNonWhitespace = -1;
82823             // These initial values are special because the first line is:
82824             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
82825             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
82826             for (var i = 0; i < text.length; i++) {
82827                 var c = text.charCodeAt(i);
82828                 if (ts.isLineBreak(c)) {
82829                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
82830                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
82831                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
82832                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
82833                     }
82834                     // Reset firstNonWhitespace for the next line.
82835                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
82836                     firstNonWhitespace = -1;
82837                 }
82838                 else if (!ts.isWhiteSpaceSingleLine(c)) {
82839                     lastNonWhitespace = i;
82840                     if (firstNonWhitespace === -1) {
82841                         firstNonWhitespace = i;
82842                     }
82843                 }
82844             }
82845             return firstNonWhitespace !== -1
82846                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
82847                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
82848                 // Last line was all whitespace, so ignore it
82849                 : acc;
82850         }
82851         function addLineOfJsxText(acc, trimmedLine) {
82852             // We do not escape the string here as that is handled by the printer
82853             // when it emits the literal. We do, however, need to decode JSX entities.
82854             var decoded = decodeEntities(trimmedLine);
82855             return acc === undefined ? decoded : acc + " " + decoded;
82856         }
82857         /**
82858          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
82859          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
82860          */
82861         function decodeEntities(text) {
82862             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
82863                 if (decimal) {
82864                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
82865                 }
82866                 else if (hex) {
82867                     return ts.utf16EncodeAsString(parseInt(hex, 16));
82868                 }
82869                 else {
82870                     var ch = entities.get(word);
82871                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
82872                     return ch ? ts.utf16EncodeAsString(ch) : match;
82873                 }
82874             });
82875         }
82876         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
82877         function tryDecodeEntities(text) {
82878             var decoded = decodeEntities(text);
82879             return decoded === text ? undefined : decoded;
82880         }
82881         function getTagName(node) {
82882             if (node.kind === 266 /* JsxElement */) {
82883                 return getTagName(node.openingElement);
82884             }
82885             else {
82886                 var name = node.tagName;
82887                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
82888                     return ts.createLiteral(ts.idText(name));
82889                 }
82890                 else {
82891                     return ts.createExpressionFromEntityName(name);
82892                 }
82893             }
82894         }
82895         /**
82896          * Emit an attribute name, which is quoted if it needs to be quoted. Because
82897          * these emit into an object literal property name, we don't need to be worried
82898          * about keywords, just non-identifier characters
82899          */
82900         function getAttributeName(node) {
82901             var name = node.name;
82902             var text = ts.idText(name);
82903             if (/^[A-Za-z_]\w*$/.test(text)) {
82904                 return name;
82905             }
82906             else {
82907                 return ts.createLiteral(text);
82908             }
82909         }
82910         function visitJsxExpression(node) {
82911             return ts.visitNode(node.expression, visitor, ts.isExpression);
82912         }
82913     }
82914     ts.transformJsx = transformJsx;
82915     var entities = ts.createMapFromTemplate({
82916         quot: 0x0022,
82917         amp: 0x0026,
82918         apos: 0x0027,
82919         lt: 0x003C,
82920         gt: 0x003E,
82921         nbsp: 0x00A0,
82922         iexcl: 0x00A1,
82923         cent: 0x00A2,
82924         pound: 0x00A3,
82925         curren: 0x00A4,
82926         yen: 0x00A5,
82927         brvbar: 0x00A6,
82928         sect: 0x00A7,
82929         uml: 0x00A8,
82930         copy: 0x00A9,
82931         ordf: 0x00AA,
82932         laquo: 0x00AB,
82933         not: 0x00AC,
82934         shy: 0x00AD,
82935         reg: 0x00AE,
82936         macr: 0x00AF,
82937         deg: 0x00B0,
82938         plusmn: 0x00B1,
82939         sup2: 0x00B2,
82940         sup3: 0x00B3,
82941         acute: 0x00B4,
82942         micro: 0x00B5,
82943         para: 0x00B6,
82944         middot: 0x00B7,
82945         cedil: 0x00B8,
82946         sup1: 0x00B9,
82947         ordm: 0x00BA,
82948         raquo: 0x00BB,
82949         frac14: 0x00BC,
82950         frac12: 0x00BD,
82951         frac34: 0x00BE,
82952         iquest: 0x00BF,
82953         Agrave: 0x00C0,
82954         Aacute: 0x00C1,
82955         Acirc: 0x00C2,
82956         Atilde: 0x00C3,
82957         Auml: 0x00C4,
82958         Aring: 0x00C5,
82959         AElig: 0x00C6,
82960         Ccedil: 0x00C7,
82961         Egrave: 0x00C8,
82962         Eacute: 0x00C9,
82963         Ecirc: 0x00CA,
82964         Euml: 0x00CB,
82965         Igrave: 0x00CC,
82966         Iacute: 0x00CD,
82967         Icirc: 0x00CE,
82968         Iuml: 0x00CF,
82969         ETH: 0x00D0,
82970         Ntilde: 0x00D1,
82971         Ograve: 0x00D2,
82972         Oacute: 0x00D3,
82973         Ocirc: 0x00D4,
82974         Otilde: 0x00D5,
82975         Ouml: 0x00D6,
82976         times: 0x00D7,
82977         Oslash: 0x00D8,
82978         Ugrave: 0x00D9,
82979         Uacute: 0x00DA,
82980         Ucirc: 0x00DB,
82981         Uuml: 0x00DC,
82982         Yacute: 0x00DD,
82983         THORN: 0x00DE,
82984         szlig: 0x00DF,
82985         agrave: 0x00E0,
82986         aacute: 0x00E1,
82987         acirc: 0x00E2,
82988         atilde: 0x00E3,
82989         auml: 0x00E4,
82990         aring: 0x00E5,
82991         aelig: 0x00E6,
82992         ccedil: 0x00E7,
82993         egrave: 0x00E8,
82994         eacute: 0x00E9,
82995         ecirc: 0x00EA,
82996         euml: 0x00EB,
82997         igrave: 0x00EC,
82998         iacute: 0x00ED,
82999         icirc: 0x00EE,
83000         iuml: 0x00EF,
83001         eth: 0x00F0,
83002         ntilde: 0x00F1,
83003         ograve: 0x00F2,
83004         oacute: 0x00F3,
83005         ocirc: 0x00F4,
83006         otilde: 0x00F5,
83007         ouml: 0x00F6,
83008         divide: 0x00F7,
83009         oslash: 0x00F8,
83010         ugrave: 0x00F9,
83011         uacute: 0x00FA,
83012         ucirc: 0x00FB,
83013         uuml: 0x00FC,
83014         yacute: 0x00FD,
83015         thorn: 0x00FE,
83016         yuml: 0x00FF,
83017         OElig: 0x0152,
83018         oelig: 0x0153,
83019         Scaron: 0x0160,
83020         scaron: 0x0161,
83021         Yuml: 0x0178,
83022         fnof: 0x0192,
83023         circ: 0x02C6,
83024         tilde: 0x02DC,
83025         Alpha: 0x0391,
83026         Beta: 0x0392,
83027         Gamma: 0x0393,
83028         Delta: 0x0394,
83029         Epsilon: 0x0395,
83030         Zeta: 0x0396,
83031         Eta: 0x0397,
83032         Theta: 0x0398,
83033         Iota: 0x0399,
83034         Kappa: 0x039A,
83035         Lambda: 0x039B,
83036         Mu: 0x039C,
83037         Nu: 0x039D,
83038         Xi: 0x039E,
83039         Omicron: 0x039F,
83040         Pi: 0x03A0,
83041         Rho: 0x03A1,
83042         Sigma: 0x03A3,
83043         Tau: 0x03A4,
83044         Upsilon: 0x03A5,
83045         Phi: 0x03A6,
83046         Chi: 0x03A7,
83047         Psi: 0x03A8,
83048         Omega: 0x03A9,
83049         alpha: 0x03B1,
83050         beta: 0x03B2,
83051         gamma: 0x03B3,
83052         delta: 0x03B4,
83053         epsilon: 0x03B5,
83054         zeta: 0x03B6,
83055         eta: 0x03B7,
83056         theta: 0x03B8,
83057         iota: 0x03B9,
83058         kappa: 0x03BA,
83059         lambda: 0x03BB,
83060         mu: 0x03BC,
83061         nu: 0x03BD,
83062         xi: 0x03BE,
83063         omicron: 0x03BF,
83064         pi: 0x03C0,
83065         rho: 0x03C1,
83066         sigmaf: 0x03C2,
83067         sigma: 0x03C3,
83068         tau: 0x03C4,
83069         upsilon: 0x03C5,
83070         phi: 0x03C6,
83071         chi: 0x03C7,
83072         psi: 0x03C8,
83073         omega: 0x03C9,
83074         thetasym: 0x03D1,
83075         upsih: 0x03D2,
83076         piv: 0x03D6,
83077         ensp: 0x2002,
83078         emsp: 0x2003,
83079         thinsp: 0x2009,
83080         zwnj: 0x200C,
83081         zwj: 0x200D,
83082         lrm: 0x200E,
83083         rlm: 0x200F,
83084         ndash: 0x2013,
83085         mdash: 0x2014,
83086         lsquo: 0x2018,
83087         rsquo: 0x2019,
83088         sbquo: 0x201A,
83089         ldquo: 0x201C,
83090         rdquo: 0x201D,
83091         bdquo: 0x201E,
83092         dagger: 0x2020,
83093         Dagger: 0x2021,
83094         bull: 0x2022,
83095         hellip: 0x2026,
83096         permil: 0x2030,
83097         prime: 0x2032,
83098         Prime: 0x2033,
83099         lsaquo: 0x2039,
83100         rsaquo: 0x203A,
83101         oline: 0x203E,
83102         frasl: 0x2044,
83103         euro: 0x20AC,
83104         image: 0x2111,
83105         weierp: 0x2118,
83106         real: 0x211C,
83107         trade: 0x2122,
83108         alefsym: 0x2135,
83109         larr: 0x2190,
83110         uarr: 0x2191,
83111         rarr: 0x2192,
83112         darr: 0x2193,
83113         harr: 0x2194,
83114         crarr: 0x21B5,
83115         lArr: 0x21D0,
83116         uArr: 0x21D1,
83117         rArr: 0x21D2,
83118         dArr: 0x21D3,
83119         hArr: 0x21D4,
83120         forall: 0x2200,
83121         part: 0x2202,
83122         exist: 0x2203,
83123         empty: 0x2205,
83124         nabla: 0x2207,
83125         isin: 0x2208,
83126         notin: 0x2209,
83127         ni: 0x220B,
83128         prod: 0x220F,
83129         sum: 0x2211,
83130         minus: 0x2212,
83131         lowast: 0x2217,
83132         radic: 0x221A,
83133         prop: 0x221D,
83134         infin: 0x221E,
83135         ang: 0x2220,
83136         and: 0x2227,
83137         or: 0x2228,
83138         cap: 0x2229,
83139         cup: 0x222A,
83140         int: 0x222B,
83141         there4: 0x2234,
83142         sim: 0x223C,
83143         cong: 0x2245,
83144         asymp: 0x2248,
83145         ne: 0x2260,
83146         equiv: 0x2261,
83147         le: 0x2264,
83148         ge: 0x2265,
83149         sub: 0x2282,
83150         sup: 0x2283,
83151         nsub: 0x2284,
83152         sube: 0x2286,
83153         supe: 0x2287,
83154         oplus: 0x2295,
83155         otimes: 0x2297,
83156         perp: 0x22A5,
83157         sdot: 0x22C5,
83158         lceil: 0x2308,
83159         rceil: 0x2309,
83160         lfloor: 0x230A,
83161         rfloor: 0x230B,
83162         lang: 0x2329,
83163         rang: 0x232A,
83164         loz: 0x25CA,
83165         spades: 0x2660,
83166         clubs: 0x2663,
83167         hearts: 0x2665,
83168         diams: 0x2666
83169     });
83170 })(ts || (ts = {}));
83171 /*@internal*/
83172 var ts;
83173 (function (ts) {
83174     function transformES2016(context) {
83175         var hoistVariableDeclaration = context.hoistVariableDeclaration;
83176         return ts.chainBundle(transformSourceFile);
83177         function transformSourceFile(node) {
83178             if (node.isDeclarationFile) {
83179                 return node;
83180             }
83181             return ts.visitEachChild(node, visitor, context);
83182         }
83183         function visitor(node) {
83184             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
83185                 return node;
83186             }
83187             switch (node.kind) {
83188                 case 209 /* BinaryExpression */:
83189                     return visitBinaryExpression(node);
83190                 default:
83191                     return ts.visitEachChild(node, visitor, context);
83192             }
83193         }
83194         function visitBinaryExpression(node) {
83195             switch (node.operatorToken.kind) {
83196                 case 66 /* AsteriskAsteriskEqualsToken */:
83197                     return visitExponentiationAssignmentExpression(node);
83198                 case 42 /* AsteriskAsteriskToken */:
83199                     return visitExponentiationExpression(node);
83200                 default:
83201                     return ts.visitEachChild(node, visitor, context);
83202             }
83203         }
83204         function visitExponentiationAssignmentExpression(node) {
83205             var target;
83206             var value;
83207             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83208             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83209             if (ts.isElementAccessExpression(left)) {
83210                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
83211                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83212                 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83213                 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
83214                 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
83215             }
83216             else if (ts.isPropertyAccessExpression(left)) {
83217                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
83218                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83219                 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
83220                 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
83221             }
83222             else {
83223                 // Transforms `a **= b` into `a = Math.pow(a, b)`
83224                 target = left;
83225                 value = left;
83226             }
83227             return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
83228         }
83229         function visitExponentiationExpression(node) {
83230             // Transforms `a ** b` into `Math.pow(a, b)`
83231             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83232             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83233             return ts.createMathPow(left, right, /*location*/ node);
83234         }
83235     }
83236     ts.transformES2016 = transformES2016;
83237 })(ts || (ts = {}));
83238 /*@internal*/
83239 var ts;
83240 (function (ts) {
83241     var ES2015SubstitutionFlags;
83242     (function (ES2015SubstitutionFlags) {
83243         /** Enables substitutions for captured `this` */
83244         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
83245         /** Enables substitutions for block-scoped bindings. */
83246         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
83247     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
83248     var LoopOutParameterFlags;
83249     (function (LoopOutParameterFlags) {
83250         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
83251         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
83252     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
83253     var CopyDirection;
83254     (function (CopyDirection) {
83255         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
83256         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
83257     })(CopyDirection || (CopyDirection = {}));
83258     var Jump;
83259     (function (Jump) {
83260         Jump[Jump["Break"] = 2] = "Break";
83261         Jump[Jump["Continue"] = 4] = "Continue";
83262         Jump[Jump["Return"] = 8] = "Return";
83263     })(Jump || (Jump = {}));
83264     // Facts we track as we traverse the tree
83265     var HierarchyFacts;
83266     (function (HierarchyFacts) {
83267         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
83268         //
83269         // Ancestor facts
83270         //
83271         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
83272         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
83273         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
83274         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
83275         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
83276         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
83277         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
83278         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
83279         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
83280         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
83281         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
83282         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
83283         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
83284         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
83285         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
83286         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
83287         //
83288         // Ancestor masks
83289         //
83290         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
83291         // We are always in *some* kind of block scope, but only specific block-scope containers are
83292         // top-level or Blocks.
83293         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
83294         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
83295         // A source file is a top-level block scope.
83296         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
83297         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
83298         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
83299         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
83300         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
83301         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
83302         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
83303         // Arrow functions are lexically scoped to their container, but are new block scopes.
83304         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
83305         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
83306         // Constructors are both new lexical scopes and new block scopes. Constructors are also
83307         // always considered non-static members of a class.
83308         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
83309         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
83310         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
83311         // within an IterationStatement to indicate whether the embedded statement is an
83312         // IterationStatementBlock.
83313         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
83314         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
83315         // 'for' statements are new block scopes and have special handling for 'let' declarations.
83316         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
83317         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
83318         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
83319         // 'let' declarations.
83320         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
83321         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
83322         // Blocks (other than function bodies) are new block scopes.
83323         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
83324         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
83325         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
83326         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
83327         //
83328         // Subtree facts
83329         //
83330         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
83331         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
83332         //
83333         // Subtree masks
83334         //
83335         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
83336         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
83337         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
83338     })(HierarchyFacts || (HierarchyFacts = {}));
83339     function transformES2015(context) {
83340         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83341         var compilerOptions = context.getCompilerOptions();
83342         var resolver = context.getEmitResolver();
83343         var previousOnSubstituteNode = context.onSubstituteNode;
83344         var previousOnEmitNode = context.onEmitNode;
83345         context.onEmitNode = onEmitNode;
83346         context.onSubstituteNode = onSubstituteNode;
83347         var currentSourceFile;
83348         var currentText;
83349         var hierarchyFacts;
83350         var taggedTemplateStringDeclarations;
83351         function recordTaggedTemplateString(temp) {
83352             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
83353         }
83354         /**
83355          * Used to track if we are emitting body of the converted loop
83356          */
83357         var convertedLoopState;
83358         /**
83359          * Keeps track of whether substitutions have been enabled for specific cases.
83360          * They are persisted between each SourceFile transformation and should not
83361          * be reset.
83362          */
83363         var enabledSubstitutions;
83364         return ts.chainBundle(transformSourceFile);
83365         function transformSourceFile(node) {
83366             if (node.isDeclarationFile) {
83367                 return node;
83368             }
83369             currentSourceFile = node;
83370             currentText = node.text;
83371             var visited = visitSourceFile(node);
83372             ts.addEmitHelpers(visited, context.readEmitHelpers());
83373             currentSourceFile = undefined;
83374             currentText = undefined;
83375             taggedTemplateStringDeclarations = undefined;
83376             hierarchyFacts = 0 /* None */;
83377             return visited;
83378         }
83379         /**
83380          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
83381          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
83382          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
83383          */
83384         function enterSubtree(excludeFacts, includeFacts) {
83385             var ancestorFacts = hierarchyFacts;
83386             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
83387             return ancestorFacts;
83388         }
83389         /**
83390          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
83391          * subtree, propagating specific facts from the subtree.
83392          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
83393          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
83394          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
83395          */
83396         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
83397             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
83398         }
83399         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
83400             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
83401                 && node.kind === 235 /* ReturnStatement */
83402                 && !node.expression;
83403         }
83404         function shouldVisitNode(node) {
83405             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
83406                 || convertedLoopState !== undefined
83407                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
83408                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
83409                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
83410         }
83411         function visitor(node) {
83412             if (shouldVisitNode(node)) {
83413                 return visitJavaScript(node);
83414             }
83415             else {
83416                 return node;
83417             }
83418         }
83419         function callExpressionVisitor(node) {
83420             if (node.kind === 102 /* SuperKeyword */) {
83421                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
83422             }
83423             return visitor(node);
83424         }
83425         function visitJavaScript(node) {
83426             switch (node.kind) {
83427                 case 120 /* StaticKeyword */:
83428                     return undefined; // elide static keyword
83429                 case 245 /* ClassDeclaration */:
83430                     return visitClassDeclaration(node);
83431                 case 214 /* ClassExpression */:
83432                     return visitClassExpression(node);
83433                 case 156 /* Parameter */:
83434                     return visitParameter(node);
83435                 case 244 /* FunctionDeclaration */:
83436                     return visitFunctionDeclaration(node);
83437                 case 202 /* ArrowFunction */:
83438                     return visitArrowFunction(node);
83439                 case 201 /* FunctionExpression */:
83440                     return visitFunctionExpression(node);
83441                 case 242 /* VariableDeclaration */:
83442                     return visitVariableDeclaration(node);
83443                 case 75 /* Identifier */:
83444                     return visitIdentifier(node);
83445                 case 243 /* VariableDeclarationList */:
83446                     return visitVariableDeclarationList(node);
83447                 case 237 /* SwitchStatement */:
83448                     return visitSwitchStatement(node);
83449                 case 251 /* CaseBlock */:
83450                     return visitCaseBlock(node);
83451                 case 223 /* Block */:
83452                     return visitBlock(node, /*isFunctionBody*/ false);
83453                 case 234 /* BreakStatement */:
83454                 case 233 /* ContinueStatement */:
83455                     return visitBreakOrContinueStatement(node);
83456                 case 238 /* LabeledStatement */:
83457                     return visitLabeledStatement(node);
83458                 case 228 /* DoStatement */:
83459                 case 229 /* WhileStatement */:
83460                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
83461                 case 230 /* ForStatement */:
83462                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
83463                 case 231 /* ForInStatement */:
83464                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
83465                 case 232 /* ForOfStatement */:
83466                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
83467                 case 226 /* ExpressionStatement */:
83468                     return visitExpressionStatement(node);
83469                 case 193 /* ObjectLiteralExpression */:
83470                     return visitObjectLiteralExpression(node);
83471                 case 280 /* CatchClause */:
83472                     return visitCatchClause(node);
83473                 case 282 /* ShorthandPropertyAssignment */:
83474                     return visitShorthandPropertyAssignment(node);
83475                 case 154 /* ComputedPropertyName */:
83476                     return visitComputedPropertyName(node);
83477                 case 192 /* ArrayLiteralExpression */:
83478                     return visitArrayLiteralExpression(node);
83479                 case 196 /* CallExpression */:
83480                     return visitCallExpression(node);
83481                 case 197 /* NewExpression */:
83482                     return visitNewExpression(node);
83483                 case 200 /* ParenthesizedExpression */:
83484                     return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
83485                 case 209 /* BinaryExpression */:
83486                     return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
83487                 case 14 /* NoSubstitutionTemplateLiteral */:
83488                 case 15 /* TemplateHead */:
83489                 case 16 /* TemplateMiddle */:
83490                 case 17 /* TemplateTail */:
83491                     return visitTemplateLiteral(node);
83492                 case 10 /* StringLiteral */:
83493                     return visitStringLiteral(node);
83494                 case 8 /* NumericLiteral */:
83495                     return visitNumericLiteral(node);
83496                 case 198 /* TaggedTemplateExpression */:
83497                     return visitTaggedTemplateExpression(node);
83498                 case 211 /* TemplateExpression */:
83499                     return visitTemplateExpression(node);
83500                 case 212 /* YieldExpression */:
83501                     return visitYieldExpression(node);
83502                 case 213 /* SpreadElement */:
83503                     return visitSpreadElement(node);
83504                 case 102 /* SuperKeyword */:
83505                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
83506                 case 104 /* ThisKeyword */:
83507                     return visitThisKeyword(node);
83508                 case 219 /* MetaProperty */:
83509                     return visitMetaProperty(node);
83510                 case 161 /* MethodDeclaration */:
83511                     return visitMethodDeclaration(node);
83512                 case 163 /* GetAccessor */:
83513                 case 164 /* SetAccessor */:
83514                     return visitAccessorDeclaration(node);
83515                 case 225 /* VariableStatement */:
83516                     return visitVariableStatement(node);
83517                 case 235 /* ReturnStatement */:
83518                     return visitReturnStatement(node);
83519                 default:
83520                     return ts.visitEachChild(node, visitor, context);
83521             }
83522         }
83523         function visitSourceFile(node) {
83524             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
83525             var prologue = [];
83526             var statements = [];
83527             startLexicalEnvironment();
83528             var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
83529             statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
83530             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
83531             if (taggedTemplateStringDeclarations) {
83532                 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
83533             }
83534             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83535             insertCaptureThisForNodeIfNeeded(prologue, node);
83536             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83537             return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
83538         }
83539         function visitSwitchStatement(node) {
83540             if (convertedLoopState !== undefined) {
83541                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
83542                 // for switch statement allow only non-labeled break
83543                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
83544                 var result = ts.visitEachChild(node, visitor, context);
83545                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
83546                 return result;
83547             }
83548             return ts.visitEachChild(node, visitor, context);
83549         }
83550         function visitCaseBlock(node) {
83551             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
83552             var updated = ts.visitEachChild(node, visitor, context);
83553             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83554             return updated;
83555         }
83556         function returnCapturedThis(node) {
83557             return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
83558         }
83559         function visitReturnStatement(node) {
83560             if (convertedLoopState) {
83561                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
83562                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83563                     node = returnCapturedThis(node);
83564                 }
83565                 return ts.createReturn(ts.createObjectLiteral([
83566                     ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
83567                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
83568                         : ts.createVoidZero())
83569                 ]));
83570             }
83571             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83572                 return returnCapturedThis(node);
83573             }
83574             return ts.visitEachChild(node, visitor, context);
83575         }
83576         function visitThisKeyword(node) {
83577             if (hierarchyFacts & 2 /* ArrowFunction */) {
83578                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
83579             }
83580             if (convertedLoopState) {
83581                 if (hierarchyFacts & 2 /* ArrowFunction */) {
83582                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
83583                     convertedLoopState.containsLexicalThis = true;
83584                     return node;
83585                 }
83586                 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
83587             }
83588             return node;
83589         }
83590         function visitIdentifier(node) {
83591             if (!convertedLoopState) {
83592                 return node;
83593             }
83594             if (ts.isGeneratedIdentifier(node)) {
83595                 return node;
83596             }
83597             if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
83598                 return node;
83599             }
83600             return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
83601         }
83602         function visitBreakOrContinueStatement(node) {
83603             if (convertedLoopState) {
83604                 // check if we can emit break/continue as is
83605                 // it is possible if either
83606                 //   - break/continue is labeled and label is located inside the converted loop
83607                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
83608                 var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
83609                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
83610                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
83611                 if (!canUseBreakOrContinue) {
83612                     var labelMarker = void 0;
83613                     var label = node.label;
83614                     if (!label) {
83615                         if (node.kind === 234 /* BreakStatement */) {
83616                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
83617                             labelMarker = "break";
83618                         }
83619                         else {
83620                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
83621                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
83622                             labelMarker = "continue";
83623                         }
83624                     }
83625                     else {
83626                         if (node.kind === 234 /* BreakStatement */) {
83627                             labelMarker = "break-" + label.escapedText;
83628                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
83629                         }
83630                         else {
83631                             labelMarker = "continue-" + label.escapedText;
83632                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
83633                         }
83634                     }
83635                     var returnExpression = ts.createLiteral(labelMarker);
83636                     if (convertedLoopState.loopOutParameters.length) {
83637                         var outParams = convertedLoopState.loopOutParameters;
83638                         var expr = void 0;
83639                         for (var i = 0; i < outParams.length; i++) {
83640                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
83641                             if (i === 0) {
83642                                 expr = copyExpr;
83643                             }
83644                             else {
83645                                 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
83646                             }
83647                         }
83648                         returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
83649                     }
83650                     return ts.createReturn(returnExpression);
83651                 }
83652             }
83653             return ts.visitEachChild(node, visitor, context);
83654         }
83655         /**
83656          * Visits a ClassDeclaration and transforms it into a variable statement.
83657          *
83658          * @param node A ClassDeclaration node.
83659          */
83660         function visitClassDeclaration(node) {
83661             // [source]
83662             //      class C { }
83663             //
83664             // [output]
83665             //      var C = (function () {
83666             //          function C() {
83667             //          }
83668             //          return C;
83669             //      }());
83670             var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
83671             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
83672             ts.setOriginalNode(variable, node);
83673             var statements = [];
83674             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
83675             ts.setOriginalNode(statement, node);
83676             ts.setTextRange(statement, node);
83677             ts.startOnNewLine(statement);
83678             statements.push(statement);
83679             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
83680             if (ts.hasModifier(node, 1 /* Export */)) {
83681                 var exportStatement = ts.hasModifier(node, 512 /* Default */)
83682                     ? ts.createExportDefault(ts.getLocalName(node))
83683                     : ts.createExternalModuleExport(ts.getLocalName(node));
83684                 ts.setOriginalNode(exportStatement, statement);
83685                 statements.push(exportStatement);
83686             }
83687             var emitFlags = ts.getEmitFlags(node);
83688             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
83689                 // Add a DeclarationMarker as a marker for the end of the declaration
83690                 statements.push(ts.createEndOfDeclarationMarker(node));
83691                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
83692             }
83693             return ts.singleOrMany(statements);
83694         }
83695         /**
83696          * Visits a ClassExpression and transforms it into an expression.
83697          *
83698          * @param node A ClassExpression node.
83699          */
83700         function visitClassExpression(node) {
83701             // [source]
83702             //      C = class { }
83703             //
83704             // [output]
83705             //      C = (function () {
83706             //          function class_1() {
83707             //          }
83708             //          return class_1;
83709             //      }())
83710             return transformClassLikeDeclarationToExpression(node);
83711         }
83712         /**
83713          * Transforms a ClassExpression or ClassDeclaration into an expression.
83714          *
83715          * @param node A ClassExpression or ClassDeclaration node.
83716          */
83717         function transformClassLikeDeclarationToExpression(node) {
83718             // [source]
83719             //      class C extends D {
83720             //          constructor() {}
83721             //          method() {}
83722             //          get prop() {}
83723             //          set prop(v) {}
83724             //      }
83725             //
83726             // [output]
83727             //      (function (_super) {
83728             //          __extends(C, _super);
83729             //          function C() {
83730             //          }
83731             //          C.prototype.method = function () {}
83732             //          Object.defineProperty(C.prototype, "prop", {
83733             //              get: function() {},
83734             //              set: function() {},
83735             //              enumerable: true,
83736             //              configurable: true
83737             //          });
83738             //          return C;
83739             //      }(D))
83740             if (node.name) {
83741                 enableSubstitutionsForBlockScopedBindings();
83742             }
83743             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
83744             var classFunction = ts.createFunctionExpression(
83745             /*modifiers*/ undefined, 
83746             /*asteriskToken*/ undefined, 
83747             /*name*/ undefined, 
83748             /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
83749             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
83750             // To preserve the behavior of the old emitter, we explicitly indent
83751             // the body of the function here if it was requested in an earlier
83752             // transformation.
83753             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
83754             // "inner" and "outer" below are added purely to preserve source map locations from
83755             // the old emitter
83756             var inner = ts.createPartiallyEmittedExpression(classFunction);
83757             inner.end = node.end;
83758             ts.setEmitFlags(inner, 1536 /* NoComments */);
83759             var outer = ts.createPartiallyEmittedExpression(inner);
83760             outer.end = ts.skipTrivia(currentText, node.pos);
83761             ts.setEmitFlags(outer, 1536 /* NoComments */);
83762             var result = ts.createParen(ts.createCall(outer, 
83763             /*typeArguments*/ undefined, extendsClauseElement
83764                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
83765                 : []));
83766             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
83767             return result;
83768         }
83769         /**
83770          * Transforms a ClassExpression or ClassDeclaration into a function body.
83771          *
83772          * @param node A ClassExpression or ClassDeclaration node.
83773          * @param extendsClauseElement The expression for the class `extends` clause.
83774          */
83775         function transformClassBody(node, extendsClauseElement) {
83776             var statements = [];
83777             startLexicalEnvironment();
83778             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
83779             addConstructor(statements, node, extendsClauseElement);
83780             addClassMembers(statements, node);
83781             // Create a synthetic text range for the return statement.
83782             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
83783             var localName = ts.getInternalName(node);
83784             // The following partially-emitted expression exists purely to align our sourcemap
83785             // emit with the original emitter.
83786             var outer = ts.createPartiallyEmittedExpression(localName);
83787             outer.end = closingBraceLocation.end;
83788             ts.setEmitFlags(outer, 1536 /* NoComments */);
83789             var statement = ts.createReturn(outer);
83790             statement.pos = closingBraceLocation.pos;
83791             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83792             statements.push(statement);
83793             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83794             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
83795             ts.setEmitFlags(block, 1536 /* NoComments */);
83796             return block;
83797         }
83798         /**
83799          * Adds a call to the `__extends` helper if needed for a class.
83800          *
83801          * @param statements The statements of the class body function.
83802          * @param node The ClassExpression or ClassDeclaration node.
83803          * @param extendsClauseElement The expression for the class `extends` clause.
83804          */
83805         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
83806             if (extendsClauseElement) {
83807                 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
83808                 /*location*/ extendsClauseElement));
83809             }
83810         }
83811         /**
83812          * Adds the constructor of the class to a class body function.
83813          *
83814          * @param statements The statements of the class body function.
83815          * @param node The ClassExpression or ClassDeclaration node.
83816          * @param extendsClauseElement The expression for the class `extends` clause.
83817          */
83818         function addConstructor(statements, node, extendsClauseElement) {
83819             var savedConvertedLoopState = convertedLoopState;
83820             convertedLoopState = undefined;
83821             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
83822             var constructor = ts.getFirstConstructorWithBody(node);
83823             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
83824             var constructorFunction = ts.createFunctionDeclaration(
83825             /*decorators*/ undefined, 
83826             /*modifiers*/ undefined, 
83827             /*asteriskToken*/ undefined, ts.getInternalName(node), 
83828             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
83829             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
83830             ts.setTextRange(constructorFunction, constructor || node);
83831             if (extendsClauseElement) {
83832                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
83833             }
83834             statements.push(constructorFunction);
83835             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
83836             convertedLoopState = savedConvertedLoopState;
83837         }
83838         /**
83839          * Transforms the parameters of the constructor declaration of a class.
83840          *
83841          * @param constructor The constructor for the class.
83842          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83843          *                            synthesized `super` call.
83844          */
83845         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
83846             // If the TypeScript transformer needed to synthesize a constructor for property
83847             // initializers, it would have also added a synthetic `...args` parameter and
83848             // `super` call.
83849             // If this is the case, we do not include the synthetic `...args` parameter and
83850             // will instead use the `arguments` object in ES5/3.
83851             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
83852                 || [];
83853         }
83854         function createDefaultConstructorBody(node, isDerivedClass) {
83855             // We must be here because the user didn't write a constructor
83856             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
83857             // If that's the case we can just immediately return the result of a 'super()' call.
83858             var statements = [];
83859             resumeLexicalEnvironment();
83860             ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83861             if (isDerivedClass) {
83862                 // return _super !== null && _super.apply(this, arguments) || this;
83863                 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
83864             }
83865             var statementsArray = ts.createNodeArray(statements);
83866             ts.setTextRange(statementsArray, node.members);
83867             var block = ts.createBlock(statementsArray, /*multiLine*/ true);
83868             ts.setTextRange(block, node);
83869             ts.setEmitFlags(block, 1536 /* NoComments */);
83870             return block;
83871         }
83872         /**
83873          * Transforms the body of a constructor declaration of a class.
83874          *
83875          * @param constructor The constructor for the class.
83876          * @param node The node which contains the constructor.
83877          * @param extendsClauseElement The expression for the class `extends` clause.
83878          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83879          *                            synthesized `super` call.
83880          */
83881         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
83882             // determine whether the class is known syntactically to be a derived class (e.g. a
83883             // class that extends a value that is not syntactically known to be `null`).
83884             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
83885             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
83886             // representation:
83887             //
83888             // ```
83889             // // es2015 (source)
83890             // class C extends Base { }
83891             //
83892             // // es5 (transformed)
83893             // var C = (function (_super) {
83894             //     function C() {
83895             //         return _super.apply(this, arguments) || this;
83896             //     }
83897             //     return C;
83898             // })(Base);
83899             // ```
83900             if (!constructor)
83901                 return createDefaultConstructorBody(node, isDerivedClass);
83902             // The prologue will contain all leading standard and custom prologue statements added by this transform
83903             var prologue = [];
83904             var statements = [];
83905             resumeLexicalEnvironment();
83906             // If a super call has already been synthesized,
83907             // we're going to assume that we should just transform everything after that.
83908             // The assumption is that no prior step in the pipeline has added any prologue directives.
83909             var statementOffset = 0;
83910             if (!hasSynthesizedSuper)
83911                 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
83912             addDefaultValueAssignmentsIfNeeded(statements, constructor);
83913             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
83914             if (!hasSynthesizedSuper)
83915                 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
83916             // If the first statement is a call to `super()`, visit the statement directly
83917             var superCallExpression;
83918             if (hasSynthesizedSuper) {
83919                 superCallExpression = createDefaultSuperCallOrThis();
83920             }
83921             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
83922                 var firstStatement = constructor.body.statements[statementOffset];
83923                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
83924                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
83925                 }
83926             }
83927             if (superCallExpression) {
83928                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
83929                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
83930             }
83931             // visit the remaining statements
83932             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
83933             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83934             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
83935             if (isDerivedClass) {
83936                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
83937                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
83938                     // following representation:
83939                     //
83940                     // ```
83941                     // // es2015 (source)
83942                     // class C extends Base {
83943                     //     constructor() {
83944                     //         super("foo");
83945                     //     }
83946                     // }
83947                     //
83948                     // // es5 (transformed)
83949                     // var C = (function (_super) {
83950                     //     function C() {
83951                     //         return _super.call(this, "foo") || this;
83952                     //     }
83953                     //     return C;
83954                     // })(Base);
83955                     // ```
83956                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
83957                     var returnStatement = ts.createReturn(superCallExpression);
83958                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
83959                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
83960                     statements.push(returnStatement);
83961                 }
83962                 else {
83963                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
83964                     //
83965                     // ```
83966                     // // es2015 (source)
83967                     // class C extends Base {
83968                     //     constructor() {
83969                     //         super("foo");
83970                     //         this.x = 1;
83971                     //     }
83972                     // }
83973                     //
83974                     // // es5 (transformed)
83975                     // var C = (function (_super) {
83976                     //     function C() {
83977                     //         var _this = _super.call(this, "foo") || this;
83978                     //         _this.x = 1;
83979                     //         return _this;
83980                     //     }
83981                     //     return C;
83982                     // })(Base);
83983                     // ```
83984                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
83985                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
83986                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
83987                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
83988                         statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
83989                     }
83990                 }
83991             }
83992             else {
83993                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
83994                 // captured when necessitated by an arrow function capturing the lexical `this`:
83995                 //
83996                 // ```
83997                 // // es2015
83998                 // class C {}
83999                 //
84000                 // // es5
84001                 // var C = (function () {
84002                 //     function C() {
84003                 //     }
84004                 //     return C;
84005                 // })();
84006                 // ```
84007                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
84008             }
84009             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), 
84010             /*location*/ constructor.body.statements), 
84011             /*multiLine*/ true);
84012             ts.setTextRange(block, constructor.body);
84013             return block;
84014         }
84015         /**
84016          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
84017          * It would generate obviously dead code, so we'll try to make things a little bit prettier
84018          * by doing a minimal check on whether some common patterns always explicitly return.
84019          */
84020         function isSufficientlyCoveredByReturnStatements(statement) {
84021             // A return statement is considered covered.
84022             if (statement.kind === 235 /* ReturnStatement */) {
84023                 return true;
84024             }
84025             // An if-statement with two covered branches is covered.
84026             else if (statement.kind === 227 /* IfStatement */) {
84027                 var ifStatement = statement;
84028                 if (ifStatement.elseStatement) {
84029                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
84030                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
84031                 }
84032             }
84033             // A block is covered if it has a last statement which is covered.
84034             else if (statement.kind === 223 /* Block */) {
84035                 var lastStatement = ts.lastOrUndefined(statement.statements);
84036                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
84037                     return true;
84038                 }
84039             }
84040             return false;
84041         }
84042         function createActualThis() {
84043             return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
84044         }
84045         function createDefaultSuperCallOrThis() {
84046             return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
84047         }
84048         /**
84049          * Visits a parameter declaration.
84050          *
84051          * @param node A ParameterDeclaration node.
84052          */
84053         function visitParameter(node) {
84054             if (node.dotDotDotToken) {
84055                 // rest parameters are elided
84056                 return undefined;
84057             }
84058             else if (ts.isBindingPattern(node.name)) {
84059                 // Binding patterns are converted into a generated name and are
84060                 // evaluated inside the function body.
84061                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
84062                 /*decorators*/ undefined, 
84063                 /*modifiers*/ undefined, 
84064                 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
84065                 /*questionToken*/ undefined, 
84066                 /*type*/ undefined, 
84067                 /*initializer*/ undefined), 
84068                 /*location*/ node), 
84069                 /*original*/ node);
84070             }
84071             else if (node.initializer) {
84072                 // Initializers are elided
84073                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
84074                 /*decorators*/ undefined, 
84075                 /*modifiers*/ undefined, 
84076                 /*dotDotDotToken*/ undefined, node.name, 
84077                 /*questionToken*/ undefined, 
84078                 /*type*/ undefined, 
84079                 /*initializer*/ undefined), 
84080                 /*location*/ node), 
84081                 /*original*/ node);
84082             }
84083             else {
84084                 return node;
84085             }
84086         }
84087         function hasDefaultValueOrBindingPattern(node) {
84088             return node.initializer !== undefined
84089                 || ts.isBindingPattern(node.name);
84090         }
84091         /**
84092          * Adds statements to the body of a function-like node if it contains parameters with
84093          * binding patterns or initializers.
84094          *
84095          * @param statements The statements for the new function body.
84096          * @param node A function-like node.
84097          */
84098         function addDefaultValueAssignmentsIfNeeded(statements, node) {
84099             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
84100                 return false;
84101             }
84102             var added = false;
84103             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
84104                 var parameter = _a[_i];
84105                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
84106                 // A rest parameter cannot have a binding pattern or an initializer,
84107                 // so let's just ignore it.
84108                 if (dotDotDotToken) {
84109                     continue;
84110                 }
84111                 if (ts.isBindingPattern(name)) {
84112                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
84113                 }
84114                 else if (initializer) {
84115                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
84116                     added = true;
84117                 }
84118             }
84119             return added;
84120         }
84121         /**
84122          * Adds statements to the body of a function-like node for parameters with binding patterns
84123          *
84124          * @param statements The statements for the new function body.
84125          * @param parameter The parameter for the function.
84126          * @param name The name of the parameter.
84127          * @param initializer The initializer for the parameter.
84128          */
84129         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
84130             // In cases where a binding pattern is simply '[]' or '{}',
84131             // we usually don't want to emit a var declaration; however, in the presence
84132             // of an initializer, we must emit that expression to preserve side effects.
84133             if (name.elements.length > 0) {
84134                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
84135                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
84136                 return true;
84137             }
84138             else if (initializer) {
84139                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
84140                 return true;
84141             }
84142             return false;
84143         }
84144         /**
84145          * Adds statements to the body of a function-like node for parameters with initializers.
84146          *
84147          * @param statements The statements for the new function body.
84148          * @param parameter The parameter for the function.
84149          * @param name The name of the parameter.
84150          * @param initializer The initializer for the parameter.
84151          */
84152         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
84153             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
84154             var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
84155                 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 */))
84156             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
84157             ts.startOnNewLine(statement);
84158             ts.setTextRange(statement, parameter);
84159             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
84160             ts.insertStatementAfterCustomPrologue(statements, statement);
84161         }
84162         /**
84163          * Gets a value indicating whether we need to add statements to handle a rest parameter.
84164          *
84165          * @param node A ParameterDeclaration node.
84166          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84167          *                                          part of a constructor declaration with a
84168          *                                          synthesized call to `super`
84169          */
84170         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
84171             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
84172         }
84173         /**
84174          * Adds statements to the body of a function-like node if it contains a rest parameter.
84175          *
84176          * @param statements The statements for the new function body.
84177          * @param node A function-like node.
84178          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84179          *                                          part of a constructor declaration with a
84180          *                                          synthesized call to `super`
84181          */
84182         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
84183             var prologueStatements = [];
84184             var parameter = ts.lastOrUndefined(node.parameters);
84185             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
84186                 return false;
84187             }
84188             // `declarationName` is the name of the local declaration for the parameter.
84189             var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84190             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
84191             // `expressionName` is the name of the parameter used in expressions.
84192             var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
84193             var restIndex = node.parameters.length - 1;
84194             var temp = ts.createLoopVariable();
84195             // var param = [];
84196             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84197             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84198                 ts.createVariableDeclaration(declarationName, 
84199                 /*type*/ undefined, ts.createArrayLiteral([]))
84200             ])), 
84201             /*location*/ parameter), 1048576 /* CustomPrologue */));
84202             // for (var _i = restIndex; _i < arguments.length; _i++) {
84203             //   param[_i - restIndex] = arguments[_i];
84204             // }
84205             var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
84206                 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
84207             ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
84208                 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
84209                     ? temp
84210                     : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
84211                 /*location*/ parameter))
84212             ]));
84213             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
84214             ts.startOnNewLine(forStatement);
84215             prologueStatements.push(forStatement);
84216             if (parameter.name.kind !== 75 /* Identifier */) {
84217                 // do the actual destructuring of the rest parameter if necessary
84218                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84219                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
84220             }
84221             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
84222             return true;
84223         }
84224         /**
84225          * Adds a statement to capture the `this` of a function declaration if it is needed.
84226          * NOTE: This must be executed *after* the subtree has been visited.
84227          *
84228          * @param statements The statements for the new function body.
84229          * @param node A node.
84230          */
84231         function insertCaptureThisForNodeIfNeeded(statements, node) {
84232             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
84233                 insertCaptureThisForNode(statements, node, ts.createThis());
84234                 return true;
84235             }
84236             return false;
84237         }
84238         function insertCaptureThisForNode(statements, node, initializer) {
84239             enableSubstitutionsForCapturedThis();
84240             var captureThisStatement = ts.createVariableStatement(
84241             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84242                 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
84243                 /*type*/ undefined, initializer)
84244             ]));
84245             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84246             ts.setSourceMapRange(captureThisStatement, node);
84247             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
84248         }
84249         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
84250             if (hierarchyFacts & 16384 /* NewTarget */) {
84251                 var newTarget = void 0;
84252                 switch (node.kind) {
84253                     case 202 /* ArrowFunction */:
84254                         return statements;
84255                     case 161 /* MethodDeclaration */:
84256                     case 163 /* GetAccessor */:
84257                     case 164 /* SetAccessor */:
84258                         // Methods and accessors cannot be constructors, so 'new.target' will
84259                         // always return 'undefined'.
84260                         newTarget = ts.createVoidZero();
84261                         break;
84262                     case 162 /* Constructor */:
84263                         // Class constructors can only be called with `new`, so `this.constructor`
84264                         // should be relatively safe to use.
84265                         newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
84266                         break;
84267                     case 244 /* FunctionDeclaration */:
84268                     case 201 /* FunctionExpression */:
84269                         // Functions can be called or constructed, and may have a `this` due to
84270                         // being a member or when calling an imported function via `other_1.f()`.
84271                         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());
84272                         break;
84273                     default:
84274                         return ts.Debug.failBadSyntaxKind(node);
84275                 }
84276                 var captureNewTargetStatement = ts.createVariableStatement(
84277                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
84278                     ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
84279                     /*type*/ undefined, newTarget)
84280                 ]));
84281                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84282                 if (copyOnWrite) {
84283                     statements = statements.slice();
84284                 }
84285                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
84286             }
84287             return statements;
84288         }
84289         /**
84290          * Adds statements to the class body function for a class to define the members of the
84291          * class.
84292          *
84293          * @param statements The statements for the class body function.
84294          * @param node The ClassExpression or ClassDeclaration node.
84295          */
84296         function addClassMembers(statements, node) {
84297             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
84298                 var member = _a[_i];
84299                 switch (member.kind) {
84300                     case 222 /* SemicolonClassElement */:
84301                         statements.push(transformSemicolonClassElementToStatement(member));
84302                         break;
84303                     case 161 /* MethodDeclaration */:
84304                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
84305                         break;
84306                     case 163 /* GetAccessor */:
84307                     case 164 /* SetAccessor */:
84308                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
84309                         if (member === accessors.firstAccessor) {
84310                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
84311                         }
84312                         break;
84313                     case 162 /* Constructor */:
84314                         // Constructors are handled in visitClassExpression/visitClassDeclaration
84315                         break;
84316                     default:
84317                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
84318                         break;
84319                 }
84320             }
84321         }
84322         /**
84323          * Transforms a SemicolonClassElement into a statement for a class body function.
84324          *
84325          * @param member The SemicolonClassElement node.
84326          */
84327         function transformSemicolonClassElementToStatement(member) {
84328             return ts.setTextRange(ts.createEmptyStatement(), member);
84329         }
84330         /**
84331          * Transforms a MethodDeclaration into a statement for a class body function.
84332          *
84333          * @param receiver The receiver for the member.
84334          * @param member The MethodDeclaration node.
84335          */
84336         function transformClassMethodDeclarationToStatement(receiver, member, container) {
84337             var commentRange = ts.getCommentRange(member);
84338             var sourceMapRange = ts.getSourceMapRange(member);
84339             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
84340             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
84341             var e;
84342             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
84343                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
84344                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
84345                         : propertyName;
84346                 e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
84347             }
84348             else {
84349                 var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
84350                 e = ts.createAssignment(memberName, memberFunction);
84351             }
84352             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
84353             ts.setSourceMapRange(memberFunction, sourceMapRange);
84354             var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
84355             ts.setOriginalNode(statement, member);
84356             ts.setCommentRange(statement, commentRange);
84357             // The location for the statement is used to emit comments only.
84358             // No source map should be emitted for this statement to align with the
84359             // old emitter.
84360             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
84361             return statement;
84362         }
84363         /**
84364          * Transforms a set of related of get/set accessors into a statement for a class body function.
84365          *
84366          * @param receiver The receiver for the member.
84367          * @param accessors The set of related get/set accessors.
84368          */
84369         function transformAccessorsToStatement(receiver, accessors, container) {
84370             var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
84371             // The location for the statement is used to emit source maps only.
84372             // No comments should be emitted for this statement to align with the
84373             // old emitter.
84374             ts.setEmitFlags(statement, 1536 /* NoComments */);
84375             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
84376             return statement;
84377         }
84378         /**
84379          * Transforms a set of related get/set accessors into an expression for either a class
84380          * body function or an ObjectLiteralExpression with computed properties.
84381          *
84382          * @param receiver The receiver for the member.
84383          */
84384         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
84385             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
84386             // To align with source maps in the old emitter, the receiver and property name
84387             // arguments are both mapped contiguously to the accessor name.
84388             var target = ts.getMutableClone(receiver);
84389             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
84390             ts.setSourceMapRange(target, firstAccessor.name);
84391             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
84392             if (ts.isPrivateIdentifier(visitedAccessorName)) {
84393                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
84394             }
84395             var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
84396             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
84397             ts.setSourceMapRange(propertyName, firstAccessor.name);
84398             var properties = [];
84399             if (getAccessor) {
84400                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
84401                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
84402                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
84403                 var getter = ts.createPropertyAssignment("get", getterFunction);
84404                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
84405                 properties.push(getter);
84406             }
84407             if (setAccessor) {
84408                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
84409                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
84410                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
84411                 var setter = ts.createPropertyAssignment("set", setterFunction);
84412                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
84413                 properties.push(setter);
84414             }
84415             properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
84416             var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
84417             /*typeArguments*/ undefined, [
84418                 target,
84419                 propertyName,
84420                 ts.createObjectLiteral(properties, /*multiLine*/ true)
84421             ]);
84422             if (startsOnNewLine) {
84423                 ts.startOnNewLine(call);
84424             }
84425             return call;
84426         }
84427         /**
84428          * Visits an ArrowFunction and transforms it into a FunctionExpression.
84429          *
84430          * @param node An ArrowFunction node.
84431          */
84432         function visitArrowFunction(node) {
84433             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
84434                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
84435             }
84436             var savedConvertedLoopState = convertedLoopState;
84437             convertedLoopState = undefined;
84438             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
84439             var func = ts.createFunctionExpression(
84440             /*modifiers*/ undefined, 
84441             /*asteriskToken*/ undefined, 
84442             /*name*/ undefined, 
84443             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84444             /*type*/ undefined, transformFunctionBody(node));
84445             ts.setTextRange(func, node);
84446             ts.setOriginalNode(func, node);
84447             ts.setEmitFlags(func, 8 /* CapturesThis */);
84448             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
84449                 enableSubstitutionsForCapturedThis();
84450             }
84451             // If an arrow function contains
84452             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
84453             convertedLoopState = savedConvertedLoopState;
84454             return func;
84455         }
84456         /**
84457          * Visits a FunctionExpression node.
84458          *
84459          * @param node a FunctionExpression node.
84460          */
84461         function visitFunctionExpression(node) {
84462             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
84463                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
84464                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84465             var savedConvertedLoopState = convertedLoopState;
84466             convertedLoopState = undefined;
84467             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84468             var body = transformFunctionBody(node);
84469             var name = hierarchyFacts & 16384 /* NewTarget */
84470                 ? ts.getLocalName(node)
84471                 : node.name;
84472             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84473             convertedLoopState = savedConvertedLoopState;
84474             return ts.updateFunctionExpression(node, 
84475             /*modifiers*/ undefined, node.asteriskToken, name, 
84476             /*typeParameters*/ undefined, parameters, 
84477             /*type*/ undefined, body);
84478         }
84479         /**
84480          * Visits a FunctionDeclaration node.
84481          *
84482          * @param node a FunctionDeclaration node.
84483          */
84484         function visitFunctionDeclaration(node) {
84485             var savedConvertedLoopState = convertedLoopState;
84486             convertedLoopState = undefined;
84487             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84488             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84489             var body = transformFunctionBody(node);
84490             var name = hierarchyFacts & 16384 /* NewTarget */
84491                 ? ts.getLocalName(node)
84492                 : node.name;
84493             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84494             convertedLoopState = savedConvertedLoopState;
84495             return ts.updateFunctionDeclaration(node, 
84496             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
84497             /*typeParameters*/ undefined, parameters, 
84498             /*type*/ undefined, body);
84499         }
84500         /**
84501          * Transforms a function-like node into a FunctionExpression.
84502          *
84503          * @param node The function-like node to transform.
84504          * @param location The source-map location for the new FunctionExpression.
84505          * @param name The name of the new FunctionExpression.
84506          */
84507         function transformFunctionLikeToExpression(node, location, name, container) {
84508             var savedConvertedLoopState = convertedLoopState;
84509             convertedLoopState = undefined;
84510             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
84511                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
84512                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84513             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84514             var body = transformFunctionBody(node);
84515             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
84516                 name = ts.getGeneratedNameForNode(node);
84517             }
84518             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84519             convertedLoopState = savedConvertedLoopState;
84520             return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
84521             /*modifiers*/ undefined, node.asteriskToken, name, 
84522             /*typeParameters*/ undefined, parameters, 
84523             /*type*/ undefined, body), location), 
84524             /*original*/ node);
84525         }
84526         /**
84527          * Transforms the body of a function-like node.
84528          *
84529          * @param node A function-like node.
84530          */
84531         function transformFunctionBody(node) {
84532             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
84533             var singleLine = false; // indicates whether the block *may* be emitted as a single line
84534             var statementsLocation;
84535             var closeBraceLocation;
84536             var prologue = [];
84537             var statements = [];
84538             var body = node.body;
84539             var statementOffset;
84540             resumeLexicalEnvironment();
84541             if (ts.isBlock(body)) {
84542                 // ensureUseStrict is false because no new prologue-directive should be added.
84543                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
84544                 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
84545                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction);
84546                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement);
84547             }
84548             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
84549             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
84550             if (ts.isBlock(body)) {
84551                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
84552                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
84553                 statementsLocation = body.statements;
84554                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
84555                 // If the original body was a multi-line block, this must be a multi-line block.
84556                 if (!multiLine && body.multiLine) {
84557                     multiLine = true;
84558                 }
84559             }
84560             else {
84561                 ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
84562                 // To align with the old emitter, we use a synthetic end position on the location
84563                 // for the statement list we synthesize when we down-level an arrow function with
84564                 // an expression function body. This prevents both comments and source maps from
84565                 // being emitted for the end position only.
84566                 statementsLocation = ts.moveRangeEnd(body, -1);
84567                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
84568                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
84569                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
84570                         singleLine = true;
84571                     }
84572                     else {
84573                         multiLine = true;
84574                     }
84575                 }
84576                 var expression = ts.visitNode(body, visitor, ts.isExpression);
84577                 var returnStatement = ts.createReturn(expression);
84578                 ts.setTextRange(returnStatement, body);
84579                 ts.moveSyntheticComments(returnStatement, body);
84580                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
84581                 statements.push(returnStatement);
84582                 // To align with the source map emit for the old emitter, we set a custom
84583                 // source map location for the close brace.
84584                 closeBraceLocation = body;
84585             }
84586             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
84587             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
84588             insertCaptureThisForNodeIfNeeded(prologue, node);
84589             // If we added any final generated statements, this must be a multi-line block
84590             if (ts.some(prologue)) {
84591                 multiLine = true;
84592             }
84593             statements.unshift.apply(statements, prologue);
84594             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
84595                 // no changes were made, preserve the tree
84596                 return body;
84597             }
84598             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
84599             ts.setTextRange(block, node.body);
84600             if (!multiLine && singleLine) {
84601                 ts.setEmitFlags(block, 1 /* SingleLine */);
84602             }
84603             if (closeBraceLocation) {
84604                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
84605             }
84606             ts.setOriginalNode(block, node.body);
84607             return block;
84608         }
84609         function visitBlock(node, isFunctionBody) {
84610             if (isFunctionBody) {
84611                 // A function body is not a block scope.
84612                 return ts.visitEachChild(node, visitor, context);
84613             }
84614             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
84615                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
84616                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
84617             var updated = ts.visitEachChild(node, visitor, context);
84618             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84619             return updated;
84620         }
84621         /**
84622          * Visits an ExpressionStatement that contains a destructuring assignment.
84623          *
84624          * @param node An ExpressionStatement node.
84625          */
84626         function visitExpressionStatement(node) {
84627             // If we are here it is most likely because our expression is a destructuring assignment.
84628             switch (node.expression.kind) {
84629                 case 200 /* ParenthesizedExpression */:
84630                     return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84631                 case 209 /* BinaryExpression */:
84632                     return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84633             }
84634             return ts.visitEachChild(node, visitor, context);
84635         }
84636         /**
84637          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
84638          *
84639          * @param node A ParenthesizedExpression node.
84640          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84641          *                                of a destructuring assignment.
84642          */
84643         function visitParenthesizedExpression(node, needsDestructuringValue) {
84644             // If we are here it is most likely because our expression is a destructuring assignment.
84645             if (!needsDestructuringValue) {
84646                 // By default we always emit the RHS at the end of a flattened destructuring
84647                 // expression. If we are in a state where we do not need the destructuring value,
84648                 // we pass that information along to the children that care about it.
84649                 switch (node.expression.kind) {
84650                     case 200 /* ParenthesizedExpression */:
84651                         return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84652                     case 209 /* BinaryExpression */:
84653                         return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84654                 }
84655             }
84656             return ts.visitEachChild(node, visitor, context);
84657         }
84658         /**
84659          * Visits a BinaryExpression that contains a destructuring assignment.
84660          *
84661          * @param node A BinaryExpression node.
84662          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84663          *                                of a destructuring assignment.
84664          */
84665         function visitBinaryExpression(node, needsDestructuringValue) {
84666             // If we are here it is because this is a destructuring assignment.
84667             if (ts.isDestructuringAssignment(node)) {
84668                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
84669             }
84670             return ts.visitEachChild(node, visitor, context);
84671         }
84672         function isVariableStatementOfTypeScriptClassWrapper(node) {
84673             return node.declarationList.declarations.length === 1
84674                 && !!node.declarationList.declarations[0].initializer
84675                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
84676         }
84677         function visitVariableStatement(node) {
84678             var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
84679             var updated;
84680             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
84681                 // we are inside a converted loop - hoist variable declarations
84682                 var assignments = void 0;
84683                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
84684                     var decl = _a[_i];
84685                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
84686                     if (decl.initializer) {
84687                         var assignment = void 0;
84688                         if (ts.isBindingPattern(decl.name)) {
84689                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
84690                         }
84691                         else {
84692                             assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
84693                             ts.setTextRange(assignment, decl);
84694                         }
84695                         assignments = ts.append(assignments, assignment);
84696                     }
84697                 }
84698                 if (assignments) {
84699                     updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
84700                 }
84701                 else {
84702                     // none of declarations has initializer - the entire variable statement can be deleted
84703                     updated = undefined;
84704                 }
84705             }
84706             else {
84707                 updated = ts.visitEachChild(node, visitor, context);
84708             }
84709             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84710             return updated;
84711         }
84712         /**
84713          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
84714          *
84715          * @param node A VariableDeclarationList node.
84716          */
84717         function visitVariableDeclarationList(node) {
84718             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
84719                 if (node.flags & 3 /* BlockScoped */) {
84720                     enableSubstitutionsForBlockScopedBindings();
84721                 }
84722                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
84723                     ? visitVariableDeclarationInLetDeclarationList
84724                     : visitVariableDeclaration);
84725                 var declarationList = ts.createVariableDeclarationList(declarations);
84726                 ts.setOriginalNode(declarationList, node);
84727                 ts.setTextRange(declarationList, node);
84728                 ts.setCommentRange(declarationList, node);
84729                 // If the first or last declaration is a binding pattern, we need to modify
84730                 // the source map range for the declaration list.
84731                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
84732                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
84733                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
84734                 }
84735                 return declarationList;
84736             }
84737             return ts.visitEachChild(node, visitor, context);
84738         }
84739         function getRangeUnion(declarations) {
84740             // declarations may not be sorted by position.
84741             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
84742             var pos = -1, end = -1;
84743             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
84744                 var node = declarations_10[_i];
84745                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
84746                 end = Math.max(end, node.end);
84747             }
84748             return ts.createRange(pos, end);
84749         }
84750         /**
84751          * Gets a value indicating whether we should emit an explicit initializer for a variable
84752          * declaration in a `let` declaration list.
84753          *
84754          * @param node A VariableDeclaration node.
84755          */
84756         function shouldEmitExplicitInitializerForLetDeclaration(node) {
84757             // Nested let bindings might need to be initialized explicitly to preserve
84758             // ES6 semantic:
84759             //
84760             //  { let x = 1; }
84761             //  { let x; } // x here should be undefined. not 1
84762             //
84763             // Top level bindings never collide with anything and thus don't require
84764             // explicit initialization. As for nested let bindings there are two cases:
84765             //
84766             // - Nested let bindings that were not renamed definitely should be
84767             //   initialized explicitly:
84768             //
84769             //    { let x = 1; }
84770             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
84771             //
84772             //   Without explicit initialization code in /*1*/ can be executed even if
84773             //   some-condition is evaluated to false.
84774             //
84775             // - Renaming introduces fresh name that should not collide with any
84776             //   existing names, however renamed bindings sometimes also should be
84777             //   explicitly initialized. One particular case: non-captured binding
84778             //   declared inside loop body (but not in loop initializer):
84779             //
84780             //    let x;
84781             //    for (;;) {
84782             //        let x;
84783             //    }
84784             //
84785             //   In downlevel codegen inner 'x' will be renamed so it won't collide
84786             //   with outer 'x' however it will should be reset on every iteration as
84787             //   if it was declared anew.
84788             //
84789             //   * Why non-captured binding?
84790             //     - Because if loop contains block scoped binding captured in some
84791             //       function then loop body will be rewritten to have a fresh scope
84792             //       on every iteration so everything will just work.
84793             //
84794             //   * Why loop initializer is excluded?
84795             //     - Since we've introduced a fresh name it already will be undefined.
84796             var flags = resolver.getNodeCheckFlags(node);
84797             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
84798             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
84799             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
84800                 || (isCapturedInFunction
84801                     && isDeclaredInLoop
84802                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
84803             var emitExplicitInitializer = !emittedAsTopLevel
84804                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
84805                 && (!resolver.isDeclarationWithCollidingName(node)
84806                     || (isDeclaredInLoop
84807                         && !isCapturedInFunction
84808                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
84809             return emitExplicitInitializer;
84810         }
84811         /**
84812          * Visits a VariableDeclaration in a `let` declaration list.
84813          *
84814          * @param node A VariableDeclaration node.
84815          */
84816         function visitVariableDeclarationInLetDeclarationList(node) {
84817             // For binding pattern names that lack initializers there is no point to emit
84818             // explicit initializer since downlevel codegen for destructuring will fail
84819             // in the absence of initializer so all binding elements will say uninitialized
84820             var name = node.name;
84821             if (ts.isBindingPattern(name)) {
84822                 return visitVariableDeclaration(node);
84823             }
84824             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
84825                 var clone_3 = ts.getMutableClone(node);
84826                 clone_3.initializer = ts.createVoidZero();
84827                 return clone_3;
84828             }
84829             return ts.visitEachChild(node, visitor, context);
84830         }
84831         /**
84832          * Visits a VariableDeclaration node with a binding pattern.
84833          *
84834          * @param node A VariableDeclaration node.
84835          */
84836         function visitVariableDeclaration(node) {
84837             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
84838             var updated;
84839             if (ts.isBindingPattern(node.name)) {
84840                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
84841                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
84842             }
84843             else {
84844                 updated = ts.visitEachChild(node, visitor, context);
84845             }
84846             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84847             return updated;
84848         }
84849         function recordLabel(node) {
84850             convertedLoopState.labels.set(ts.idText(node.label), true);
84851         }
84852         function resetLabel(node) {
84853             convertedLoopState.labels.set(ts.idText(node.label), false);
84854         }
84855         function visitLabeledStatement(node) {
84856             if (convertedLoopState && !convertedLoopState.labels) {
84857                 convertedLoopState.labels = ts.createMap();
84858             }
84859             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
84860             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
84861                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
84862                 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
84863         }
84864         function visitIterationStatement(node, outermostLabeledStatement) {
84865             switch (node.kind) {
84866                 case 228 /* DoStatement */:
84867                 case 229 /* WhileStatement */:
84868                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
84869                 case 230 /* ForStatement */:
84870                     return visitForStatement(node, outermostLabeledStatement);
84871                 case 231 /* ForInStatement */:
84872                     return visitForInStatement(node, outermostLabeledStatement);
84873                 case 232 /* ForOfStatement */:
84874                     return visitForOfStatement(node, outermostLabeledStatement);
84875             }
84876         }
84877         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
84878             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84879             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
84880             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84881             return updated;
84882         }
84883         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
84884             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
84885         }
84886         function visitForStatement(node, outermostLabeledStatement) {
84887             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
84888         }
84889         function visitForInStatement(node, outermostLabeledStatement) {
84890             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
84891         }
84892         function visitForOfStatement(node, outermostLabeledStatement) {
84893             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
84894         }
84895         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
84896             var statements = [];
84897             var initializer = node.initializer;
84898             if (ts.isVariableDeclarationList(initializer)) {
84899                 if (node.initializer.flags & 3 /* BlockScoped */) {
84900                     enableSubstitutionsForBlockScopedBindings();
84901                 }
84902                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
84903                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
84904                     // This works whether the declaration is a var, let, or const.
84905                     // It will use rhsIterationValue _a[_i] as the initializer.
84906                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
84907                     var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
84908                     ts.setOriginalNode(declarationList, node.initializer);
84909                     // Adjust the source map range for the first declaration to align with the old
84910                     // emitter.
84911                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
84912                     statements.push(ts.createVariableStatement(
84913                     /*modifiers*/ undefined, declarationList));
84914                 }
84915                 else {
84916                     // The following call does not include the initializer, so we have
84917                     // to emit it separately.
84918                     statements.push(ts.setTextRange(ts.createVariableStatement(
84919                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
84920                         ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
84921                         /*type*/ undefined, boundValue)
84922                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
84923                 }
84924             }
84925             else {
84926                 // Initializer is an expression. Emit the expression in the body, so that it's
84927                 // evaluated on every iteration.
84928                 var assignment = ts.createAssignment(initializer, boundValue);
84929                 if (ts.isDestructuringAssignment(assignment)) {
84930                     ts.aggregateTransformFlags(assignment);
84931                     statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
84932                 }
84933                 else {
84934                     assignment.end = initializer.end;
84935                     statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
84936                 }
84937             }
84938             if (convertedLoopBodyStatements) {
84939                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
84940             }
84941             else {
84942                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
84943                 if (ts.isBlock(statement)) {
84944                     return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
84945                 }
84946                 else {
84947                     statements.push(statement);
84948                     return createSyntheticBlockForConvertedStatements(statements);
84949                 }
84950             }
84951         }
84952         function createSyntheticBlockForConvertedStatements(statements) {
84953             return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
84954             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84955         }
84956         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
84957             // The following ES6 code:
84958             //
84959             //    for (let v of expr) { }
84960             //
84961             // should be emitted as
84962             //
84963             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
84964             //        var v = _a[_i];
84965             //    }
84966             //
84967             // where _a and _i are temps emitted to capture the RHS and the counter,
84968             // respectively.
84969             // When the left hand side is an expression instead of a let declaration,
84970             // the "let v" is not emitted.
84971             // When the left hand side is a let/const, the v is renamed if there is
84972             // another v in scope.
84973             // Note that all assignments to the LHS are emitted in the body, including
84974             // all destructuring.
84975             // Note also that because an extra statement is needed to assign to the LHS,
84976             // for-of bodies are always emitted as blocks.
84977             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84978             // In the case where the user wrote an identifier as the RHS, like this:
84979             //
84980             //     for (let v of arr) { }
84981             //
84982             // we don't want to emit a temporary variable for the RHS, just use it directly.
84983             var counter = ts.createLoopVariable();
84984             var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84985             // The old emitter does not emit source maps for the expression
84986             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
84987             var forStatement = ts.setTextRange(ts.createFor(
84988             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84989                 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
84990                 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
84991             ]), node.expression), 2097152 /* NoHoisting */), 
84992             /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
84993             /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
84994             /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
84995             /*location*/ node);
84996             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
84997             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
84998             ts.setTextRange(forStatement, node);
84999             return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
85000         }
85001         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
85002             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
85003             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
85004             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
85005             var errorRecord = ts.createUniqueName("e");
85006             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
85007             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
85008             var values = ts.createValuesHelper(context, expression, node.expression);
85009             var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
85010             hoistVariableDeclaration(errorRecord);
85011             hoistVariableDeclaration(returnMethod);
85012             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
85013             var initializer = ancestorFacts & 1024 /* IterationContainer */
85014                 ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
85015                 : values;
85016             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
85017             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
85018                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
85019                 ts.createVariableDeclaration(result, /*type*/ undefined, next)
85020             ]), node.expression), 2097152 /* NoHoisting */), 
85021             /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
85022             /*incrementor*/ ts.createAssignment(result, next), 
85023             /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
85024             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
85025             return ts.createTry(ts.createBlock([
85026                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
85027             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
85028                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
85029                     ts.createPropertyAssignment("error", catchVariable)
85030                 ])))
85031             ]), 1 /* SingleLine */)), ts.createBlock([
85032                 ts.createTry(
85033                 /*tryBlock*/ ts.createBlock([
85034                     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 */),
85035                 ]), 
85036                 /*catchClause*/ undefined, 
85037                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
85038                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
85039                 ]), 1 /* SingleLine */))
85040             ]));
85041         }
85042         /**
85043          * Visits an ObjectLiteralExpression with computed property names.
85044          *
85045          * @param node An ObjectLiteralExpression node.
85046          */
85047         function visitObjectLiteralExpression(node) {
85048             // We are here because a ComputedPropertyName was used somewhere in the expression.
85049             var properties = node.properties;
85050             var numProperties = properties.length;
85051             // Find the first computed property.
85052             // Everything until that point can be emitted as part of the initial object literal.
85053             var numInitialProperties = numProperties;
85054             var numInitialPropertiesWithoutYield = numProperties;
85055             for (var i = 0; i < numProperties; i++) {
85056                 var property = properties[i];
85057                 if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
85058                     && i < numInitialPropertiesWithoutYield) {
85059                     numInitialPropertiesWithoutYield = i;
85060                 }
85061                 if (property.name.kind === 154 /* ComputedPropertyName */) {
85062                     numInitialProperties = i;
85063                     break;
85064                 }
85065             }
85066             if (numInitialProperties !== numProperties) {
85067                 if (numInitialPropertiesWithoutYield < numInitialProperties) {
85068                     numInitialProperties = numInitialPropertiesWithoutYield;
85069                 }
85070                 // For computed properties, we need to create a unique handle to the object
85071                 // literal so we can modify it without risking internal assignments tainting the object.
85072                 var temp = ts.createTempVariable(hoistVariableDeclaration);
85073                 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
85074                 var expressions = [];
85075                 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
85076                 if (node.multiLine) {
85077                     ts.startOnNewLine(assignment);
85078                 }
85079                 expressions.push(assignment);
85080                 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
85081                 // We need to clone the temporary identifier so that we can write it on a
85082                 // new line
85083                 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
85084                 return ts.inlineExpressions(expressions);
85085             }
85086             return ts.visitEachChild(node, visitor, context);
85087         }
85088         function shouldConvertPartOfIterationStatement(node) {
85089             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
85090         }
85091         function shouldConvertInitializerOfForStatement(node) {
85092             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
85093         }
85094         function shouldConvertConditionOfForStatement(node) {
85095             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
85096         }
85097         function shouldConvertIncrementorOfForStatement(node) {
85098             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85099         }
85100         function shouldConvertIterationStatement(node) {
85101             return shouldConvertBodyOfIterationStatement(node)
85102                 || shouldConvertInitializerOfForStatement(node);
85103         }
85104         function shouldConvertBodyOfIterationStatement(node) {
85105             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
85106         }
85107         /**
85108          * Records constituents of name for the given variable to be hoisted in the outer scope.
85109          */
85110         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
85111             if (!state.hoistedLocalVariables) {
85112                 state.hoistedLocalVariables = [];
85113             }
85114             visit(node.name);
85115             function visit(node) {
85116                 if (node.kind === 75 /* Identifier */) {
85117                     state.hoistedLocalVariables.push(node);
85118                 }
85119                 else {
85120                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
85121                         var element = _a[_i];
85122                         if (!ts.isOmittedExpression(element)) {
85123                             visit(element.name);
85124                         }
85125                     }
85126                 }
85127             }
85128         }
85129         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
85130             if (!shouldConvertIterationStatement(node)) {
85131                 var saveAllowedNonLabeledJumps = void 0;
85132                 if (convertedLoopState) {
85133                     // we get here if we are trying to emit normal loop loop inside converted loop
85134                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
85135                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
85136                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
85137                 }
85138                 var result = convert
85139                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
85140                     : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
85141                 if (convertedLoopState) {
85142                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
85143                 }
85144                 return result;
85145             }
85146             var currentState = createConvertedLoopState(node);
85147             var statements = [];
85148             var outerConvertedLoopState = convertedLoopState;
85149             convertedLoopState = currentState;
85150             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
85151             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
85152             convertedLoopState = outerConvertedLoopState;
85153             if (initializerFunction)
85154                 statements.push(initializerFunction.functionDeclaration);
85155             if (bodyFunction)
85156                 statements.push(bodyFunction.functionDeclaration);
85157             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
85158             if (initializerFunction) {
85159                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
85160             }
85161             var loop;
85162             if (bodyFunction) {
85163                 if (convert) {
85164                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
85165                 }
85166                 else {
85167                     var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
85168                     ts.aggregateTransformFlags(clone_4);
85169                     loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
85170                 }
85171             }
85172             else {
85173                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
85174                 ts.aggregateTransformFlags(clone_5);
85175                 loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
85176             }
85177             statements.push(loop);
85178             return statements;
85179         }
85180         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
85181             switch (node.kind) {
85182                 case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
85183                 case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
85184                 case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
85185                 case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
85186                 case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
85187                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
85188             }
85189         }
85190         function convertForStatement(node, initializerFunction, convertedLoopBody) {
85191             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
85192             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85193             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);
85194         }
85195         function convertForOfStatement(node, convertedLoopBody) {
85196             return ts.updateForOf(node, 
85197             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85198         }
85199         function convertForInStatement(node, convertedLoopBody) {
85200             return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85201         }
85202         function convertDoStatement(node, convertedLoopBody) {
85203             return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
85204         }
85205         function convertWhileStatement(node, convertedLoopBody) {
85206             return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85207         }
85208         function createConvertedLoopState(node) {
85209             var loopInitializer;
85210             switch (node.kind) {
85211                 case 230 /* ForStatement */:
85212                 case 231 /* ForInStatement */:
85213                 case 232 /* ForOfStatement */:
85214                     var initializer = node.initializer;
85215                     if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
85216                         loopInitializer = initializer;
85217                     }
85218                     break;
85219             }
85220             // variables that will be passed to the loop as parameters
85221             var loopParameters = [];
85222             // variables declared in the loop initializer that will be changed inside the loop
85223             var loopOutParameters = [];
85224             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
85225                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
85226                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
85227                     var decl = _a[_i];
85228                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85229                 }
85230             }
85231             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
85232             if (convertedLoopState) {
85233                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
85234                 // if outer converted loop has already accumulated some state - pass it through
85235                 if (convertedLoopState.argumentsName) {
85236                     // outer loop has already used 'arguments' so we've already have some name to alias it
85237                     // use the same name in all nested loops
85238                     currentState.argumentsName = convertedLoopState.argumentsName;
85239                 }
85240                 if (convertedLoopState.thisName) {
85241                     // outer loop has already used 'this' so we've already have some name to alias it
85242                     // use the same name in all nested loops
85243                     currentState.thisName = convertedLoopState.thisName;
85244                 }
85245                 if (convertedLoopState.hoistedLocalVariables) {
85246                     // we've already collected some non-block scoped variable declarations in enclosing loop
85247                     // use the same storage in nested loop
85248                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
85249                 }
85250             }
85251             return currentState;
85252         }
85253         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
85254             var extraVariableDeclarations;
85255             // propagate state from the inner loop to the outer loop if necessary
85256             if (state.argumentsName) {
85257                 // if alias for arguments is set
85258                 if (outerState) {
85259                     // pass it to outer converted loop
85260                     outerState.argumentsName = state.argumentsName;
85261                 }
85262                 else {
85263                     // this is top level converted loop and we need to create an alias for 'arguments' object
85264                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, 
85265                     /*type*/ undefined, ts.createIdentifier("arguments")));
85266                 }
85267             }
85268             if (state.thisName) {
85269                 // if alias for this is set
85270                 if (outerState) {
85271                     // pass it to outer converted loop
85272                     outerState.thisName = state.thisName;
85273                 }
85274                 else {
85275                     // this is top level converted loop so we need to create an alias for 'this' here
85276                     // NOTE:
85277                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
85278                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
85279                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, 
85280                     /*type*/ undefined, ts.createIdentifier("this")));
85281                 }
85282             }
85283             if (state.hoistedLocalVariables) {
85284                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
85285                 if (outerState) {
85286                     // pass them to outer converted loop
85287                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
85288                 }
85289                 else {
85290                     if (!extraVariableDeclarations) {
85291                         extraVariableDeclarations = [];
85292                     }
85293                     // hoist collected variable declarations
85294                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
85295                         var identifier = _a[_i];
85296                         extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
85297                     }
85298                 }
85299             }
85300             // add extra variables to hold out parameters if necessary
85301             if (state.loopOutParameters.length) {
85302                 if (!extraVariableDeclarations) {
85303                     extraVariableDeclarations = [];
85304                 }
85305                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
85306                     var outParam = _c[_b];
85307                     extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
85308                 }
85309             }
85310             if (state.conditionVariable) {
85311                 if (!extraVariableDeclarations) {
85312                     extraVariableDeclarations = [];
85313                 }
85314                 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
85315             }
85316             // create variable statement to hold all introduced variable declarations
85317             if (extraVariableDeclarations) {
85318                 statements.push(ts.createVariableStatement(
85319                 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
85320             }
85321         }
85322         function createOutVariable(p) {
85323             return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
85324         }
85325         /**
85326          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
85327          * that is captured in a closure inside of the initializer. The `_loop_init` function is
85328          * used to preserve the per-iteration environment semantics of
85329          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85330          */
85331         function createFunctionForInitializerOfForStatement(node, currentState) {
85332             var functionName = ts.createUniqueName("_loop_init");
85333             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
85334             var emitFlags = 0 /* None */;
85335             if (currentState.containsLexicalThis)
85336                 emitFlags |= 8 /* CapturesThis */;
85337             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
85338                 emitFlags |= 262144 /* AsyncFunctionBody */;
85339             var statements = [];
85340             statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
85341             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
85342             // This transforms the following ES2015 syntax:
85343             //
85344             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
85345             //      // loop body
85346             //  }
85347             //
85348             // Into the following ES5 syntax:
85349             //
85350             //  var _loop_init_1 = function () {
85351             //      var i = (setImmediate(() => console.log(i)), 0);
85352             //      out_i_1 = i;
85353             //  };
85354             //  var out_i_1;
85355             //  _loop_init_1();
85356             //  for (var i = out_i_1; i < 2; i++) {
85357             //      // loop body
85358             //  }
85359             //
85360             // Which prevents mutations to `i` in the per-iteration environment of the body
85361             // from affecting the initial value for `i` outside of the per-iteration environment.
85362             var functionDeclaration = ts.createVariableStatement(
85363             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85364                 ts.createVariableDeclaration(functionName, 
85365                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85366                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85367                 /*name*/ undefined, 
85368                 /*typeParameters*/ undefined, 
85369                 /*parameters*/ undefined, 
85370                 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
85371             ]), 2097152 /* NoHoisting */));
85372             var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
85373             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85374         }
85375         /**
85376          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
85377          * that is captured in a closure inside of the loop body. The `_loop` function is used to
85378          * preserve the per-iteration environment semantics of
85379          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85380          */
85381         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
85382             var functionName = ts.createUniqueName("_loop");
85383             startLexicalEnvironment();
85384             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
85385             var lexicalEnvironment = endLexicalEnvironment();
85386             var statements = [];
85387             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
85388                 // If a block-scoped variable declared in the initializer of `node` is captured in
85389                 // the condition or incrementor, we must move the condition and incrementor into
85390                 // the body of the for loop.
85391                 //
85392                 // This transforms the following ES2015 syntax:
85393                 //
85394                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
85395                 //      // loop body
85396                 //  }
85397                 //
85398                 // Into the following ES5 syntax:
85399                 //
85400                 //  var _loop_1 = function (i) {
85401                 //      if (inc_1)
85402                 //          setImmediate(() => console.log(i)), i++;
85403                 //      else
85404                 //          inc_1 = true;
85405                 //      if (!(setImmediate(() => console.log(i)), i < 2))
85406                 //          return out_i_1 = i, "break";
85407                 //      // loop body
85408                 //      out_i_1 = i;
85409                 //  }
85410                 //  var out_i_1, inc_1 = false;
85411                 //  for (var i = 0;;) {
85412                 //      var state_1 = _loop_1(i);
85413                 //      i = out_i_1;
85414                 //      if (state_1 === "break")
85415                 //          break;
85416                 //  }
85417                 //
85418                 // Which prevents mutations to `i` in the per-iteration environment of the body
85419                 // from affecting the value of `i` in the previous per-iteration environment.
85420                 //
85421                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
85422                 // environment that is carried over to the next iteration of the loop. As a result,
85423                 // we must indicate whether this is the first evaluation of the loop body so that
85424                 // we only evaluate the incrementor on subsequent evaluations.
85425                 currentState.conditionVariable = ts.createUniqueName("inc");
85426                 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
85427                 if (shouldConvertConditionOfForStatement(node)) {
85428                     statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
85429                 }
85430             }
85431             if (ts.isBlock(statement)) {
85432                 ts.addRange(statements, statement.statements);
85433             }
85434             else {
85435                 statements.push(statement);
85436             }
85437             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
85438             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
85439             var loopBody = ts.createBlock(statements, /*multiLine*/ true);
85440             if (ts.isBlock(statement))
85441                 ts.setOriginalNode(loopBody, statement);
85442             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
85443             var emitFlags = 0;
85444             if (currentState.containsLexicalThis)
85445                 emitFlags |= 8 /* CapturesThis */;
85446             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
85447                 emitFlags |= 262144 /* AsyncFunctionBody */;
85448             // This transforms the following ES2015 syntax (in addition to other variations):
85449             //
85450             //  for (let i = 0; i < 2; i++) {
85451             //      setImmediate(() => console.log(i));
85452             //  }
85453             //
85454             // Into the following ES5 syntax:
85455             //
85456             //  var _loop_1 = function (i) {
85457             //      setImmediate(() => console.log(i));
85458             //  };
85459             //  for (var i = 0; i < 2; i++) {
85460             //      _loop_1(i);
85461             //  }
85462             var functionDeclaration = ts.createVariableStatement(
85463             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85464                 ts.createVariableDeclaration(functionName, 
85465                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85466                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85467                 /*name*/ undefined, 
85468                 /*typeParameters*/ undefined, currentState.loopParameters, 
85469                 /*type*/ undefined, loopBody), emitFlags))
85470             ]), 2097152 /* NoHoisting */));
85471             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
85472             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85473         }
85474         function copyOutParameter(outParam, copyDirection) {
85475             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
85476             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
85477             return ts.createBinary(target, 62 /* EqualsToken */, source);
85478         }
85479         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
85480             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
85481                 var outParam = outParams_1[_i];
85482                 if (outParam.flags & partFlags) {
85483                     statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
85484                 }
85485             }
85486         }
85487         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
85488             var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
85489             var callResult = containsYield
85490                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85491                 : call;
85492             return ts.createStatement(callResult);
85493         }
85494         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
85495             var statements = [];
85496             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
85497             // simple loops are emitted as just 'loop()';
85498             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
85499             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
85500                 !state.labeledNonLocalBreaks &&
85501                 !state.labeledNonLocalContinues;
85502             var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
85503             var callResult = containsYield
85504                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85505                 : call;
85506             if (isSimpleLoop) {
85507                 statements.push(ts.createExpressionStatement(callResult));
85508                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85509             }
85510             else {
85511                 var loopResultName = ts.createUniqueName("state");
85512                 var stateVariable = ts.createVariableStatement(
85513                 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
85514                 statements.push(stateVariable);
85515                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85516                 if (state.nonLocalJumps & 8 /* Return */) {
85517                     var returnStatement = void 0;
85518                     if (outerState) {
85519                         outerState.nonLocalJumps |= 8 /* Return */;
85520                         returnStatement = ts.createReturn(loopResultName);
85521                     }
85522                     else {
85523                         returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
85524                     }
85525                     statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
85526                 }
85527                 if (state.nonLocalJumps & 2 /* Break */) {
85528                     statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
85529                 }
85530                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
85531                     var caseClauses = [];
85532                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
85533                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
85534                     statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
85535                 }
85536             }
85537             return statements;
85538         }
85539         function setLabeledJump(state, isBreak, labelText, labelMarker) {
85540             if (isBreak) {
85541                 if (!state.labeledNonLocalBreaks) {
85542                     state.labeledNonLocalBreaks = ts.createMap();
85543                 }
85544                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
85545             }
85546             else {
85547                 if (!state.labeledNonLocalContinues) {
85548                     state.labeledNonLocalContinues = ts.createMap();
85549                 }
85550                 state.labeledNonLocalContinues.set(labelText, labelMarker);
85551             }
85552         }
85553         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
85554             if (!table) {
85555                 return;
85556             }
85557             table.forEach(function (labelMarker, labelText) {
85558                 var statements = [];
85559                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
85560                 // then emit labeled break\continue
85561                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
85562                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
85563                     var label = ts.createIdentifier(labelText);
85564                     statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
85565                 }
85566                 else {
85567                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
85568                     statements.push(ts.createReturn(loopResultName));
85569                 }
85570                 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
85571             });
85572         }
85573         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
85574             var name = decl.name;
85575             if (ts.isBindingPattern(name)) {
85576                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
85577                     var element = _a[_i];
85578                     if (!ts.isOmittedExpression(element)) {
85579                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85580                     }
85581                 }
85582             }
85583             else {
85584                 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
85585                 var checkFlags = resolver.getNodeCheckFlags(decl);
85586                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
85587                     var outParamName = ts.createUniqueName("out_" + ts.idText(name));
85588                     var flags = 0;
85589                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
85590                         flags |= 1 /* Body */;
85591                     }
85592                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
85593                         flags |= 2 /* Initializer */;
85594                     }
85595                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
85596                 }
85597             }
85598         }
85599         /**
85600          * Adds the members of an object literal to an array of expressions.
85601          *
85602          * @param expressions An array of expressions.
85603          * @param node An ObjectLiteralExpression node.
85604          * @param receiver The receiver for members of the ObjectLiteralExpression.
85605          * @param numInitialNonComputedProperties The number of initial properties without
85606          *                                        computed property names.
85607          */
85608         function addObjectLiteralMembers(expressions, node, receiver, start) {
85609             var properties = node.properties;
85610             var numProperties = properties.length;
85611             for (var i = start; i < numProperties; i++) {
85612                 var property = properties[i];
85613                 switch (property.kind) {
85614                     case 163 /* GetAccessor */:
85615                     case 164 /* SetAccessor */:
85616                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
85617                         if (property === accessors.firstAccessor) {
85618                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
85619                         }
85620                         break;
85621                     case 161 /* MethodDeclaration */:
85622                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
85623                         break;
85624                     case 281 /* PropertyAssignment */:
85625                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
85626                         break;
85627                     case 282 /* ShorthandPropertyAssignment */:
85628                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
85629                         break;
85630                     default:
85631                         ts.Debug.failBadSyntaxKind(node);
85632                         break;
85633                 }
85634             }
85635         }
85636         /**
85637          * Transforms a PropertyAssignment node into an expression.
85638          *
85639          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
85640          * @param property The PropertyAssignment node.
85641          * @param receiver The receiver for the assignment.
85642          */
85643         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85644             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
85645             ts.setTextRange(expression, property);
85646             if (startsOnNewLine) {
85647                 ts.startOnNewLine(expression);
85648             }
85649             return expression;
85650         }
85651         /**
85652          * Transforms a ShorthandPropertyAssignment node into an expression.
85653          *
85654          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
85655          * @param property The ShorthandPropertyAssignment node.
85656          * @param receiver The receiver for the assignment.
85657          */
85658         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85659             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
85660             ts.setTextRange(expression, property);
85661             if (startsOnNewLine) {
85662                 ts.startOnNewLine(expression);
85663             }
85664             return expression;
85665         }
85666         /**
85667          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
85668          *
85669          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
85670          * @param method The MethodDeclaration node.
85671          * @param receiver The receiver for the assignment.
85672          */
85673         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
85674             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
85675             ts.setTextRange(expression, method);
85676             if (startsOnNewLine) {
85677                 ts.startOnNewLine(expression);
85678             }
85679             return expression;
85680         }
85681         function visitCatchClause(node) {
85682             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
85683             var updated;
85684             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
85685             if (ts.isBindingPattern(node.variableDeclaration.name)) {
85686                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
85687                 var newVariableDeclaration = ts.createVariableDeclaration(temp);
85688                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
85689                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
85690                 var list = ts.createVariableDeclarationList(vars);
85691                 ts.setTextRange(list, node.variableDeclaration);
85692                 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
85693                 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
85694             }
85695             else {
85696                 updated = ts.visitEachChild(node, visitor, context);
85697             }
85698             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
85699             return updated;
85700         }
85701         function addStatementToStartOfBlock(block, statement) {
85702             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
85703             return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
85704         }
85705         /**
85706          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
85707          * PropertyAssignment.
85708          *
85709          * @param node A MethodDeclaration node.
85710          */
85711         function visitMethodDeclaration(node) {
85712             // We should only get here for methods on an object literal with regular identifier names.
85713             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
85714             // Methods with computed property names are handled in visitObjectLiteralExpression.
85715             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85716             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
85717             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
85718             return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
85719             /*location*/ node);
85720         }
85721         /**
85722          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
85723          *
85724          * @param node An AccessorDeclaration node.
85725          */
85726         function visitAccessorDeclaration(node) {
85727             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85728             var savedConvertedLoopState = convertedLoopState;
85729             convertedLoopState = undefined;
85730             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
85731             var updated;
85732             var parameters = ts.visitParameterList(node.parameters, visitor, context);
85733             var body = transformFunctionBody(node);
85734             if (node.kind === 163 /* GetAccessor */) {
85735                 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
85736             }
85737             else {
85738                 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
85739             }
85740             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
85741             convertedLoopState = savedConvertedLoopState;
85742             return updated;
85743         }
85744         /**
85745          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
85746          *
85747          * @param node A ShorthandPropertyAssignment node.
85748          */
85749         function visitShorthandPropertyAssignment(node) {
85750             return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
85751             /*location*/ node);
85752         }
85753         function visitComputedPropertyName(node) {
85754             return ts.visitEachChild(node, visitor, context);
85755         }
85756         /**
85757          * Visits a YieldExpression node.
85758          *
85759          * @param node A YieldExpression node.
85760          */
85761         function visitYieldExpression(node) {
85762             // `yield` expressions are transformed using the generators transformer.
85763             return ts.visitEachChild(node, visitor, context);
85764         }
85765         /**
85766          * Visits an ArrayLiteralExpression that contains a spread element.
85767          *
85768          * @param node An ArrayLiteralExpression node.
85769          */
85770         function visitArrayLiteralExpression(node) {
85771             if (ts.some(node.elements, ts.isSpreadElement)) {
85772                 // We are here because we contain a SpreadElementExpression.
85773                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
85774             }
85775             return ts.visitEachChild(node, visitor, context);
85776         }
85777         /**
85778          * Visits a CallExpression that contains either a spread element or `super`.
85779          *
85780          * @param node a CallExpression.
85781          */
85782         function visitCallExpression(node) {
85783             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
85784                 return visitTypeScriptClassWrapper(node);
85785             }
85786             var expression = ts.skipOuterExpressions(node.expression);
85787             if (expression.kind === 102 /* SuperKeyword */ ||
85788                 ts.isSuperProperty(expression) ||
85789                 ts.some(node.arguments, ts.isSpreadElement)) {
85790                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
85791             }
85792             return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
85793             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85794         }
85795         function visitTypeScriptClassWrapper(node) {
85796             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
85797             // The wrapper has a form similar to:
85798             //
85799             //  (function() {
85800             //      class C { // 1
85801             //      }
85802             //      C.x = 1; // 2
85803             //      return C;
85804             //  }())
85805             //
85806             // When we transform the class, we end up with something like this:
85807             //
85808             //  (function () {
85809             //      var C = (function () { // 3
85810             //          function C() {
85811             //          }
85812             //          return C; // 4
85813             //      }());
85814             //      C.x = 1;
85815             //      return C;
85816             //  }())
85817             //
85818             // We want to simplify the two nested IIFEs to end up with something like this:
85819             //
85820             //  (function () {
85821             //      function C() {
85822             //      }
85823             //      C.x = 1;
85824             //      return C;
85825             //  }())
85826             // We skip any outer expressions in a number of places to get to the innermost
85827             // expression, but we will restore them later to preserve comments and source maps.
85828             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
85829             // The class statements are the statements generated by visiting the first statement with initializer of the
85830             // body (1), while all other statements are added to remainingStatements (2)
85831             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
85832             // visit the class body statements outside of any converted loop body.
85833             var savedConvertedLoopState = convertedLoopState;
85834             convertedLoopState = undefined;
85835             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
85836             convertedLoopState = savedConvertedLoopState;
85837             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
85838             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
85839             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
85840             // We know there is only one variable declaration here as we verified this in an
85841             // earlier call to isTypeScriptClassWrapper
85842             var variable = varStatement.declarationList.declarations[0];
85843             var initializer = ts.skipOuterExpressions(variable.initializer);
85844             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
85845             // we see as an assignment, for example:
85846             //
85847             //  (function () {
85848             //      var C_1;
85849             //      var C = C_1 = (function () {
85850             //          function C() {
85851             //          }
85852             //          C.x = function () { return C_1; }
85853             //          return C;
85854             //      }());
85855             //      C = C_1 = __decorate([dec], C);
85856             //      return C;
85857             //  }())
85858             //
85859             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
85860             // The underlying call (3) is another IIFE that may contain a '_super' argument.
85861             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
85862             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
85863             var funcStatements = func.body.statements;
85864             var classBodyStart = 0;
85865             var classBodyEnd = -1;
85866             var statements = [];
85867             if (aliasAssignment) {
85868                 // If we have a class alias assignment, we need to move it to the down-level constructor
85869                 // function we generated for the class.
85870                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
85871                 if (extendsCall) {
85872                     statements.push(extendsCall);
85873                     classBodyStart++;
85874                 }
85875                 // The next statement is the function declaration.
85876                 statements.push(funcStatements[classBodyStart]);
85877                 classBodyStart++;
85878                 // Add the class alias following the declaration.
85879                 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
85880             }
85881             // Find the trailing 'return' statement (4)
85882             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
85883                 classBodyEnd--;
85884             }
85885             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
85886             // as we already have one that has been introduced by the 'ts' transformer.
85887             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
85888             if (classBodyEnd < -1) {
85889                 // If there were any hoisted declarations following the return statement, we should
85890                 // append them.
85891                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
85892             }
85893             // Add the remaining statements of the outer wrapper.
85894             ts.addRange(statements, remainingStatements);
85895             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
85896             // after the remaining statements from the 'ts' transformer.
85897             ts.addRange(statements, classStatements, /*start*/ 1);
85898             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
85899             // and comment locations.
85900             return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
85901             /*modifiers*/ undefined, 
85902             /*asteriskToken*/ undefined, 
85903             /*name*/ undefined, 
85904             /*typeParameters*/ undefined, func.parameters, 
85905             /*type*/ undefined, ts.updateBlock(func.body, statements))), 
85906             /*typeArguments*/ undefined, call.arguments))));
85907         }
85908         function visitImmediateSuperCallInBody(node) {
85909             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
85910         }
85911         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
85912             // We are here either because SuperKeyword was used somewhere in the expression, or
85913             // because we contain a SpreadElementExpression.
85914             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
85915                 node.expression.kind === 102 /* SuperKeyword */ ||
85916                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
85917                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85918                 if (node.expression.kind === 102 /* SuperKeyword */) {
85919                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
85920                 }
85921                 var resultingCall = void 0;
85922                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
85923                     // [source]
85924                     //      f(...a, b)
85925                     //      x.m(...a, b)
85926                     //      super(...a, b)
85927                     //      super.m(...a, b) // in static
85928                     //      super.m(...a, b) // in instance
85929                     //
85930                     // [output]
85931                     //      f.apply(void 0, a.concat([b]))
85932                     //      (_a = x).m.apply(_a, a.concat([b]))
85933                     //      _super.apply(this, a.concat([b]))
85934                     //      _super.m.apply(this, a.concat([b]))
85935                     //      _super.prototype.m.apply(this, a.concat([b]))
85936                     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));
85937                 }
85938                 else {
85939                     // [source]
85940                     //      super(a)
85941                     //      super.m(a) // in static
85942                     //      super.m(a) // in instance
85943                     //
85944                     // [output]
85945                     //      _super.call(this, a)
85946                     //      _super.m.call(this, a)
85947                     //      _super.prototype.m.call(this, a)
85948                     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), 
85949                     /*location*/ node);
85950                 }
85951                 if (node.expression.kind === 102 /* SuperKeyword */) {
85952                     var initializer = ts.createLogicalOr(resultingCall, createActualThis());
85953                     resultingCall = assignToCapturedThis
85954                         ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
85955                         : initializer;
85956                 }
85957                 return ts.setOriginalNode(resultingCall, node);
85958             }
85959             return ts.visitEachChild(node, visitor, context);
85960         }
85961         /**
85962          * Visits a NewExpression that contains a spread element.
85963          *
85964          * @param node A NewExpression node.
85965          */
85966         function visitNewExpression(node) {
85967             if (ts.some(node.arguments, ts.isSpreadElement)) {
85968                 // We are here because we contain a SpreadElementExpression.
85969                 // [source]
85970                 //      new C(...a)
85971                 //
85972                 // [output]
85973                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
85974                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85975                 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)), 
85976                 /*typeArguments*/ undefined, []);
85977             }
85978             return ts.visitEachChild(node, visitor, context);
85979         }
85980         /**
85981          * Transforms an array of Expression nodes that contains a SpreadExpression.
85982          *
85983          * @param elements The array of Expression nodes.
85984          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
85985          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
85986          */
85987         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
85988             // [source]
85989             //      [a, ...b, c]
85990             //
85991             // [output (downlevelIteration)]
85992             //      __spread([a], b, [c])
85993             //
85994             // [output]
85995             //      __spreadArrays([a], b, [c])
85996             // Map spans of spread expressions into their expressions and spans of other
85997             // expressions into an array literal.
85998             var numElements = elements.length;
85999             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
86000                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
86001             }));
86002             if (compilerOptions.downlevelIteration) {
86003                 if (segments.length === 1) {
86004                     var firstSegment = segments[0];
86005                     if (isCallToHelper(firstSegment, "___spread")) {
86006                         return segments[0];
86007                     }
86008                 }
86009                 return ts.createSpreadHelper(context, segments);
86010             }
86011             else {
86012                 if (segments.length === 1) {
86013                     var firstSegment = segments[0];
86014                     if (!needsUniqueCopy
86015                         || isPackedArrayLiteral(firstSegment)
86016                         || isCallToHelper(firstSegment, "___spreadArrays")) {
86017                         return segments[0];
86018                     }
86019                 }
86020                 return ts.createSpreadArraysHelper(context, segments);
86021             }
86022         }
86023         function isPackedElement(node) {
86024             return !ts.isOmittedExpression(node);
86025         }
86026         function isPackedArrayLiteral(node) {
86027             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
86028         }
86029         function isCallToHelper(firstSegment, helperName) {
86030             return ts.isCallExpression(firstSegment)
86031                 && ts.isIdentifier(firstSegment.expression)
86032                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
86033                 && firstSegment.expression.escapedText === helperName;
86034         }
86035         function partitionSpread(node) {
86036             return ts.isSpreadElement(node)
86037                 ? visitSpanOfSpreads
86038                 : visitSpanOfNonSpreads;
86039         }
86040         function visitSpanOfSpreads(chunk) {
86041             return ts.map(chunk, visitExpressionOfSpread);
86042         }
86043         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
86044             return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
86045         }
86046         function visitSpreadElement(node) {
86047             return ts.visitNode(node.expression, visitor, ts.isExpression);
86048         }
86049         /**
86050          * Transforms the expression of a SpreadExpression node.
86051          *
86052          * @param node A SpreadExpression node.
86053          */
86054         function visitExpressionOfSpread(node) {
86055             return ts.visitNode(node.expression, visitor, ts.isExpression);
86056         }
86057         /**
86058          * Visits a template literal.
86059          *
86060          * @param node A template literal.
86061          */
86062         function visitTemplateLiteral(node) {
86063             return ts.setTextRange(ts.createLiteral(node.text), node);
86064         }
86065         /**
86066          * Visits a string literal with an extended unicode escape.
86067          *
86068          * @param node A string literal.
86069          */
86070         function visitStringLiteral(node) {
86071             if (node.hasExtendedUnicodeEscape) {
86072                 return ts.setTextRange(ts.createLiteral(node.text), node);
86073             }
86074             return node;
86075         }
86076         /**
86077          * Visits a binary or octal (ES6) numeric literal.
86078          *
86079          * @param node A string literal.
86080          */
86081         function visitNumericLiteral(node) {
86082             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
86083                 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
86084             }
86085             return node;
86086         }
86087         /**
86088          * Visits a TaggedTemplateExpression node.
86089          *
86090          * @param node A TaggedTemplateExpression node.
86091          */
86092         function visitTaggedTemplateExpression(node) {
86093             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
86094         }
86095         /**
86096          * Visits a TemplateExpression node.
86097          *
86098          * @param node A TemplateExpression node.
86099          */
86100         function visitTemplateExpression(node) {
86101             var expressions = [];
86102             addTemplateHead(expressions, node);
86103             addTemplateSpans(expressions, node);
86104             // createAdd will check if each expression binds less closely than binary '+'.
86105             // If it does, it wraps the expression in parentheses. Otherwise, something like
86106             //    `abc${ 1 << 2 }`
86107             // becomes
86108             //    "abc" + 1 << 2 + ""
86109             // which is really
86110             //    ("abc" + 1) << (2 + "")
86111             // rather than
86112             //    "abc" + (1 << 2) + ""
86113             var expression = ts.reduceLeft(expressions, ts.createAdd);
86114             if (ts.nodeIsSynthesized(expression)) {
86115                 expression.pos = node.pos;
86116                 expression.end = node.end;
86117             }
86118             return expression;
86119         }
86120         /**
86121          * Gets a value indicating whether we need to include the head of a TemplateExpression.
86122          *
86123          * @param node A TemplateExpression node.
86124          */
86125         function shouldAddTemplateHead(node) {
86126             // If this expression has an empty head literal and the first template span has a non-empty
86127             // literal, then emitting the empty head literal is not necessary.
86128             //     `${ foo } and ${ bar }`
86129             // can be emitted as
86130             //     foo + " and " + bar
86131             // This is because it is only required that one of the first two operands in the emit
86132             // output must be a string literal, so that the other operand and all following operands
86133             // are forced into strings.
86134             //
86135             // If the first template span has an empty literal, then the head must still be emitted.
86136             //     `${ foo }${ bar }`
86137             // must still be emitted as
86138             //     "" + foo + bar
86139             // There is always atleast one templateSpan in this code path, since
86140             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
86141             ts.Debug.assert(node.templateSpans.length !== 0);
86142             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
86143         }
86144         /**
86145          * Adds the head of a TemplateExpression to an array of expressions.
86146          *
86147          * @param expressions An array of expressions.
86148          * @param node A TemplateExpression node.
86149          */
86150         function addTemplateHead(expressions, node) {
86151             if (!shouldAddTemplateHead(node)) {
86152                 return;
86153             }
86154             expressions.push(ts.createLiteral(node.head.text));
86155         }
86156         /**
86157          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
86158          *
86159          * @param expressions An array of expressions.
86160          * @param node A TemplateExpression node.
86161          */
86162         function addTemplateSpans(expressions, node) {
86163             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
86164                 var span = _a[_i];
86165                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
86166                 // Only emit if the literal is non-empty.
86167                 // The binary '+' operator is left-associative, so the first string concatenation
86168                 // with the head will force the result up to this point to be a string.
86169                 // Emitting a '+ ""' has no semantic effect for middles and tails.
86170                 if (span.literal.text.length !== 0) {
86171                     expressions.push(ts.createLiteral(span.literal.text));
86172                 }
86173             }
86174         }
86175         /**
86176          * Visits the `super` keyword
86177          */
86178         function visitSuperKeyword(isExpressionOfCall) {
86179             return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
86180                 ts.createFileLevelUniqueName("_super");
86181         }
86182         function visitMetaProperty(node) {
86183             if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
86184                 hierarchyFacts |= 16384 /* NewTarget */;
86185                 return ts.createFileLevelUniqueName("_newTarget");
86186             }
86187             return node;
86188         }
86189         /**
86190          * Called by the printer just before a node is printed.
86191          *
86192          * @param hint A hint as to the intended usage of the node.
86193          * @param node The node to be printed.
86194          * @param emitCallback The callback used to emit the node.
86195          */
86196         function onEmitNode(hint, node, emitCallback) {
86197             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
86198                 // If we are tracking a captured `this`, keep track of the enclosing function.
86199                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
86200                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
86201                     : 65 /* FunctionIncludes */);
86202                 previousOnEmitNode(hint, node, emitCallback);
86203                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86204                 return;
86205             }
86206             previousOnEmitNode(hint, node, emitCallback);
86207         }
86208         /**
86209          * Enables a more costly code path for substitutions when we determine a source file
86210          * contains block-scoped bindings (e.g. `let` or `const`).
86211          */
86212         function enableSubstitutionsForBlockScopedBindings() {
86213             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
86214                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
86215                 context.enableSubstitution(75 /* Identifier */);
86216             }
86217         }
86218         /**
86219          * Enables a more costly code path for substitutions when we determine a source file
86220          * contains a captured `this`.
86221          */
86222         function enableSubstitutionsForCapturedThis() {
86223             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
86224                 enabledSubstitutions |= 1 /* CapturedThis */;
86225                 context.enableSubstitution(104 /* ThisKeyword */);
86226                 context.enableEmitNotification(162 /* Constructor */);
86227                 context.enableEmitNotification(161 /* MethodDeclaration */);
86228                 context.enableEmitNotification(163 /* GetAccessor */);
86229                 context.enableEmitNotification(164 /* SetAccessor */);
86230                 context.enableEmitNotification(202 /* ArrowFunction */);
86231                 context.enableEmitNotification(201 /* FunctionExpression */);
86232                 context.enableEmitNotification(244 /* FunctionDeclaration */);
86233             }
86234         }
86235         /**
86236          * Hooks node substitutions.
86237          *
86238          * @param hint The context for the emitter.
86239          * @param node The node to substitute.
86240          */
86241         function onSubstituteNode(hint, node) {
86242             node = previousOnSubstituteNode(hint, node);
86243             if (hint === 1 /* Expression */) {
86244                 return substituteExpression(node);
86245             }
86246             if (ts.isIdentifier(node)) {
86247                 return substituteIdentifier(node);
86248             }
86249             return node;
86250         }
86251         /**
86252          * Hooks substitutions for non-expression identifiers.
86253          */
86254         function substituteIdentifier(node) {
86255             // Only substitute the identifier if we have enabled substitutions for block-scoped
86256             // bindings.
86257             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86258                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
86259                 if (original && isNameOfDeclarationWithCollidingName(original)) {
86260                     return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
86261                 }
86262             }
86263             return node;
86264         }
86265         /**
86266          * Determines whether a name is the name of a declaration with a colliding name.
86267          * NOTE: This function expects to be called with an original source tree node.
86268          *
86269          * @param node An original source tree node.
86270          */
86271         function isNameOfDeclarationWithCollidingName(node) {
86272             switch (node.parent.kind) {
86273                 case 191 /* BindingElement */:
86274                 case 245 /* ClassDeclaration */:
86275                 case 248 /* EnumDeclaration */:
86276                 case 242 /* VariableDeclaration */:
86277                     return node.parent.name === node
86278                         && resolver.isDeclarationWithCollidingName(node.parent);
86279             }
86280             return false;
86281         }
86282         /**
86283          * Substitutes an expression.
86284          *
86285          * @param node An Expression node.
86286          */
86287         function substituteExpression(node) {
86288             switch (node.kind) {
86289                 case 75 /* Identifier */:
86290                     return substituteExpressionIdentifier(node);
86291                 case 104 /* ThisKeyword */:
86292                     return substituteThisKeyword(node);
86293             }
86294             return node;
86295         }
86296         /**
86297          * Substitutes an expression identifier.
86298          *
86299          * @param node An Identifier node.
86300          */
86301         function substituteExpressionIdentifier(node) {
86302             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86303                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
86304                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
86305                     return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
86306                 }
86307             }
86308             return node;
86309         }
86310         function isPartOfClassBody(declaration, node) {
86311             var currentNode = ts.getParseTreeNode(node);
86312             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
86313                 // if the node has no correlation to a parse tree node, its definitely not
86314                 // part of the body.
86315                 // if the node is outside of the document range of the declaration, its
86316                 // definitely not part of the body.
86317                 return false;
86318             }
86319             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
86320             while (currentNode) {
86321                 if (currentNode === blockScope || currentNode === declaration) {
86322                     // if we are in the enclosing block scope of the declaration, we are definitely
86323                     // not inside the class body.
86324                     return false;
86325                 }
86326                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
86327                     return true;
86328                 }
86329                 currentNode = currentNode.parent;
86330             }
86331             return false;
86332         }
86333         /**
86334          * Substitutes `this` when contained within an arrow function.
86335          *
86336          * @param node The ThisKeyword node.
86337          */
86338         function substituteThisKeyword(node) {
86339             if (enabledSubstitutions & 1 /* CapturedThis */
86340                 && hierarchyFacts & 16 /* CapturesThis */) {
86341                 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
86342             }
86343             return node;
86344         }
86345         function getClassMemberPrefix(node, member) {
86346             return ts.hasModifier(member, 32 /* Static */)
86347                 ? ts.getInternalName(node)
86348                 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
86349         }
86350         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
86351             if (!constructor || !hasExtendsClause) {
86352                 return false;
86353             }
86354             if (ts.some(constructor.parameters)) {
86355                 return false;
86356             }
86357             var statement = ts.firstOrUndefined(constructor.body.statements);
86358             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
86359                 return false;
86360             }
86361             var statementExpression = statement.expression;
86362             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
86363                 return false;
86364             }
86365             var callTarget = statementExpression.expression;
86366             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
86367                 return false;
86368             }
86369             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
86370             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
86371                 return false;
86372             }
86373             var expression = callArgument.expression;
86374             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
86375         }
86376     }
86377     ts.transformES2015 = transformES2015;
86378     function createExtendsHelper(context, name) {
86379         context.requestEmitHelper(ts.extendsHelper);
86380         return ts.createCall(ts.getUnscopedHelperName("__extends"), 
86381         /*typeArguments*/ undefined, [
86382             name,
86383             ts.createFileLevelUniqueName("_super")
86384         ]);
86385     }
86386     ts.extendsHelper = {
86387         name: "typescript:extends",
86388         importName: "__extends",
86389         scoped: false,
86390         priority: 0,
86391         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            })();"
86392     };
86393 })(ts || (ts = {}));
86394 /*@internal*/
86395 var ts;
86396 (function (ts) {
86397     /**
86398      * Transforms ES5 syntax into ES3 syntax.
86399      *
86400      * @param context Context and state information for the transformation.
86401      */
86402     function transformES5(context) {
86403         var compilerOptions = context.getCompilerOptions();
86404         // enable emit notification only if using --jsx preserve or react-native
86405         var previousOnEmitNode;
86406         var noSubstitution;
86407         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
86408             previousOnEmitNode = context.onEmitNode;
86409             context.onEmitNode = onEmitNode;
86410             context.enableEmitNotification(268 /* JsxOpeningElement */);
86411             context.enableEmitNotification(269 /* JsxClosingElement */);
86412             context.enableEmitNotification(267 /* JsxSelfClosingElement */);
86413             noSubstitution = [];
86414         }
86415         var previousOnSubstituteNode = context.onSubstituteNode;
86416         context.onSubstituteNode = onSubstituteNode;
86417         context.enableSubstitution(194 /* PropertyAccessExpression */);
86418         context.enableSubstitution(281 /* PropertyAssignment */);
86419         return ts.chainBundle(transformSourceFile);
86420         /**
86421          * Transforms an ES5 source file to ES3.
86422          *
86423          * @param node A SourceFile
86424          */
86425         function transformSourceFile(node) {
86426             return node;
86427         }
86428         /**
86429          * Called by the printer just before a node is printed.
86430          *
86431          * @param hint A hint as to the intended usage of the node.
86432          * @param node The node to emit.
86433          * @param emitCallback A callback used to emit the node.
86434          */
86435         function onEmitNode(hint, node, emitCallback) {
86436             switch (node.kind) {
86437                 case 268 /* JsxOpeningElement */:
86438                 case 269 /* JsxClosingElement */:
86439                 case 267 /* JsxSelfClosingElement */:
86440                     var tagName = node.tagName;
86441                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
86442                     break;
86443             }
86444             previousOnEmitNode(hint, node, emitCallback);
86445         }
86446         /**
86447          * Hooks node substitutions.
86448          *
86449          * @param hint A hint as to the intended usage of the node.
86450          * @param node The node to substitute.
86451          */
86452         function onSubstituteNode(hint, node) {
86453             if (node.id && noSubstitution && noSubstitution[node.id]) {
86454                 return previousOnSubstituteNode(hint, node);
86455             }
86456             node = previousOnSubstituteNode(hint, node);
86457             if (ts.isPropertyAccessExpression(node)) {
86458                 return substitutePropertyAccessExpression(node);
86459             }
86460             else if (ts.isPropertyAssignment(node)) {
86461                 return substitutePropertyAssignment(node);
86462             }
86463             return node;
86464         }
86465         /**
86466          * Substitutes a PropertyAccessExpression whose name is a reserved word.
86467          *
86468          * @param node A PropertyAccessExpression
86469          */
86470         function substitutePropertyAccessExpression(node) {
86471             if (ts.isPrivateIdentifier(node.name)) {
86472                 return node;
86473             }
86474             var literalName = trySubstituteReservedName(node.name);
86475             if (literalName) {
86476                 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
86477             }
86478             return node;
86479         }
86480         /**
86481          * Substitutes a PropertyAssignment whose name is a reserved word.
86482          *
86483          * @param node A PropertyAssignment
86484          */
86485         function substitutePropertyAssignment(node) {
86486             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
86487             if (literalName) {
86488                 return ts.updatePropertyAssignment(node, literalName, node.initializer);
86489             }
86490             return node;
86491         }
86492         /**
86493          * If an identifier name is a reserved word, returns a string literal for the name.
86494          *
86495          * @param name An Identifier
86496          */
86497         function trySubstituteReservedName(name) {
86498             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
86499             if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
86500                 return ts.setTextRange(ts.createLiteral(name), name);
86501             }
86502             return undefined;
86503         }
86504     }
86505     ts.transformES5 = transformES5;
86506 })(ts || (ts = {}));
86507 // Transforms generator functions into a compatible ES5 representation with similar runtime
86508 // semantics. This is accomplished by first transforming the body of each generator
86509 // function into an intermediate representation that is the compiled into a JavaScript
86510 // switch statement.
86511 //
86512 // Many functions in this transformer will contain comments indicating the expected
86513 // intermediate representation. For illustrative purposes, the following intermediate
86514 // language is used to define this intermediate representation:
86515 //
86516 //  .nop                            - Performs no operation.
86517 //  .local NAME, ...                - Define local variable declarations.
86518 //  .mark LABEL                     - Mark the location of a label.
86519 //  .br LABEL                       - Jump to a label. If jumping out of a protected
86520 //                                    region, all .finally blocks are executed.
86521 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
86522 //                                    If jumping out of a protected region, all .finally
86523 //                                    blocks are executed.
86524 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
86525 //                                    If jumping out of a protected region, all .finally
86526 //                                    blocks are executed.
86527 //  .yield (x)                      - Yield the value of the optional expression `x`.
86528 //                                    Resume at the next label.
86529 //  .yieldstar (x)                  - Delegate yield to the value of the optional
86530 //                                    expression `x`. Resume at the next label.
86531 //                                    NOTE: `x` must be an Iterator, not an Iterable.
86532 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
86533 //                                    "break" abrupt completions jump to the CONTINUE or
86534 //                                    BREAK labels, respectively.
86535 //  .endloop                        - Marks the end of a loop.
86536 //  .with (x)                       - Marks the beginning of a WithStatement block, using
86537 //                                    the supplied expression.
86538 //  .endwith                        - Marks the end of a WithStatement.
86539 //  .switch                         - Marks the beginning of a SwitchStatement.
86540 //  .endswitch                      - Marks the end of a SwitchStatement.
86541 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
86542 //                                    supplied name.
86543 //  .endlabeled                     - Marks the end of a LabeledStatement.
86544 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
86545 //                                    labels for each block.
86546 //  .catch (x)                      - Marks the beginning of a catch block.
86547 //  .finally                        - Marks the beginning of a finally block.
86548 //  .endfinally                     - Marks the end of a finally block.
86549 //  .endtry                         - Marks the end of a protected region.
86550 //  .throw (x)                      - Throws the value of the expression `x`.
86551 //  .return (x)                     - Returns the value of the expression `x`.
86552 //
86553 // In addition, the illustrative intermediate representation introduces some special
86554 // variables:
86555 //
86556 //  %sent%                          - Either returns the next value sent to the generator,
86557 //                                    returns the result of a delegated yield, or throws
86558 //                                    the exception sent to the generator.
86559 //  %error%                         - Returns the value of the current exception in a
86560 //                                    catch block.
86561 //
86562 // This intermediate representation is then compiled into JavaScript syntax. The resulting
86563 // compilation output looks something like the following:
86564 //
86565 //  function f() {
86566 //      var /*locals*/;
86567 //      /*functions*/
86568 //      return __generator(function (state) {
86569 //          switch (state.label) {
86570 //              /*cases per label*/
86571 //          }
86572 //      });
86573 //  }
86574 //
86575 // Each of the above instructions corresponds to JavaScript emit similar to the following:
86576 //
86577 //  .local NAME                   | var NAME;
86578 // -------------------------------|----------------------------------------------
86579 //  .mark LABEL                   | case LABEL:
86580 // -------------------------------|----------------------------------------------
86581 //  .br LABEL                     |     return [3 /*break*/, LABEL];
86582 // -------------------------------|----------------------------------------------
86583 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
86584 // -------------------------------|----------------------------------------------
86585 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
86586 // -------------------------------|----------------------------------------------
86587 //  .yield (x)                    |     return [4 /*yield*/, x];
86588 //  .mark RESUME                  | case RESUME:
86589 //      a = %sent%;               |     a = state.sent();
86590 // -------------------------------|----------------------------------------------
86591 //  .yieldstar (x)                |     return [5 /*yield**/, x];
86592 //  .mark RESUME                  | case RESUME:
86593 //      a = %sent%;               |     a = state.sent();
86594 // -------------------------------|----------------------------------------------
86595 //  .with (_a)                    |     with (_a) {
86596 //      a();                      |         a();
86597 //                                |     }
86598 //                                |     state.label = LABEL;
86599 //  .mark LABEL                   | case LABEL:
86600 //                                |     with (_a) {
86601 //      b();                      |         b();
86602 //                                |     }
86603 //  .endwith                      |
86604 // -------------------------------|----------------------------------------------
86605 //                                | case 0:
86606 //                                |     state.trys = [];
86607 //                                | ...
86608 //  .try TRY, CATCH, FINALLY, END |
86609 //  .mark TRY                     | case TRY:
86610 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
86611 //  .nop                          |
86612 //      a();                      |     a();
86613 //  .br END                       |     return [3 /*break*/, END];
86614 //  .catch (e)                    |
86615 //  .mark CATCH                   | case CATCH:
86616 //                                |     e = state.sent();
86617 //      b();                      |     b();
86618 //  .br END                       |     return [3 /*break*/, END];
86619 //  .finally                      |
86620 //  .mark FINALLY                 | case FINALLY:
86621 //      c();                      |     c();
86622 //  .endfinally                   |     return [7 /*endfinally*/];
86623 //  .endtry                       |
86624 //  .mark END                     | case END:
86625 /*@internal*/
86626 var ts;
86627 (function (ts) {
86628     var OpCode;
86629     (function (OpCode) {
86630         OpCode[OpCode["Nop"] = 0] = "Nop";
86631         OpCode[OpCode["Statement"] = 1] = "Statement";
86632         OpCode[OpCode["Assign"] = 2] = "Assign";
86633         OpCode[OpCode["Break"] = 3] = "Break";
86634         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
86635         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
86636         OpCode[OpCode["Yield"] = 6] = "Yield";
86637         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
86638         OpCode[OpCode["Return"] = 8] = "Return";
86639         OpCode[OpCode["Throw"] = 9] = "Throw";
86640         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
86641     })(OpCode || (OpCode = {}));
86642     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
86643     var BlockAction;
86644     (function (BlockAction) {
86645         BlockAction[BlockAction["Open"] = 0] = "Open";
86646         BlockAction[BlockAction["Close"] = 1] = "Close";
86647     })(BlockAction || (BlockAction = {}));
86648     // the kind for a generated code block in a FunctionBuilder
86649     var CodeBlockKind;
86650     (function (CodeBlockKind) {
86651         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
86652         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
86653         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
86654         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
86655         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
86656     })(CodeBlockKind || (CodeBlockKind = {}));
86657     // the state for a generated code exception block
86658     var ExceptionBlockState;
86659     (function (ExceptionBlockState) {
86660         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
86661         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
86662         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
86663         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
86664     })(ExceptionBlockState || (ExceptionBlockState = {}));
86665     // NOTE: changes to this enum should be reflected in the __generator helper.
86666     var Instruction;
86667     (function (Instruction) {
86668         Instruction[Instruction["Next"] = 0] = "Next";
86669         Instruction[Instruction["Throw"] = 1] = "Throw";
86670         Instruction[Instruction["Return"] = 2] = "Return";
86671         Instruction[Instruction["Break"] = 3] = "Break";
86672         Instruction[Instruction["Yield"] = 4] = "Yield";
86673         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
86674         Instruction[Instruction["Catch"] = 6] = "Catch";
86675         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
86676     })(Instruction || (Instruction = {}));
86677     function getInstructionName(instruction) {
86678         switch (instruction) {
86679             case 2 /* Return */: return "return";
86680             case 3 /* Break */: return "break";
86681             case 4 /* Yield */: return "yield";
86682             case 5 /* YieldStar */: return "yield*";
86683             case 7 /* Endfinally */: return "endfinally";
86684             default: return undefined; // TODO: GH#18217
86685         }
86686     }
86687     function transformGenerators(context) {
86688         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
86689         var compilerOptions = context.getCompilerOptions();
86690         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86691         var resolver = context.getEmitResolver();
86692         var previousOnSubstituteNode = context.onSubstituteNode;
86693         context.onSubstituteNode = onSubstituteNode;
86694         var renamedCatchVariables;
86695         var renamedCatchVariableDeclarations;
86696         var inGeneratorFunctionBody;
86697         var inStatementContainingYield;
86698         // The following three arrays store information about generated code blocks.
86699         // All three arrays are correlated by their index. This approach is used over allocating
86700         // objects to store the same information to avoid GC overhead.
86701         //
86702         var blocks; // Information about the code block
86703         var blockOffsets; // The operation offset at which a code block begins or ends
86704         var blockActions; // Whether the code block is opened or closed
86705         var blockStack; // A stack of currently open code blocks
86706         // Labels are used to mark locations in the code that can be the target of a Break (jump)
86707         // operation. These are translated into case clauses in a switch statement.
86708         // The following two arrays are correlated by their index. This approach is used over
86709         // allocating objects to store the same information to avoid GC overhead.
86710         //
86711         var labelOffsets; // The operation offset at which the label is defined.
86712         var labelExpressions; // The NumericLiteral nodes bound to each label.
86713         var nextLabelId = 1; // The next label id to use.
86714         // Operations store information about generated code for the function body. This
86715         // Includes things like statements, assignments, breaks (jumps), and yields.
86716         // The following three arrays are correlated by their index. This approach is used over
86717         // allocating objects to store the same information to avoid GC overhead.
86718         //
86719         var operations; // The operation to perform.
86720         var operationArguments; // The arguments to the operation.
86721         var operationLocations; // The source map location for the operation.
86722         var state; // The name of the state object used by the generator at runtime.
86723         // The following variables store information used by the `build` function:
86724         //
86725         var blockIndex = 0; // The index of the current block.
86726         var labelNumber = 0; // The current label number.
86727         var labelNumbers;
86728         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
86729         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
86730         var clauses; // The case clauses generated for labels.
86731         var statements; // The statements for the current label.
86732         var exceptionBlockStack; // A stack of containing exception blocks.
86733         var currentExceptionBlock; // The current exception block.
86734         var withBlockStack; // A stack containing `with` blocks.
86735         return ts.chainBundle(transformSourceFile);
86736         function transformSourceFile(node) {
86737             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
86738                 return node;
86739             }
86740             var visited = ts.visitEachChild(node, visitor, context);
86741             ts.addEmitHelpers(visited, context.readEmitHelpers());
86742             return visited;
86743         }
86744         /**
86745          * Visits a node.
86746          *
86747          * @param node The node to visit.
86748          */
86749         function visitor(node) {
86750             var transformFlags = node.transformFlags;
86751             if (inStatementContainingYield) {
86752                 return visitJavaScriptInStatementContainingYield(node);
86753             }
86754             else if (inGeneratorFunctionBody) {
86755                 return visitJavaScriptInGeneratorFunctionBody(node);
86756             }
86757             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
86758                 return visitGenerator(node);
86759             }
86760             else if (transformFlags & 512 /* ContainsGenerator */) {
86761                 return ts.visitEachChild(node, visitor, context);
86762             }
86763             else {
86764                 return node;
86765             }
86766         }
86767         /**
86768          * Visits a node that is contained within a statement that contains yield.
86769          *
86770          * @param node The node to visit.
86771          */
86772         function visitJavaScriptInStatementContainingYield(node) {
86773             switch (node.kind) {
86774                 case 228 /* DoStatement */:
86775                     return visitDoStatement(node);
86776                 case 229 /* WhileStatement */:
86777                     return visitWhileStatement(node);
86778                 case 237 /* SwitchStatement */:
86779                     return visitSwitchStatement(node);
86780                 case 238 /* LabeledStatement */:
86781                     return visitLabeledStatement(node);
86782                 default:
86783                     return visitJavaScriptInGeneratorFunctionBody(node);
86784             }
86785         }
86786         /**
86787          * Visits a node that is contained within a generator function.
86788          *
86789          * @param node The node to visit.
86790          */
86791         function visitJavaScriptInGeneratorFunctionBody(node) {
86792             switch (node.kind) {
86793                 case 244 /* FunctionDeclaration */:
86794                     return visitFunctionDeclaration(node);
86795                 case 201 /* FunctionExpression */:
86796                     return visitFunctionExpression(node);
86797                 case 163 /* GetAccessor */:
86798                 case 164 /* SetAccessor */:
86799                     return visitAccessorDeclaration(node);
86800                 case 225 /* VariableStatement */:
86801                     return visitVariableStatement(node);
86802                 case 230 /* ForStatement */:
86803                     return visitForStatement(node);
86804                 case 231 /* ForInStatement */:
86805                     return visitForInStatement(node);
86806                 case 234 /* BreakStatement */:
86807                     return visitBreakStatement(node);
86808                 case 233 /* ContinueStatement */:
86809                     return visitContinueStatement(node);
86810                 case 235 /* ReturnStatement */:
86811                     return visitReturnStatement(node);
86812                 default:
86813                     if (node.transformFlags & 262144 /* ContainsYield */) {
86814                         return visitJavaScriptContainingYield(node);
86815                     }
86816                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
86817                         return ts.visitEachChild(node, visitor, context);
86818                     }
86819                     else {
86820                         return node;
86821                     }
86822             }
86823         }
86824         /**
86825          * Visits a node that contains a YieldExpression.
86826          *
86827          * @param node The node to visit.
86828          */
86829         function visitJavaScriptContainingYield(node) {
86830             switch (node.kind) {
86831                 case 209 /* BinaryExpression */:
86832                     return visitBinaryExpression(node);
86833                 case 210 /* ConditionalExpression */:
86834                     return visitConditionalExpression(node);
86835                 case 212 /* YieldExpression */:
86836                     return visitYieldExpression(node);
86837                 case 192 /* ArrayLiteralExpression */:
86838                     return visitArrayLiteralExpression(node);
86839                 case 193 /* ObjectLiteralExpression */:
86840                     return visitObjectLiteralExpression(node);
86841                 case 195 /* ElementAccessExpression */:
86842                     return visitElementAccessExpression(node);
86843                 case 196 /* CallExpression */:
86844                     return visitCallExpression(node);
86845                 case 197 /* NewExpression */:
86846                     return visitNewExpression(node);
86847                 default:
86848                     return ts.visitEachChild(node, visitor, context);
86849             }
86850         }
86851         /**
86852          * Visits a generator function.
86853          *
86854          * @param node The node to visit.
86855          */
86856         function visitGenerator(node) {
86857             switch (node.kind) {
86858                 case 244 /* FunctionDeclaration */:
86859                     return visitFunctionDeclaration(node);
86860                 case 201 /* FunctionExpression */:
86861                     return visitFunctionExpression(node);
86862                 default:
86863                     return ts.Debug.failBadSyntaxKind(node);
86864             }
86865         }
86866         /**
86867          * Visits a function declaration.
86868          *
86869          * This will be called when one of the following conditions are met:
86870          * - The function declaration is a generator function.
86871          * - The function declaration is contained within the body of a generator function.
86872          *
86873          * @param node The node to visit.
86874          */
86875         function visitFunctionDeclaration(node) {
86876             // Currently, we only support generators that were originally async functions.
86877             if (node.asteriskToken) {
86878                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
86879                 /*decorators*/ undefined, node.modifiers, 
86880                 /*asteriskToken*/ undefined, node.name, 
86881                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86882                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86883                 /*location*/ node), node);
86884             }
86885             else {
86886                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86887                 var savedInStatementContainingYield = inStatementContainingYield;
86888                 inGeneratorFunctionBody = false;
86889                 inStatementContainingYield = false;
86890                 node = ts.visitEachChild(node, visitor, context);
86891                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86892                 inStatementContainingYield = savedInStatementContainingYield;
86893             }
86894             if (inGeneratorFunctionBody) {
86895                 // Function declarations in a generator function body are hoisted
86896                 // to the top of the lexical scope and elided from the current statement.
86897                 hoistFunctionDeclaration(node);
86898                 return undefined;
86899             }
86900             else {
86901                 return node;
86902             }
86903         }
86904         /**
86905          * Visits a function expression.
86906          *
86907          * This will be called when one of the following conditions are met:
86908          * - The function expression is a generator function.
86909          * - The function expression is contained within the body of a generator function.
86910          *
86911          * @param node The node to visit.
86912          */
86913         function visitFunctionExpression(node) {
86914             // Currently, we only support generators that were originally async functions.
86915             if (node.asteriskToken) {
86916                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
86917                 /*modifiers*/ undefined, 
86918                 /*asteriskToken*/ undefined, node.name, 
86919                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86920                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86921                 /*location*/ node), node);
86922             }
86923             else {
86924                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86925                 var savedInStatementContainingYield = inStatementContainingYield;
86926                 inGeneratorFunctionBody = false;
86927                 inStatementContainingYield = false;
86928                 node = ts.visitEachChild(node, visitor, context);
86929                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86930                 inStatementContainingYield = savedInStatementContainingYield;
86931             }
86932             return node;
86933         }
86934         /**
86935          * Visits a get or set accessor declaration.
86936          *
86937          * This will be called when one of the following conditions are met:
86938          * - The accessor is contained within the body of a generator function.
86939          *
86940          * @param node The node to visit.
86941          */
86942         function visitAccessorDeclaration(node) {
86943             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86944             var savedInStatementContainingYield = inStatementContainingYield;
86945             inGeneratorFunctionBody = false;
86946             inStatementContainingYield = false;
86947             node = ts.visitEachChild(node, visitor, context);
86948             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86949             inStatementContainingYield = savedInStatementContainingYield;
86950             return node;
86951         }
86952         /**
86953          * Transforms the body of a generator function declaration.
86954          *
86955          * @param node The function body to transform.
86956          */
86957         function transformGeneratorFunctionBody(body) {
86958             // Save existing generator state
86959             var statements = [];
86960             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86961             var savedInStatementContainingYield = inStatementContainingYield;
86962             var savedBlocks = blocks;
86963             var savedBlockOffsets = blockOffsets;
86964             var savedBlockActions = blockActions;
86965             var savedBlockStack = blockStack;
86966             var savedLabelOffsets = labelOffsets;
86967             var savedLabelExpressions = labelExpressions;
86968             var savedNextLabelId = nextLabelId;
86969             var savedOperations = operations;
86970             var savedOperationArguments = operationArguments;
86971             var savedOperationLocations = operationLocations;
86972             var savedState = state;
86973             // Initialize generator state
86974             inGeneratorFunctionBody = true;
86975             inStatementContainingYield = false;
86976             blocks = undefined;
86977             blockOffsets = undefined;
86978             blockActions = undefined;
86979             blockStack = undefined;
86980             labelOffsets = undefined;
86981             labelExpressions = undefined;
86982             nextLabelId = 1;
86983             operations = undefined;
86984             operationArguments = undefined;
86985             operationLocations = undefined;
86986             state = ts.createTempVariable(/*recordTempVariable*/ undefined);
86987             // Build the generator
86988             resumeLexicalEnvironment();
86989             var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
86990             transformAndEmitStatements(body.statements, statementOffset);
86991             var buildResult = build();
86992             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86993             statements.push(ts.createReturn(buildResult));
86994             // Restore previous generator state
86995             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86996             inStatementContainingYield = savedInStatementContainingYield;
86997             blocks = savedBlocks;
86998             blockOffsets = savedBlockOffsets;
86999             blockActions = savedBlockActions;
87000             blockStack = savedBlockStack;
87001             labelOffsets = savedLabelOffsets;
87002             labelExpressions = savedLabelExpressions;
87003             nextLabelId = savedNextLabelId;
87004             operations = savedOperations;
87005             operationArguments = savedOperationArguments;
87006             operationLocations = savedOperationLocations;
87007             state = savedState;
87008             return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
87009         }
87010         /**
87011          * Visits a variable statement.
87012          *
87013          * This will be called when one of the following conditions are met:
87014          * - The variable statement is contained within the body of a generator function.
87015          *
87016          * @param node The node to visit.
87017          */
87018         function visitVariableStatement(node) {
87019             if (node.transformFlags & 262144 /* ContainsYield */) {
87020                 transformAndEmitVariableDeclarationList(node.declarationList);
87021                 return undefined;
87022             }
87023             else {
87024                 // Do not hoist custom prologues.
87025                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
87026                     return node;
87027                 }
87028                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
87029                     var variable = _a[_i];
87030                     hoistVariableDeclaration(variable.name);
87031                 }
87032                 var variables = ts.getInitializedVariables(node.declarationList);
87033                 if (variables.length === 0) {
87034                     return undefined;
87035                 }
87036                 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
87037             }
87038         }
87039         /**
87040          * Visits a binary expression.
87041          *
87042          * This will be called when one of the following conditions are met:
87043          * - The node contains a YieldExpression.
87044          *
87045          * @param node The node to visit.
87046          */
87047         function visitBinaryExpression(node) {
87048             var assoc = ts.getExpressionAssociativity(node);
87049             switch (assoc) {
87050                 case 0 /* Left */:
87051                     return visitLeftAssociativeBinaryExpression(node);
87052                 case 1 /* Right */:
87053                     return visitRightAssociativeBinaryExpression(node);
87054                 default:
87055                     return ts.Debug.assertNever(assoc);
87056             }
87057         }
87058         /**
87059          * Visits a right-associative binary expression containing `yield`.
87060          *
87061          * @param node The node to visit.
87062          */
87063         function visitRightAssociativeBinaryExpression(node) {
87064             var left = node.left, right = node.right;
87065             if (containsYield(right)) {
87066                 var target = void 0;
87067                 switch (left.kind) {
87068                     case 194 /* PropertyAccessExpression */:
87069                         // [source]
87070                         //      a.b = yield;
87071                         //
87072                         // [intermediate]
87073                         //  .local _a
87074                         //      _a = a;
87075                         //  .yield resumeLabel
87076                         //  .mark resumeLabel
87077                         //      _a.b = %sent%;
87078                         target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
87079                         break;
87080                     case 195 /* ElementAccessExpression */:
87081                         // [source]
87082                         //      a[b] = yield;
87083                         //
87084                         // [intermediate]
87085                         //  .local _a, _b
87086                         //      _a = a;
87087                         //      _b = b;
87088                         //  .yield resumeLabel
87089                         //  .mark resumeLabel
87090                         //      _a[_b] = %sent%;
87091                         target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
87092                         break;
87093                     default:
87094                         target = ts.visitNode(left, visitor, ts.isExpression);
87095                         break;
87096                 }
87097                 var operator = node.operatorToken.kind;
87098                 if (ts.isCompoundAssignment(operator)) {
87099                     return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
87100                 }
87101                 else {
87102                     return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
87103                 }
87104             }
87105             return ts.visitEachChild(node, visitor, context);
87106         }
87107         function visitLeftAssociativeBinaryExpression(node) {
87108             if (containsYield(node.right)) {
87109                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
87110                     return visitLogicalBinaryExpression(node);
87111                 }
87112                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
87113                     return visitCommaExpression(node);
87114                 }
87115                 // [source]
87116                 //      a() + (yield) + c()
87117                 //
87118                 // [intermediate]
87119                 //  .local _a
87120                 //      _a = a();
87121                 //  .yield resumeLabel
87122                 //      _a + %sent% + c()
87123                 var clone_6 = ts.getMutableClone(node);
87124                 clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
87125                 clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
87126                 return clone_6;
87127             }
87128             return ts.visitEachChild(node, visitor, context);
87129         }
87130         /**
87131          * Visits a logical binary expression containing `yield`.
87132          *
87133          * @param node A node to visit.
87134          */
87135         function visitLogicalBinaryExpression(node) {
87136             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
87137             // to be transformed as such:
87138             //
87139             // [source]
87140             //      x = a() && yield;
87141             //
87142             // [intermediate]
87143             //  .local _a
87144             //      _a = a();
87145             //  .brfalse resultLabel, (_a)
87146             //  .yield resumeLabel
87147             //  .mark resumeLabel
87148             //      _a = %sent%;
87149             //  .mark resultLabel
87150             //      x = _a;
87151             //
87152             // [source]
87153             //      x = a() || yield;
87154             //
87155             // [intermediate]
87156             //  .local _a
87157             //      _a = a();
87158             //  .brtrue resultLabel, (_a)
87159             //  .yield resumeLabel
87160             //  .mark resumeLabel
87161             //      _a = %sent%;
87162             //  .mark resultLabel
87163             //      x = _a;
87164             var resultLabel = defineLabel();
87165             var resultLocal = declareLocal();
87166             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
87167             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
87168                 // Logical `&&` shortcuts when the left-hand operand is falsey.
87169                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
87170             }
87171             else {
87172                 // Logical `||` shortcuts when the left-hand operand is truthy.
87173                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
87174             }
87175             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
87176             markLabel(resultLabel);
87177             return resultLocal;
87178         }
87179         /**
87180          * Visits a comma expression containing `yield`.
87181          *
87182          * @param node The node to visit.
87183          */
87184         function visitCommaExpression(node) {
87185             // [source]
87186             //      x = a(), yield, b();
87187             //
87188             // [intermediate]
87189             //      a();
87190             //  .yield resumeLabel
87191             //  .mark resumeLabel
87192             //      x = %sent%, b();
87193             var pendingExpressions = [];
87194             visit(node.left);
87195             visit(node.right);
87196             return ts.inlineExpressions(pendingExpressions);
87197             function visit(node) {
87198                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
87199                     visit(node.left);
87200                     visit(node.right);
87201                 }
87202                 else {
87203                     if (containsYield(node) && pendingExpressions.length > 0) {
87204                         emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
87205                         pendingExpressions = [];
87206                     }
87207                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
87208                 }
87209             }
87210         }
87211         /**
87212          * Visits a conditional expression containing `yield`.
87213          *
87214          * @param node The node to visit.
87215          */
87216         function visitConditionalExpression(node) {
87217             // [source]
87218             //      x = a() ? yield : b();
87219             //
87220             // [intermediate]
87221             //  .local _a
87222             //  .brfalse whenFalseLabel, (a())
87223             //  .yield resumeLabel
87224             //  .mark resumeLabel
87225             //      _a = %sent%;
87226             //  .br resultLabel
87227             //  .mark whenFalseLabel
87228             //      _a = b();
87229             //  .mark resultLabel
87230             //      x = _a;
87231             // We only need to perform a specific transformation if a `yield` expression exists
87232             // in either the `whenTrue` or `whenFalse` branches.
87233             // A `yield` in the condition will be handled by the normal visitor.
87234             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
87235                 var whenFalseLabel = defineLabel();
87236                 var resultLabel = defineLabel();
87237                 var resultLocal = declareLocal();
87238                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
87239                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
87240                 emitBreak(resultLabel);
87241                 markLabel(whenFalseLabel);
87242                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
87243                 markLabel(resultLabel);
87244                 return resultLocal;
87245             }
87246             return ts.visitEachChild(node, visitor, context);
87247         }
87248         /**
87249          * Visits a `yield` expression.
87250          *
87251          * @param node The node to visit.
87252          */
87253         function visitYieldExpression(node) {
87254             // [source]
87255             //      x = yield a();
87256             //
87257             // [intermediate]
87258             //  .yield resumeLabel, (a())
87259             //  .mark resumeLabel
87260             //      x = %sent%;
87261             var resumeLabel = defineLabel();
87262             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87263             if (node.asteriskToken) {
87264                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
87265                     ? ts.createValuesHelper(context, expression, /*location*/ node)
87266                     : expression;
87267                 emitYieldStar(iterator, /*location*/ node);
87268             }
87269             else {
87270                 emitYield(expression, /*location*/ node);
87271             }
87272             markLabel(resumeLabel);
87273             return createGeneratorResume(/*location*/ node);
87274         }
87275         /**
87276          * Visits an ArrayLiteralExpression that contains a YieldExpression.
87277          *
87278          * @param node The node to visit.
87279          */
87280         function visitArrayLiteralExpression(node) {
87281             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
87282         }
87283         /**
87284          * Visits an array of expressions containing one or more YieldExpression nodes
87285          * and returns an expression for the resulting value.
87286          *
87287          * @param elements The elements to visit.
87288          * @param multiLine Whether array literals created should be emitted on multiple lines.
87289          */
87290         function visitElements(elements, leadingElement, location, multiLine) {
87291             // [source]
87292             //      ar = [1, yield, 2];
87293             //
87294             // [intermediate]
87295             //  .local _a
87296             //      _a = [1];
87297             //  .yield resumeLabel
87298             //  .mark resumeLabel
87299             //      ar = _a.concat([%sent%, 2]);
87300             var numInitialElements = countInitialNodesWithoutYield(elements);
87301             var temp;
87302             if (numInitialElements > 0) {
87303                 temp = declareLocal();
87304                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
87305                 emitAssignment(temp, ts.createArrayLiteral(leadingElement
87306                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
87307                 leadingElement = undefined;
87308             }
87309             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
87310             return temp
87311                 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87312                 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
87313             function reduceElement(expressions, element) {
87314                 if (containsYield(element) && expressions.length > 0) {
87315                     var hasAssignedTemp = temp !== undefined;
87316                     if (!temp) {
87317                         temp = declareLocal();
87318                     }
87319                     emitAssignment(temp, hasAssignedTemp
87320                         ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87321                         : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
87322                     leadingElement = undefined;
87323                     expressions = [];
87324                 }
87325                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
87326                 return expressions;
87327             }
87328         }
87329         function visitObjectLiteralExpression(node) {
87330             // [source]
87331             //      o = {
87332             //          a: 1,
87333             //          b: yield,
87334             //          c: 2
87335             //      };
87336             //
87337             // [intermediate]
87338             //  .local _a
87339             //      _a = {
87340             //          a: 1
87341             //      };
87342             //  .yield resumeLabel
87343             //  .mark resumeLabel
87344             //      o = (_a.b = %sent%,
87345             //          _a.c = 2,
87346             //          _a);
87347             var properties = node.properties;
87348             var multiLine = node.multiLine;
87349             var numInitialProperties = countInitialNodesWithoutYield(properties);
87350             var temp = declareLocal();
87351             emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
87352             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
87353             expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
87354             return ts.inlineExpressions(expressions);
87355             function reduceProperty(expressions, property) {
87356                 if (containsYield(property) && expressions.length > 0) {
87357                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
87358                     expressions = [];
87359                 }
87360                 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
87361                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
87362                 if (visited) {
87363                     if (multiLine) {
87364                         ts.startOnNewLine(visited);
87365                     }
87366                     expressions.push(visited);
87367                 }
87368                 return expressions;
87369             }
87370         }
87371         /**
87372          * Visits an ElementAccessExpression that contains a YieldExpression.
87373          *
87374          * @param node The node to visit.
87375          */
87376         function visitElementAccessExpression(node) {
87377             if (containsYield(node.argumentExpression)) {
87378                 // [source]
87379                 //      a = x[yield];
87380                 //
87381                 // [intermediate]
87382                 //  .local _a
87383                 //      _a = x;
87384                 //  .yield resumeLabel
87385                 //  .mark resumeLabel
87386                 //      a = _a[%sent%]
87387                 var clone_7 = ts.getMutableClone(node);
87388                 clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
87389                 clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
87390                 return clone_7;
87391             }
87392             return ts.visitEachChild(node, visitor, context);
87393         }
87394         function visitCallExpression(node) {
87395             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
87396                 // [source]
87397                 //      a.b(1, yield, 2);
87398                 //
87399                 // [intermediate]
87400                 //  .local _a, _b, _c
87401                 //      _b = (_a = a).b;
87402                 //      _c = [1];
87403                 //  .yield resumeLabel
87404                 //  .mark resumeLabel
87405                 //      _b.apply(_a, _c.concat([%sent%, 2]));
87406                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
87407                 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
87408                 /*location*/ node), node);
87409             }
87410             return ts.visitEachChild(node, visitor, context);
87411         }
87412         function visitNewExpression(node) {
87413             if (ts.forEach(node.arguments, containsYield)) {
87414                 // [source]
87415                 //      new a.b(1, yield, 2);
87416                 //
87417                 // [intermediate]
87418                 //  .local _a, _b, _c
87419                 //      _b = (_a = a.b).bind;
87420                 //      _c = [1];
87421                 //  .yield resumeLabel
87422                 //  .mark resumeLabel
87423                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
87424                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
87425                 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
87426                 /*leadingElement*/ ts.createVoidZero())), 
87427                 /*typeArguments*/ undefined, []), node), node);
87428             }
87429             return ts.visitEachChild(node, visitor, context);
87430         }
87431         function transformAndEmitStatements(statements, start) {
87432             if (start === void 0) { start = 0; }
87433             var numStatements = statements.length;
87434             for (var i = start; i < numStatements; i++) {
87435                 transformAndEmitStatement(statements[i]);
87436             }
87437         }
87438         function transformAndEmitEmbeddedStatement(node) {
87439             if (ts.isBlock(node)) {
87440                 transformAndEmitStatements(node.statements);
87441             }
87442             else {
87443                 transformAndEmitStatement(node);
87444             }
87445         }
87446         function transformAndEmitStatement(node) {
87447             var savedInStatementContainingYield = inStatementContainingYield;
87448             if (!inStatementContainingYield) {
87449                 inStatementContainingYield = containsYield(node);
87450             }
87451             transformAndEmitStatementWorker(node);
87452             inStatementContainingYield = savedInStatementContainingYield;
87453         }
87454         function transformAndEmitStatementWorker(node) {
87455             switch (node.kind) {
87456                 case 223 /* Block */:
87457                     return transformAndEmitBlock(node);
87458                 case 226 /* ExpressionStatement */:
87459                     return transformAndEmitExpressionStatement(node);
87460                 case 227 /* IfStatement */:
87461                     return transformAndEmitIfStatement(node);
87462                 case 228 /* DoStatement */:
87463                     return transformAndEmitDoStatement(node);
87464                 case 229 /* WhileStatement */:
87465                     return transformAndEmitWhileStatement(node);
87466                 case 230 /* ForStatement */:
87467                     return transformAndEmitForStatement(node);
87468                 case 231 /* ForInStatement */:
87469                     return transformAndEmitForInStatement(node);
87470                 case 233 /* ContinueStatement */:
87471                     return transformAndEmitContinueStatement(node);
87472                 case 234 /* BreakStatement */:
87473                     return transformAndEmitBreakStatement(node);
87474                 case 235 /* ReturnStatement */:
87475                     return transformAndEmitReturnStatement(node);
87476                 case 236 /* WithStatement */:
87477                     return transformAndEmitWithStatement(node);
87478                 case 237 /* SwitchStatement */:
87479                     return transformAndEmitSwitchStatement(node);
87480                 case 238 /* LabeledStatement */:
87481                     return transformAndEmitLabeledStatement(node);
87482                 case 239 /* ThrowStatement */:
87483                     return transformAndEmitThrowStatement(node);
87484                 case 240 /* TryStatement */:
87485                     return transformAndEmitTryStatement(node);
87486                 default:
87487                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87488             }
87489         }
87490         function transformAndEmitBlock(node) {
87491             if (containsYield(node)) {
87492                 transformAndEmitStatements(node.statements);
87493             }
87494             else {
87495                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87496             }
87497         }
87498         function transformAndEmitExpressionStatement(node) {
87499             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87500         }
87501         function transformAndEmitVariableDeclarationList(node) {
87502             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
87503                 var variable = _a[_i];
87504                 var name = ts.getSynthesizedClone(variable.name);
87505                 ts.setCommentRange(name, variable.name);
87506                 hoistVariableDeclaration(name);
87507             }
87508             var variables = ts.getInitializedVariables(node);
87509             var numVariables = variables.length;
87510             var variablesWritten = 0;
87511             var pendingExpressions = [];
87512             while (variablesWritten < numVariables) {
87513                 for (var i = variablesWritten; i < numVariables; i++) {
87514                     var variable = variables[i];
87515                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
87516                         break;
87517                     }
87518                     pendingExpressions.push(transformInitializedVariable(variable));
87519                 }
87520                 if (pendingExpressions.length) {
87521                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
87522                     variablesWritten += pendingExpressions.length;
87523                     pendingExpressions = [];
87524                 }
87525             }
87526             return undefined;
87527         }
87528         function transformInitializedVariable(node) {
87529             return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
87530         }
87531         function transformAndEmitIfStatement(node) {
87532             if (containsYield(node)) {
87533                 // [source]
87534                 //      if (x)
87535                 //          /*thenStatement*/
87536                 //      else
87537                 //          /*elseStatement*/
87538                 //
87539                 // [intermediate]
87540                 //  .brfalse elseLabel, (x)
87541                 //      /*thenStatement*/
87542                 //  .br endLabel
87543                 //  .mark elseLabel
87544                 //      /*elseStatement*/
87545                 //  .mark endLabel
87546                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
87547                     var endLabel = defineLabel();
87548                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
87549                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
87550                     transformAndEmitEmbeddedStatement(node.thenStatement);
87551                     if (node.elseStatement) {
87552                         emitBreak(endLabel);
87553                         markLabel(elseLabel);
87554                         transformAndEmitEmbeddedStatement(node.elseStatement);
87555                     }
87556                     markLabel(endLabel);
87557                 }
87558                 else {
87559                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87560                 }
87561             }
87562             else {
87563                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87564             }
87565         }
87566         function transformAndEmitDoStatement(node) {
87567             if (containsYield(node)) {
87568                 // [source]
87569                 //      do {
87570                 //          /*body*/
87571                 //      }
87572                 //      while (i < 10);
87573                 //
87574                 // [intermediate]
87575                 //  .loop conditionLabel, endLabel
87576                 //  .mark loopLabel
87577                 //      /*body*/
87578                 //  .mark conditionLabel
87579                 //  .brtrue loopLabel, (i < 10)
87580                 //  .endloop
87581                 //  .mark endLabel
87582                 var conditionLabel = defineLabel();
87583                 var loopLabel = defineLabel();
87584                 beginLoopBlock(/*continueLabel*/ conditionLabel);
87585                 markLabel(loopLabel);
87586                 transformAndEmitEmbeddedStatement(node.statement);
87587                 markLabel(conditionLabel);
87588                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87589                 endLoopBlock();
87590             }
87591             else {
87592                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87593             }
87594         }
87595         function visitDoStatement(node) {
87596             if (inStatementContainingYield) {
87597                 beginScriptLoopBlock();
87598                 node = ts.visitEachChild(node, visitor, context);
87599                 endLoopBlock();
87600                 return node;
87601             }
87602             else {
87603                 return ts.visitEachChild(node, visitor, context);
87604             }
87605         }
87606         function transformAndEmitWhileStatement(node) {
87607             if (containsYield(node)) {
87608                 // [source]
87609                 //      while (i < 10) {
87610                 //          /*body*/
87611                 //      }
87612                 //
87613                 // [intermediate]
87614                 //  .loop loopLabel, endLabel
87615                 //  .mark loopLabel
87616                 //  .brfalse endLabel, (i < 10)
87617                 //      /*body*/
87618                 //  .br loopLabel
87619                 //  .endloop
87620                 //  .mark endLabel
87621                 var loopLabel = defineLabel();
87622                 var endLabel = beginLoopBlock(loopLabel);
87623                 markLabel(loopLabel);
87624                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87625                 transformAndEmitEmbeddedStatement(node.statement);
87626                 emitBreak(loopLabel);
87627                 endLoopBlock();
87628             }
87629             else {
87630                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87631             }
87632         }
87633         function visitWhileStatement(node) {
87634             if (inStatementContainingYield) {
87635                 beginScriptLoopBlock();
87636                 node = ts.visitEachChild(node, visitor, context);
87637                 endLoopBlock();
87638                 return node;
87639             }
87640             else {
87641                 return ts.visitEachChild(node, visitor, context);
87642             }
87643         }
87644         function transformAndEmitForStatement(node) {
87645             if (containsYield(node)) {
87646                 // [source]
87647                 //      for (var i = 0; i < 10; i++) {
87648                 //          /*body*/
87649                 //      }
87650                 //
87651                 // [intermediate]
87652                 //  .local i
87653                 //      i = 0;
87654                 //  .loop incrementLabel, endLoopLabel
87655                 //  .mark conditionLabel
87656                 //  .brfalse endLoopLabel, (i < 10)
87657                 //      /*body*/
87658                 //  .mark incrementLabel
87659                 //      i++;
87660                 //  .br conditionLabel
87661                 //  .endloop
87662                 //  .mark endLoopLabel
87663                 var conditionLabel = defineLabel();
87664                 var incrementLabel = defineLabel();
87665                 var endLabel = beginLoopBlock(incrementLabel);
87666                 if (node.initializer) {
87667                     var initializer = node.initializer;
87668                     if (ts.isVariableDeclarationList(initializer)) {
87669                         transformAndEmitVariableDeclarationList(initializer);
87670                     }
87671                     else {
87672                         emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
87673                     }
87674                 }
87675                 markLabel(conditionLabel);
87676                 if (node.condition) {
87677                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
87678                 }
87679                 transformAndEmitEmbeddedStatement(node.statement);
87680                 markLabel(incrementLabel);
87681                 if (node.incrementor) {
87682                     emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
87683                 }
87684                 emitBreak(conditionLabel);
87685                 endLoopBlock();
87686             }
87687             else {
87688                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87689             }
87690         }
87691         function visitForStatement(node) {
87692             if (inStatementContainingYield) {
87693                 beginScriptLoopBlock();
87694             }
87695             var initializer = node.initializer;
87696             if (initializer && ts.isVariableDeclarationList(initializer)) {
87697                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87698                     var variable = _a[_i];
87699                     hoistVariableDeclaration(variable.name);
87700                 }
87701                 var variables = ts.getInitializedVariables(initializer);
87702                 node = ts.updateFor(node, variables.length > 0
87703                     ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
87704                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87705             }
87706             else {
87707                 node = ts.visitEachChild(node, visitor, context);
87708             }
87709             if (inStatementContainingYield) {
87710                 endLoopBlock();
87711             }
87712             return node;
87713         }
87714         function transformAndEmitForInStatement(node) {
87715             // TODO(rbuckton): Source map locations
87716             if (containsYield(node)) {
87717                 // [source]
87718                 //      for (var p in o) {
87719                 //          /*body*/
87720                 //      }
87721                 //
87722                 // [intermediate]
87723                 //  .local _a, _b, _i
87724                 //      _a = [];
87725                 //      for (_b in o) _a.push(_b);
87726                 //      _i = 0;
87727                 //  .loop incrementLabel, endLoopLabel
87728                 //  .mark conditionLabel
87729                 //  .brfalse endLoopLabel, (_i < _a.length)
87730                 //      p = _a[_i];
87731                 //      /*body*/
87732                 //  .mark incrementLabel
87733                 //      _b++;
87734                 //  .br conditionLabel
87735                 //  .endloop
87736                 //  .mark endLoopLabel
87737                 var keysArray = declareLocal(); // _a
87738                 var key = declareLocal(); // _b
87739                 var keysIndex = ts.createLoopVariable(); // _i
87740                 var initializer = node.initializer;
87741                 hoistVariableDeclaration(keysIndex);
87742                 emitAssignment(keysArray, ts.createArrayLiteral());
87743                 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
87744                 /*typeArguments*/ undefined, [key]))));
87745                 emitAssignment(keysIndex, ts.createLiteral(0));
87746                 var conditionLabel = defineLabel();
87747                 var incrementLabel = defineLabel();
87748                 var endLabel = beginLoopBlock(incrementLabel);
87749                 markLabel(conditionLabel);
87750                 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
87751                 var variable = void 0;
87752                 if (ts.isVariableDeclarationList(initializer)) {
87753                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87754                         var variable_1 = _a[_i];
87755                         hoistVariableDeclaration(variable_1.name);
87756                     }
87757                     variable = ts.getSynthesizedClone(initializer.declarations[0].name);
87758                 }
87759                 else {
87760                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
87761                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
87762                 }
87763                 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
87764                 transformAndEmitEmbeddedStatement(node.statement);
87765                 markLabel(incrementLabel);
87766                 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
87767                 emitBreak(conditionLabel);
87768                 endLoopBlock();
87769             }
87770             else {
87771                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87772             }
87773         }
87774         function visitForInStatement(node) {
87775             // [source]
87776             //      for (var x in a) {
87777             //          /*body*/
87778             //      }
87779             //
87780             // [intermediate]
87781             //  .local x
87782             //  .loop
87783             //      for (x in a) {
87784             //          /*body*/
87785             //      }
87786             //  .endloop
87787             if (inStatementContainingYield) {
87788                 beginScriptLoopBlock();
87789             }
87790             var initializer = node.initializer;
87791             if (ts.isVariableDeclarationList(initializer)) {
87792                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87793                     var variable = _a[_i];
87794                     hoistVariableDeclaration(variable.name);
87795                 }
87796                 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87797             }
87798             else {
87799                 node = ts.visitEachChild(node, visitor, context);
87800             }
87801             if (inStatementContainingYield) {
87802                 endLoopBlock();
87803             }
87804             return node;
87805         }
87806         function transformAndEmitContinueStatement(node) {
87807             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
87808             if (label > 0) {
87809                 emitBreak(label, /*location*/ node);
87810             }
87811             else {
87812                 // invalid continue without a containing loop. Leave the node as is, per #17875.
87813                 emitStatement(node);
87814             }
87815         }
87816         function visitContinueStatement(node) {
87817             if (inStatementContainingYield) {
87818                 var label = findContinueTarget(node.label && ts.idText(node.label));
87819                 if (label > 0) {
87820                     return createInlineBreak(label, /*location*/ node);
87821                 }
87822             }
87823             return ts.visitEachChild(node, visitor, context);
87824         }
87825         function transformAndEmitBreakStatement(node) {
87826             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
87827             if (label > 0) {
87828                 emitBreak(label, /*location*/ node);
87829             }
87830             else {
87831                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
87832                 emitStatement(node);
87833             }
87834         }
87835         function visitBreakStatement(node) {
87836             if (inStatementContainingYield) {
87837                 var label = findBreakTarget(node.label && ts.idText(node.label));
87838                 if (label > 0) {
87839                     return createInlineBreak(label, /*location*/ node);
87840                 }
87841             }
87842             return ts.visitEachChild(node, visitor, context);
87843         }
87844         function transformAndEmitReturnStatement(node) {
87845             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87846             /*location*/ node);
87847         }
87848         function visitReturnStatement(node) {
87849             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87850             /*location*/ node);
87851         }
87852         function transformAndEmitWithStatement(node) {
87853             if (containsYield(node)) {
87854                 // [source]
87855                 //      with (x) {
87856                 //          /*body*/
87857                 //      }
87858                 //
87859                 // [intermediate]
87860                 //  .with (x)
87861                 //      /*body*/
87862                 //  .endwith
87863                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
87864                 transformAndEmitEmbeddedStatement(node.statement);
87865                 endWithBlock();
87866             }
87867             else {
87868                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87869             }
87870         }
87871         function transformAndEmitSwitchStatement(node) {
87872             if (containsYield(node.caseBlock)) {
87873                 // [source]
87874                 //      switch (x) {
87875                 //          case a:
87876                 //              /*caseStatements*/
87877                 //          case b:
87878                 //              /*caseStatements*/
87879                 //          default:
87880                 //              /*defaultStatements*/
87881                 //      }
87882                 //
87883                 // [intermediate]
87884                 //  .local _a
87885                 //  .switch endLabel
87886                 //      _a = x;
87887                 //      switch (_a) {
87888                 //          case a:
87889                 //  .br clauseLabels[0]
87890                 //      }
87891                 //      switch (_a) {
87892                 //          case b:
87893                 //  .br clauseLabels[1]
87894                 //      }
87895                 //  .br clauseLabels[2]
87896                 //  .mark clauseLabels[0]
87897                 //      /*caseStatements*/
87898                 //  .mark clauseLabels[1]
87899                 //      /*caseStatements*/
87900                 //  .mark clauseLabels[2]
87901                 //      /*caseStatements*/
87902                 //  .endswitch
87903                 //  .mark endLabel
87904                 var caseBlock = node.caseBlock;
87905                 var numClauses = caseBlock.clauses.length;
87906                 var endLabel = beginSwitchBlock();
87907                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
87908                 // Create labels for each clause and find the index of the first default clause.
87909                 var clauseLabels = [];
87910                 var defaultClauseIndex = -1;
87911                 for (var i = 0; i < numClauses; i++) {
87912                     var clause = caseBlock.clauses[i];
87913                     clauseLabels.push(defineLabel());
87914                     if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
87915                         defaultClauseIndex = i;
87916                     }
87917                 }
87918                 // Emit switch statements for each run of case clauses either from the first case
87919                 // clause or the next case clause with a `yield` in its expression, up to the next
87920                 // case clause with a `yield` in its expression.
87921                 var clausesWritten = 0;
87922                 var pendingClauses = [];
87923                 while (clausesWritten < numClauses) {
87924                     var defaultClausesSkipped = 0;
87925                     for (var i = clausesWritten; i < numClauses; i++) {
87926                         var clause = caseBlock.clauses[i];
87927                         if (clause.kind === 277 /* CaseClause */) {
87928                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
87929                                 break;
87930                             }
87931                             pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
87932                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
87933                             ]));
87934                         }
87935                         else {
87936                             defaultClausesSkipped++;
87937                         }
87938                     }
87939                     if (pendingClauses.length) {
87940                         emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
87941                         clausesWritten += pendingClauses.length;
87942                         pendingClauses = [];
87943                     }
87944                     if (defaultClausesSkipped > 0) {
87945                         clausesWritten += defaultClausesSkipped;
87946                         defaultClausesSkipped = 0;
87947                     }
87948                 }
87949                 if (defaultClauseIndex >= 0) {
87950                     emitBreak(clauseLabels[defaultClauseIndex]);
87951                 }
87952                 else {
87953                     emitBreak(endLabel);
87954                 }
87955                 for (var i = 0; i < numClauses; i++) {
87956                     markLabel(clauseLabels[i]);
87957                     transformAndEmitStatements(caseBlock.clauses[i].statements);
87958                 }
87959                 endSwitchBlock();
87960             }
87961             else {
87962                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87963             }
87964         }
87965         function visitSwitchStatement(node) {
87966             if (inStatementContainingYield) {
87967                 beginScriptSwitchBlock();
87968             }
87969             node = ts.visitEachChild(node, visitor, context);
87970             if (inStatementContainingYield) {
87971                 endSwitchBlock();
87972             }
87973             return node;
87974         }
87975         function transformAndEmitLabeledStatement(node) {
87976             if (containsYield(node)) {
87977                 // [source]
87978                 //      x: {
87979                 //          /*body*/
87980                 //      }
87981                 //
87982                 // [intermediate]
87983                 //  .labeled "x", endLabel
87984                 //      /*body*/
87985                 //  .endlabeled
87986                 //  .mark endLabel
87987                 beginLabeledBlock(ts.idText(node.label));
87988                 transformAndEmitEmbeddedStatement(node.statement);
87989                 endLabeledBlock();
87990             }
87991             else {
87992                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87993             }
87994         }
87995         function visitLabeledStatement(node) {
87996             if (inStatementContainingYield) {
87997                 beginScriptLabeledBlock(ts.idText(node.label));
87998             }
87999             node = ts.visitEachChild(node, visitor, context);
88000             if (inStatementContainingYield) {
88001                 endLabeledBlock();
88002             }
88003             return node;
88004         }
88005         function transformAndEmitThrowStatement(node) {
88006             emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
88007             /*location*/ node);
88008         }
88009         function transformAndEmitTryStatement(node) {
88010             if (containsYield(node)) {
88011                 // [source]
88012                 //      try {
88013                 //          /*tryBlock*/
88014                 //      }
88015                 //      catch (e) {
88016                 //          /*catchBlock*/
88017                 //      }
88018                 //      finally {
88019                 //          /*finallyBlock*/
88020                 //      }
88021                 //
88022                 // [intermediate]
88023                 //  .local _a
88024                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
88025                 //  .mark tryLabel
88026                 //  .nop
88027                 //      /*tryBlock*/
88028                 //  .br endLabel
88029                 //  .catch
88030                 //  .mark catchLabel
88031                 //      _a = %error%;
88032                 //      /*catchBlock*/
88033                 //  .br endLabel
88034                 //  .finally
88035                 //  .mark finallyLabel
88036                 //      /*finallyBlock*/
88037                 //  .endfinally
88038                 //  .endtry
88039                 //  .mark endLabel
88040                 beginExceptionBlock();
88041                 transformAndEmitEmbeddedStatement(node.tryBlock);
88042                 if (node.catchClause) {
88043                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
88044                     transformAndEmitEmbeddedStatement(node.catchClause.block);
88045                 }
88046                 if (node.finallyBlock) {
88047                     beginFinallyBlock();
88048                     transformAndEmitEmbeddedStatement(node.finallyBlock);
88049                 }
88050                 endExceptionBlock();
88051             }
88052             else {
88053                 emitStatement(ts.visitEachChild(node, visitor, context));
88054             }
88055         }
88056         function containsYield(node) {
88057             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
88058         }
88059         function countInitialNodesWithoutYield(nodes) {
88060             var numNodes = nodes.length;
88061             for (var i = 0; i < numNodes; i++) {
88062                 if (containsYield(nodes[i])) {
88063                     return i;
88064                 }
88065             }
88066             return -1;
88067         }
88068         function onSubstituteNode(hint, node) {
88069             node = previousOnSubstituteNode(hint, node);
88070             if (hint === 1 /* Expression */) {
88071                 return substituteExpression(node);
88072             }
88073             return node;
88074         }
88075         function substituteExpression(node) {
88076             if (ts.isIdentifier(node)) {
88077                 return substituteExpressionIdentifier(node);
88078             }
88079             return node;
88080         }
88081         function substituteExpressionIdentifier(node) {
88082             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
88083                 var original = ts.getOriginalNode(node);
88084                 if (ts.isIdentifier(original) && original.parent) {
88085                     var declaration = resolver.getReferencedValueDeclaration(original);
88086                     if (declaration) {
88087                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
88088                         if (name) {
88089                             var clone_8 = ts.getMutableClone(name);
88090                             ts.setSourceMapRange(clone_8, node);
88091                             ts.setCommentRange(clone_8, node);
88092                             return clone_8;
88093                         }
88094                     }
88095                 }
88096             }
88097             return node;
88098         }
88099         function cacheExpression(node) {
88100             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
88101                 return node;
88102             }
88103             var temp = ts.createTempVariable(hoistVariableDeclaration);
88104             emitAssignment(temp, node, /*location*/ node);
88105             return temp;
88106         }
88107         function declareLocal(name) {
88108             var temp = name
88109                 ? ts.createUniqueName(name)
88110                 : ts.createTempVariable(/*recordTempVariable*/ undefined);
88111             hoistVariableDeclaration(temp);
88112             return temp;
88113         }
88114         /**
88115          * Defines a label, uses as the target of a Break operation.
88116          */
88117         function defineLabel() {
88118             if (!labelOffsets) {
88119                 labelOffsets = [];
88120             }
88121             var label = nextLabelId;
88122             nextLabelId++;
88123             labelOffsets[label] = -1;
88124             return label;
88125         }
88126         /**
88127          * Marks the current operation with the specified label.
88128          */
88129         function markLabel(label) {
88130             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
88131             labelOffsets[label] = operations ? operations.length : 0;
88132         }
88133         /**
88134          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
88135          *
88136          * @param block Information about the block.
88137          */
88138         function beginBlock(block) {
88139             if (!blocks) {
88140                 blocks = [];
88141                 blockActions = [];
88142                 blockOffsets = [];
88143                 blockStack = [];
88144             }
88145             var index = blockActions.length;
88146             blockActions[index] = 0 /* Open */;
88147             blockOffsets[index] = operations ? operations.length : 0;
88148             blocks[index] = block;
88149             blockStack.push(block);
88150             return index;
88151         }
88152         /**
88153          * Ends the current block operation.
88154          */
88155         function endBlock() {
88156             var block = peekBlock();
88157             if (block === undefined)
88158                 return ts.Debug.fail("beginBlock was never called.");
88159             var index = blockActions.length;
88160             blockActions[index] = 1 /* Close */;
88161             blockOffsets[index] = operations ? operations.length : 0;
88162             blocks[index] = block;
88163             blockStack.pop();
88164             return block;
88165         }
88166         /**
88167          * Gets the current open block.
88168          */
88169         function peekBlock() {
88170             return ts.lastOrUndefined(blockStack);
88171         }
88172         /**
88173          * Gets the kind of the current open block.
88174          */
88175         function peekBlockKind() {
88176             var block = peekBlock();
88177             return block && block.kind;
88178         }
88179         /**
88180          * Begins a code block for a generated `with` statement.
88181          *
88182          * @param expression An identifier representing expression for the `with` block.
88183          */
88184         function beginWithBlock(expression) {
88185             var startLabel = defineLabel();
88186             var endLabel = defineLabel();
88187             markLabel(startLabel);
88188             beginBlock({
88189                 kind: 1 /* With */,
88190                 expression: expression,
88191                 startLabel: startLabel,
88192                 endLabel: endLabel
88193             });
88194         }
88195         /**
88196          * Ends a code block for a generated `with` statement.
88197          */
88198         function endWithBlock() {
88199             ts.Debug.assert(peekBlockKind() === 1 /* With */);
88200             var block = endBlock();
88201             markLabel(block.endLabel);
88202         }
88203         /**
88204          * Begins a code block for a generated `try` statement.
88205          */
88206         function beginExceptionBlock() {
88207             var startLabel = defineLabel();
88208             var endLabel = defineLabel();
88209             markLabel(startLabel);
88210             beginBlock({
88211                 kind: 0 /* Exception */,
88212                 state: 0 /* Try */,
88213                 startLabel: startLabel,
88214                 endLabel: endLabel
88215             });
88216             emitNop();
88217             return endLabel;
88218         }
88219         /**
88220          * Enters the `catch` clause of a generated `try` statement.
88221          *
88222          * @param variable The catch variable.
88223          */
88224         function beginCatchBlock(variable) {
88225             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88226             // generated identifiers should already be unique within a file
88227             var name;
88228             if (ts.isGeneratedIdentifier(variable.name)) {
88229                 name = variable.name;
88230                 hoistVariableDeclaration(variable.name);
88231             }
88232             else {
88233                 var text = ts.idText(variable.name);
88234                 name = declareLocal(text);
88235                 if (!renamedCatchVariables) {
88236                     renamedCatchVariables = ts.createMap();
88237                     renamedCatchVariableDeclarations = [];
88238                     context.enableSubstitution(75 /* Identifier */);
88239                 }
88240                 renamedCatchVariables.set(text, true);
88241                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
88242             }
88243             var exception = peekBlock();
88244             ts.Debug.assert(exception.state < 1 /* Catch */);
88245             var endLabel = exception.endLabel;
88246             emitBreak(endLabel);
88247             var catchLabel = defineLabel();
88248             markLabel(catchLabel);
88249             exception.state = 1 /* Catch */;
88250             exception.catchVariable = name;
88251             exception.catchLabel = catchLabel;
88252             emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
88253             emitNop();
88254         }
88255         /**
88256          * Enters the `finally` block of a generated `try` statement.
88257          */
88258         function beginFinallyBlock() {
88259             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88260             var exception = peekBlock();
88261             ts.Debug.assert(exception.state < 2 /* Finally */);
88262             var endLabel = exception.endLabel;
88263             emitBreak(endLabel);
88264             var finallyLabel = defineLabel();
88265             markLabel(finallyLabel);
88266             exception.state = 2 /* Finally */;
88267             exception.finallyLabel = finallyLabel;
88268         }
88269         /**
88270          * Ends the code block for a generated `try` statement.
88271          */
88272         function endExceptionBlock() {
88273             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88274             var exception = endBlock();
88275             var state = exception.state;
88276             if (state < 2 /* Finally */) {
88277                 emitBreak(exception.endLabel);
88278             }
88279             else {
88280                 emitEndfinally();
88281             }
88282             markLabel(exception.endLabel);
88283             emitNop();
88284             exception.state = 3 /* Done */;
88285         }
88286         /**
88287          * Begins a code block that supports `break` or `continue` statements that are defined in
88288          * the source tree and not from generated code.
88289          *
88290          * @param labelText Names from containing labeled statements.
88291          */
88292         function beginScriptLoopBlock() {
88293             beginBlock({
88294                 kind: 3 /* Loop */,
88295                 isScript: true,
88296                 breakLabel: -1,
88297                 continueLabel: -1
88298             });
88299         }
88300         /**
88301          * Begins a code block that supports `break` or `continue` statements that are defined in
88302          * generated code. Returns a label used to mark the operation to which to jump when a
88303          * `break` statement targets this block.
88304          *
88305          * @param continueLabel A Label used to mark the operation to which to jump when a
88306          *                      `continue` statement targets this block.
88307          */
88308         function beginLoopBlock(continueLabel) {
88309             var breakLabel = defineLabel();
88310             beginBlock({
88311                 kind: 3 /* Loop */,
88312                 isScript: false,
88313                 breakLabel: breakLabel,
88314                 continueLabel: continueLabel,
88315             });
88316             return breakLabel;
88317         }
88318         /**
88319          * Ends a code block that supports `break` or `continue` statements that are defined in
88320          * generated code or in the source tree.
88321          */
88322         function endLoopBlock() {
88323             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
88324             var block = endBlock();
88325             var breakLabel = block.breakLabel;
88326             if (!block.isScript) {
88327                 markLabel(breakLabel);
88328             }
88329         }
88330         /**
88331          * Begins a code block that supports `break` statements that are defined in the source
88332          * tree and not from generated code.
88333          *
88334          */
88335         function beginScriptSwitchBlock() {
88336             beginBlock({
88337                 kind: 2 /* Switch */,
88338                 isScript: true,
88339                 breakLabel: -1
88340             });
88341         }
88342         /**
88343          * Begins a code block that supports `break` statements that are defined in generated code.
88344          * Returns a label used to mark the operation to which to jump when a `break` statement
88345          * targets this block.
88346          */
88347         function beginSwitchBlock() {
88348             var breakLabel = defineLabel();
88349             beginBlock({
88350                 kind: 2 /* Switch */,
88351                 isScript: false,
88352                 breakLabel: breakLabel,
88353             });
88354             return breakLabel;
88355         }
88356         /**
88357          * Ends a code block that supports `break` statements that are defined in generated code.
88358          */
88359         function endSwitchBlock() {
88360             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
88361             var block = endBlock();
88362             var breakLabel = block.breakLabel;
88363             if (!block.isScript) {
88364                 markLabel(breakLabel);
88365             }
88366         }
88367         function beginScriptLabeledBlock(labelText) {
88368             beginBlock({
88369                 kind: 4 /* Labeled */,
88370                 isScript: true,
88371                 labelText: labelText,
88372                 breakLabel: -1
88373             });
88374         }
88375         function beginLabeledBlock(labelText) {
88376             var breakLabel = defineLabel();
88377             beginBlock({
88378                 kind: 4 /* Labeled */,
88379                 isScript: false,
88380                 labelText: labelText,
88381                 breakLabel: breakLabel
88382             });
88383         }
88384         function endLabeledBlock() {
88385             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
88386             var block = endBlock();
88387             if (!block.isScript) {
88388                 markLabel(block.breakLabel);
88389             }
88390         }
88391         /**
88392          * Indicates whether the provided block supports `break` statements.
88393          *
88394          * @param block A code block.
88395          */
88396         function supportsUnlabeledBreak(block) {
88397             return block.kind === 2 /* Switch */
88398                 || block.kind === 3 /* Loop */;
88399         }
88400         /**
88401          * Indicates whether the provided block supports `break` statements with labels.
88402          *
88403          * @param block A code block.
88404          */
88405         function supportsLabeledBreakOrContinue(block) {
88406             return block.kind === 4 /* Labeled */;
88407         }
88408         /**
88409          * Indicates whether the provided block supports `continue` statements.
88410          *
88411          * @param block A code block.
88412          */
88413         function supportsUnlabeledContinue(block) {
88414             return block.kind === 3 /* Loop */;
88415         }
88416         function hasImmediateContainingLabeledBlock(labelText, start) {
88417             for (var j = start; j >= 0; j--) {
88418                 var containingBlock = blockStack[j];
88419                 if (supportsLabeledBreakOrContinue(containingBlock)) {
88420                     if (containingBlock.labelText === labelText) {
88421                         return true;
88422                     }
88423                 }
88424                 else {
88425                     break;
88426                 }
88427             }
88428             return false;
88429         }
88430         /**
88431          * Finds the label that is the target for a `break` statement.
88432          *
88433          * @param labelText An optional name of a containing labeled statement.
88434          */
88435         function findBreakTarget(labelText) {
88436             if (blockStack) {
88437                 if (labelText) {
88438                     for (var i = blockStack.length - 1; i >= 0; i--) {
88439                         var block = blockStack[i];
88440                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
88441                             return block.breakLabel;
88442                         }
88443                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88444                             return block.breakLabel;
88445                         }
88446                     }
88447                 }
88448                 else {
88449                     for (var i = blockStack.length - 1; i >= 0; i--) {
88450                         var block = blockStack[i];
88451                         if (supportsUnlabeledBreak(block)) {
88452                             return block.breakLabel;
88453                         }
88454                     }
88455                 }
88456             }
88457             return 0;
88458         }
88459         /**
88460          * Finds the label that is the target for a `continue` statement.
88461          *
88462          * @param labelText An optional name of a containing labeled statement.
88463          */
88464         function findContinueTarget(labelText) {
88465             if (blockStack) {
88466                 if (labelText) {
88467                     for (var i = blockStack.length - 1; i >= 0; i--) {
88468                         var block = blockStack[i];
88469                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88470                             return block.continueLabel;
88471                         }
88472                     }
88473                 }
88474                 else {
88475                     for (var i = blockStack.length - 1; i >= 0; i--) {
88476                         var block = blockStack[i];
88477                         if (supportsUnlabeledContinue(block)) {
88478                             return block.continueLabel;
88479                         }
88480                     }
88481                 }
88482             }
88483             return 0;
88484         }
88485         /**
88486          * Creates an expression that can be used to indicate the value for a label.
88487          *
88488          * @param label A label.
88489          */
88490         function createLabel(label) {
88491             if (label !== undefined && label > 0) {
88492                 if (labelExpressions === undefined) {
88493                     labelExpressions = [];
88494                 }
88495                 var expression = ts.createLiteral(-1);
88496                 if (labelExpressions[label] === undefined) {
88497                     labelExpressions[label] = [expression];
88498                 }
88499                 else {
88500                     labelExpressions[label].push(expression);
88501                 }
88502                 return expression;
88503             }
88504             return ts.createOmittedExpression();
88505         }
88506         /**
88507          * Creates a numeric literal for the provided instruction.
88508          */
88509         function createInstruction(instruction) {
88510             var literal = ts.createLiteral(instruction);
88511             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
88512             return literal;
88513         }
88514         /**
88515          * Creates a statement that can be used indicate a Break operation to the provided label.
88516          *
88517          * @param label A label.
88518          * @param location An optional source map location for the statement.
88519          */
88520         function createInlineBreak(label, location) {
88521             ts.Debug.assertLessThan(0, label, "Invalid label");
88522             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88523                 createInstruction(3 /* Break */),
88524                 createLabel(label)
88525             ])), location);
88526         }
88527         /**
88528          * Creates a statement that can be used indicate a Return operation.
88529          *
88530          * @param expression The expression for the return statement.
88531          * @param location An optional source map location for the statement.
88532          */
88533         function createInlineReturn(expression, location) {
88534             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88535                 ? [createInstruction(2 /* Return */), expression]
88536                 : [createInstruction(2 /* Return */)])), location);
88537         }
88538         /**
88539          * Creates an expression that can be used to resume from a Yield operation.
88540          */
88541         function createGeneratorResume(location) {
88542             return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
88543             /*typeArguments*/ undefined, []), location);
88544         }
88545         /**
88546          * Emits an empty instruction.
88547          */
88548         function emitNop() {
88549             emitWorker(0 /* Nop */);
88550         }
88551         /**
88552          * Emits a Statement.
88553          *
88554          * @param node A statement.
88555          */
88556         function emitStatement(node) {
88557             if (node) {
88558                 emitWorker(1 /* Statement */, [node]);
88559             }
88560             else {
88561                 emitNop();
88562             }
88563         }
88564         /**
88565          * Emits an Assignment operation.
88566          *
88567          * @param left The left-hand side of the assignment.
88568          * @param right The right-hand side of the assignment.
88569          * @param location An optional source map location for the assignment.
88570          */
88571         function emitAssignment(left, right, location) {
88572             emitWorker(2 /* Assign */, [left, right], location);
88573         }
88574         /**
88575          * Emits a Break operation to the specified label.
88576          *
88577          * @param label A label.
88578          * @param location An optional source map location for the assignment.
88579          */
88580         function emitBreak(label, location) {
88581             emitWorker(3 /* Break */, [label], location);
88582         }
88583         /**
88584          * Emits a Break operation to the specified label when a condition evaluates to a truthy
88585          * value at runtime.
88586          *
88587          * @param label A label.
88588          * @param condition The condition.
88589          * @param location An optional source map location for the assignment.
88590          */
88591         function emitBreakWhenTrue(label, condition, location) {
88592             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
88593         }
88594         /**
88595          * Emits a Break to the specified label when a condition evaluates to a falsey value at
88596          * runtime.
88597          *
88598          * @param label A label.
88599          * @param condition The condition.
88600          * @param location An optional source map location for the assignment.
88601          */
88602         function emitBreakWhenFalse(label, condition, location) {
88603             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
88604         }
88605         /**
88606          * Emits a YieldStar operation for the provided expression.
88607          *
88608          * @param expression An optional value for the yield operation.
88609          * @param location An optional source map location for the assignment.
88610          */
88611         function emitYieldStar(expression, location) {
88612             emitWorker(7 /* YieldStar */, [expression], location);
88613         }
88614         /**
88615          * Emits a Yield operation for the provided expression.
88616          *
88617          * @param expression An optional value for the yield operation.
88618          * @param location An optional source map location for the assignment.
88619          */
88620         function emitYield(expression, location) {
88621             emitWorker(6 /* Yield */, [expression], location);
88622         }
88623         /**
88624          * Emits a Return operation for the provided expression.
88625          *
88626          * @param expression An optional value for the operation.
88627          * @param location An optional source map location for the assignment.
88628          */
88629         function emitReturn(expression, location) {
88630             emitWorker(8 /* Return */, [expression], location);
88631         }
88632         /**
88633          * Emits a Throw operation for the provided expression.
88634          *
88635          * @param expression A value for the operation.
88636          * @param location An optional source map location for the assignment.
88637          */
88638         function emitThrow(expression, location) {
88639             emitWorker(9 /* Throw */, [expression], location);
88640         }
88641         /**
88642          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
88643          */
88644         function emitEndfinally() {
88645             emitWorker(10 /* Endfinally */);
88646         }
88647         /**
88648          * Emits an operation.
88649          *
88650          * @param code The OpCode for the operation.
88651          * @param args The optional arguments for the operation.
88652          */
88653         function emitWorker(code, args, location) {
88654             if (operations === undefined) {
88655                 operations = [];
88656                 operationArguments = [];
88657                 operationLocations = [];
88658             }
88659             if (labelOffsets === undefined) {
88660                 // mark entry point
88661                 markLabel(defineLabel());
88662             }
88663             var operationIndex = operations.length;
88664             operations[operationIndex] = code;
88665             operationArguments[operationIndex] = args;
88666             operationLocations[operationIndex] = location;
88667         }
88668         /**
88669          * Builds the generator function body.
88670          */
88671         function build() {
88672             blockIndex = 0;
88673             labelNumber = 0;
88674             labelNumbers = undefined;
88675             lastOperationWasAbrupt = false;
88676             lastOperationWasCompletion = false;
88677             clauses = undefined;
88678             statements = undefined;
88679             exceptionBlockStack = undefined;
88680             currentExceptionBlock = undefined;
88681             withBlockStack = undefined;
88682             var buildResult = buildStatements();
88683             return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
88684             /*modifiers*/ undefined, 
88685             /*asteriskToken*/ undefined, 
88686             /*name*/ undefined, 
88687             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
88688             /*type*/ undefined, ts.createBlock(buildResult, 
88689             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
88690         }
88691         /**
88692          * Builds the statements for the generator function body.
88693          */
88694         function buildStatements() {
88695             if (operations) {
88696                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
88697                     writeOperation(operationIndex);
88698                 }
88699                 flushFinalLabel(operations.length);
88700             }
88701             else {
88702                 flushFinalLabel(0);
88703             }
88704             if (clauses) {
88705                 var labelExpression = ts.createPropertyAccess(state, "label");
88706                 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
88707                 return [ts.startOnNewLine(switchStatement)];
88708             }
88709             if (statements) {
88710                 return statements;
88711             }
88712             return [];
88713         }
88714         /**
88715          * Flush the current label and advance to a new label.
88716          */
88717         function flushLabel() {
88718             if (!statements) {
88719                 return;
88720             }
88721             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
88722             lastOperationWasAbrupt = false;
88723             lastOperationWasCompletion = false;
88724             labelNumber++;
88725         }
88726         /**
88727          * Flush the final label of the generator function body.
88728          */
88729         function flushFinalLabel(operationIndex) {
88730             if (isFinalLabelReachable(operationIndex)) {
88731                 tryEnterLabel(operationIndex);
88732                 withBlockStack = undefined;
88733                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
88734             }
88735             if (statements && clauses) {
88736                 appendLabel(/*markLabelEnd*/ false);
88737             }
88738             updateLabelExpressions();
88739         }
88740         /**
88741          * Tests whether the final label of the generator function body
88742          * is reachable by user code.
88743          */
88744         function isFinalLabelReachable(operationIndex) {
88745             // if the last operation was *not* a completion (return/throw) then
88746             // the final label is reachable.
88747             if (!lastOperationWasCompletion) {
88748                 return true;
88749             }
88750             // if there are no labels defined or referenced, then the final label is
88751             // not reachable.
88752             if (!labelOffsets || !labelExpressions) {
88753                 return false;
88754             }
88755             // if the label for this offset is referenced, then the final label
88756             // is reachable.
88757             for (var label = 0; label < labelOffsets.length; label++) {
88758                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
88759                     return true;
88760                 }
88761             }
88762             return false;
88763         }
88764         /**
88765          * Appends a case clause for the last label and sets the new label.
88766          *
88767          * @param markLabelEnd Indicates that the transition between labels was a fall-through
88768          *                     from a previous case clause and the change in labels should be
88769          *                     reflected on the `state` object.
88770          */
88771         function appendLabel(markLabelEnd) {
88772             if (!clauses) {
88773                 clauses = [];
88774             }
88775             if (statements) {
88776                 if (withBlockStack) {
88777                     // The previous label was nested inside one or more `with` blocks, so we
88778                     // surround the statements in generated `with` blocks to create the same environment.
88779                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
88780                         var withBlock = withBlockStack[i];
88781                         statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
88782                     }
88783                 }
88784                 if (currentExceptionBlock) {
88785                     // The previous label was nested inside of an exception block, so we must
88786                     // indicate entry into a protected region by pushing the label numbers
88787                     // for each block in the protected region.
88788                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
88789                     statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
88790                     /*typeArguments*/ undefined, [
88791                         ts.createArrayLiteral([
88792                             createLabel(startLabel),
88793                             createLabel(catchLabel),
88794                             createLabel(finallyLabel),
88795                             createLabel(endLabel)
88796                         ])
88797                     ])));
88798                     currentExceptionBlock = undefined;
88799                 }
88800                 if (markLabelEnd) {
88801                     // The case clause for the last label falls through to this label, so we
88802                     // add an assignment statement to reflect the change in labels.
88803                     statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
88804                 }
88805             }
88806             clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
88807             statements = undefined;
88808         }
88809         /**
88810          * Tries to enter into a new label at the current operation index.
88811          */
88812         function tryEnterLabel(operationIndex) {
88813             if (!labelOffsets) {
88814                 return;
88815             }
88816             for (var label = 0; label < labelOffsets.length; label++) {
88817                 if (labelOffsets[label] === operationIndex) {
88818                     flushLabel();
88819                     if (labelNumbers === undefined) {
88820                         labelNumbers = [];
88821                     }
88822                     if (labelNumbers[labelNumber] === undefined) {
88823                         labelNumbers[labelNumber] = [label];
88824                     }
88825                     else {
88826                         labelNumbers[labelNumber].push(label);
88827                     }
88828                 }
88829             }
88830         }
88831         /**
88832          * Updates literal expressions for labels with actual label numbers.
88833          */
88834         function updateLabelExpressions() {
88835             if (labelExpressions !== undefined && labelNumbers !== undefined) {
88836                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
88837                     var labels = labelNumbers[labelNumber_1];
88838                     if (labels !== undefined) {
88839                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
88840                             var label = labels_1[_i];
88841                             var expressions = labelExpressions[label];
88842                             if (expressions !== undefined) {
88843                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
88844                                     var expression = expressions_1[_a];
88845                                     expression.text = String(labelNumber_1);
88846                                 }
88847                             }
88848                         }
88849                     }
88850                 }
88851             }
88852         }
88853         /**
88854          * Tries to enter or leave a code block.
88855          */
88856         function tryEnterOrLeaveBlock(operationIndex) {
88857             if (blocks) {
88858                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
88859                     var block = blocks[blockIndex];
88860                     var blockAction = blockActions[blockIndex];
88861                     switch (block.kind) {
88862                         case 0 /* Exception */:
88863                             if (blockAction === 0 /* Open */) {
88864                                 if (!exceptionBlockStack) {
88865                                     exceptionBlockStack = [];
88866                                 }
88867                                 if (!statements) {
88868                                     statements = [];
88869                                 }
88870                                 exceptionBlockStack.push(currentExceptionBlock);
88871                                 currentExceptionBlock = block;
88872                             }
88873                             else if (blockAction === 1 /* Close */) {
88874                                 currentExceptionBlock = exceptionBlockStack.pop();
88875                             }
88876                             break;
88877                         case 1 /* With */:
88878                             if (blockAction === 0 /* Open */) {
88879                                 if (!withBlockStack) {
88880                                     withBlockStack = [];
88881                                 }
88882                                 withBlockStack.push(block);
88883                             }
88884                             else if (blockAction === 1 /* Close */) {
88885                                 withBlockStack.pop();
88886                             }
88887                             break;
88888                         // default: do nothing
88889                     }
88890                 }
88891             }
88892         }
88893         /**
88894          * Writes an operation as a statement to the current label's statement list.
88895          *
88896          * @param operation The OpCode of the operation
88897          */
88898         function writeOperation(operationIndex) {
88899             tryEnterLabel(operationIndex);
88900             tryEnterOrLeaveBlock(operationIndex);
88901             // early termination, nothing else to process in this label
88902             if (lastOperationWasAbrupt) {
88903                 return;
88904             }
88905             lastOperationWasAbrupt = false;
88906             lastOperationWasCompletion = false;
88907             var opcode = operations[operationIndex];
88908             if (opcode === 0 /* Nop */) {
88909                 return;
88910             }
88911             else if (opcode === 10 /* Endfinally */) {
88912                 return writeEndfinally();
88913             }
88914             var args = operationArguments[operationIndex];
88915             if (opcode === 1 /* Statement */) {
88916                 return writeStatement(args[0]);
88917             }
88918             var location = operationLocations[operationIndex];
88919             switch (opcode) {
88920                 case 2 /* Assign */:
88921                     return writeAssign(args[0], args[1], location);
88922                 case 3 /* Break */:
88923                     return writeBreak(args[0], location);
88924                 case 4 /* BreakWhenTrue */:
88925                     return writeBreakWhenTrue(args[0], args[1], location);
88926                 case 5 /* BreakWhenFalse */:
88927                     return writeBreakWhenFalse(args[0], args[1], location);
88928                 case 6 /* Yield */:
88929                     return writeYield(args[0], location);
88930                 case 7 /* YieldStar */:
88931                     return writeYieldStar(args[0], location);
88932                 case 8 /* Return */:
88933                     return writeReturn(args[0], location);
88934                 case 9 /* Throw */:
88935                     return writeThrow(args[0], location);
88936             }
88937         }
88938         /**
88939          * Writes a statement to the current label's statement list.
88940          *
88941          * @param statement A statement to write.
88942          */
88943         function writeStatement(statement) {
88944             if (statement) {
88945                 if (!statements) {
88946                     statements = [statement];
88947                 }
88948                 else {
88949                     statements.push(statement);
88950                 }
88951             }
88952         }
88953         /**
88954          * Writes an Assign operation to the current label's statement list.
88955          *
88956          * @param left The left-hand side of the assignment.
88957          * @param right The right-hand side of the assignment.
88958          * @param operationLocation The source map location for the operation.
88959          */
88960         function writeAssign(left, right, operationLocation) {
88961             writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
88962         }
88963         /**
88964          * Writes a Throw operation to the current label's statement list.
88965          *
88966          * @param expression The value to throw.
88967          * @param operationLocation The source map location for the operation.
88968          */
88969         function writeThrow(expression, operationLocation) {
88970             lastOperationWasAbrupt = true;
88971             lastOperationWasCompletion = true;
88972             writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
88973         }
88974         /**
88975          * Writes a Return operation to the current label's statement list.
88976          *
88977          * @param expression The value to return.
88978          * @param operationLocation The source map location for the operation.
88979          */
88980         function writeReturn(expression, operationLocation) {
88981             lastOperationWasAbrupt = true;
88982             lastOperationWasCompletion = true;
88983             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88984                 ? [createInstruction(2 /* Return */), expression]
88985                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88986         }
88987         /**
88988          * Writes a Break operation to the current label's statement list.
88989          *
88990          * @param label The label for the Break.
88991          * @param operationLocation The source map location for the operation.
88992          */
88993         function writeBreak(label, operationLocation) {
88994             lastOperationWasAbrupt = true;
88995             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88996                 createInstruction(3 /* Break */),
88997                 createLabel(label)
88998             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88999         }
89000         /**
89001          * Writes a BreakWhenTrue operation to the current label's statement list.
89002          *
89003          * @param label The label for the Break.
89004          * @param condition The condition for the Break.
89005          * @param operationLocation The source map location for the operation.
89006          */
89007         function writeBreakWhenTrue(label, condition, operationLocation) {
89008             writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
89009                 createInstruction(3 /* Break */),
89010                 createLabel(label)
89011             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
89012         }
89013         /**
89014          * Writes a BreakWhenFalse operation to the current label's statement list.
89015          *
89016          * @param label The label for the Break.
89017          * @param condition The condition for the Break.
89018          * @param operationLocation The source map location for the operation.
89019          */
89020         function writeBreakWhenFalse(label, condition, operationLocation) {
89021             writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
89022                 createInstruction(3 /* Break */),
89023                 createLabel(label)
89024             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
89025         }
89026         /**
89027          * Writes a Yield operation to the current label's statement list.
89028          *
89029          * @param expression The expression to yield.
89030          * @param operationLocation The source map location for the operation.
89031          */
89032         function writeYield(expression, operationLocation) {
89033             lastOperationWasAbrupt = true;
89034             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
89035                 ? [createInstruction(4 /* Yield */), expression]
89036                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
89037         }
89038         /**
89039          * Writes a YieldStar instruction to the current label's statement list.
89040          *
89041          * @param expression The expression to yield.
89042          * @param operationLocation The source map location for the operation.
89043          */
89044         function writeYieldStar(expression, operationLocation) {
89045             lastOperationWasAbrupt = true;
89046             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
89047                 createInstruction(5 /* YieldStar */),
89048                 expression
89049             ])), operationLocation), 384 /* NoTokenSourceMaps */));
89050         }
89051         /**
89052          * Writes an Endfinally instruction to the current label's statement list.
89053          */
89054         function writeEndfinally() {
89055             lastOperationWasAbrupt = true;
89056             writeStatement(ts.createReturn(ts.createArrayLiteral([
89057                 createInstruction(7 /* Endfinally */)
89058             ])));
89059         }
89060     }
89061     ts.transformGenerators = transformGenerators;
89062     function createGeneratorHelper(context, body) {
89063         context.requestEmitHelper(ts.generatorHelper);
89064         return ts.createCall(ts.getUnscopedHelperName("__generator"), 
89065         /*typeArguments*/ undefined, [ts.createThis(), body]);
89066     }
89067     // The __generator helper is used by down-level transformations to emulate the runtime
89068     // semantics of an ES2015 generator function. When called, this helper returns an
89069     // object that implements the Iterator protocol, in that it has `next`, `return`, and
89070     // `throw` methods that step through the generator when invoked.
89071     //
89072     // parameters:
89073     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
89074     //  @param body     A function that acts as the transformed generator body.
89075     //
89076     // variables:
89077     //  _       Persistent state for the generator that is shared between the helper and the
89078     //          generator body. The state object has the following members:
89079     //            sent() - A method that returns or throws the current completion value.
89080     //            label  - The next point at which to resume evaluation of the generator body.
89081     //            trys   - A stack of protected regions (try/catch/finally blocks).
89082     //            ops    - A stack of pending instructions when inside of a finally block.
89083     //  f       A value indicating whether the generator is executing.
89084     //  y       An iterator to delegate for a yield*.
89085     //  t       A temporary variable that holds one of the following values (note that these
89086     //          cases do not overlap):
89087     //          - The completion value when resuming from a `yield` or `yield*`.
89088     //          - The error value for a catch block.
89089     //          - The current protected region (array of try/catch/finally/end labels).
89090     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
89091     //            of a `yield*`.
89092     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
89093     //
89094     // functions:
89095     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
89096     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
89097     //              completed.
89098     //
89099     // The __generator helper understands a limited set of instructions:
89100     //  0: next(value?)     - Start or resume the generator with the specified value.
89101     //  1: throw(error)     - Resume the generator with an exception. If the generator is
89102     //                        suspended inside of one or more protected regions, evaluates
89103     //                        any intervening finally blocks between the current label and
89104     //                        the nearest catch block or function boundary. If uncaught, the
89105     //                        exception is thrown to the caller.
89106     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
89107     //                        suspended inside of one or more protected regions, evaluates any
89108     //                        intervening finally blocks.
89109     //  3: break(label)     - Jump to the specified label. If the label is outside of the
89110     //                        current protected region, evaluates any intervening finally
89111     //                        blocks.
89112     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
89113     //                        resumed, the generator will continue at the next label.
89114     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
89115     //                        delegation completes, the generator will continue at the next
89116     //                        label.
89117     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
89118     //                        the current label is inside of one or more protected regions,
89119     //                        evaluates any intervening finally blocks between the current
89120     //                        label and the nearest catch block or function boundary. If
89121     //                        uncaught, the exception is thrown to the caller.
89122     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
89123     //                        entering a finally block.
89124     //
89125     // For examples of how these are used, see the comments in ./transformers/generators.ts
89126     ts.generatorHelper = {
89127         name: "typescript:generator",
89128         importName: "__generator",
89129         scoped: false,
89130         priority: 6,
89131         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            };"
89132     };
89133 })(ts || (ts = {}));
89134 /*@internal*/
89135 var ts;
89136 (function (ts) {
89137     function transformModule(context) {
89138         function getTransformModuleDelegate(moduleKind) {
89139             switch (moduleKind) {
89140                 case ts.ModuleKind.AMD: return transformAMDModule;
89141                 case ts.ModuleKind.UMD: return transformUMDModule;
89142                 default: return transformCommonJSModule;
89143             }
89144         }
89145         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
89146         var compilerOptions = context.getCompilerOptions();
89147         var resolver = context.getEmitResolver();
89148         var host = context.getEmitHost();
89149         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
89150         var moduleKind = ts.getEmitModuleKind(compilerOptions);
89151         var previousOnSubstituteNode = context.onSubstituteNode;
89152         var previousOnEmitNode = context.onEmitNode;
89153         context.onSubstituteNode = onSubstituteNode;
89154         context.onEmitNode = onEmitNode;
89155         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
89156         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
89157         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
89158         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
89159         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
89160         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
89161         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
89162         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
89163         var currentSourceFile; // The current file.
89164         var currentModuleInfo; // The ExternalModuleInfo for the current file.
89165         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
89166         var needUMDDynamicImportHelper;
89167         return ts.chainBundle(transformSourceFile);
89168         /**
89169          * Transforms the module aspects of a SourceFile.
89170          *
89171          * @param node The SourceFile node.
89172          */
89173         function transformSourceFile(node) {
89174             if (node.isDeclarationFile ||
89175                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
89176                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
89177                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
89178                 return node;
89179             }
89180             currentSourceFile = node;
89181             currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
89182             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
89183             // Perform the transformation.
89184             var transformModule = getTransformModuleDelegate(moduleKind);
89185             var updated = transformModule(node);
89186             currentSourceFile = undefined;
89187             currentModuleInfo = undefined;
89188             needUMDDynamicImportHelper = false;
89189             return ts.aggregateTransformFlags(updated);
89190         }
89191         function shouldEmitUnderscoreUnderscoreESModule() {
89192             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
89193                 return true;
89194             }
89195             return false;
89196         }
89197         /**
89198          * Transforms a SourceFile into a CommonJS module.
89199          *
89200          * @param node The SourceFile node.
89201          */
89202         function transformCommonJSModule(node) {
89203             startLexicalEnvironment();
89204             var statements = [];
89205             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
89206             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
89207             if (shouldEmitUnderscoreUnderscoreESModule()) {
89208                 ts.append(statements, createUnderscoreUnderscoreESModule());
89209             }
89210             if (ts.length(currentModuleInfo.exportedNames)) {
89211                 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())));
89212             }
89213             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89214             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89215             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
89216             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89217             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
89218             ts.addEmitHelpers(updated, context.readEmitHelpers());
89219             return updated;
89220         }
89221         /**
89222          * Transforms a SourceFile into an AMD module.
89223          *
89224          * @param node The SourceFile node.
89225          */
89226         function transformAMDModule(node) {
89227             var define = ts.createIdentifier("define");
89228             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89229             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
89230             // An AMD define function has the following shape:
89231             //
89232             //     define(id?, dependencies?, factory);
89233             //
89234             // This has the shape of the following:
89235             //
89236             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
89237             //
89238             // The location of the alias in the parameter list in the factory function needs to
89239             // match the position of the module name in the dependency list.
89240             //
89241             // To ensure this is true in cases of modules with no aliases, e.g.:
89242             //
89243             //     import "module"
89244             //
89245             // or
89246             //
89247             //     /// <amd-dependency path= "a.css" />
89248             //
89249             // we need to add modules without alias names to the end of the dependencies list
89250             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89251             // Create an updated SourceFile:
89252             //
89253             //     define(moduleName?, ["module1", "module2"], function ...
89254             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89255                 ts.createExpressionStatement(ts.createCall(define, 
89256                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89257                     // Add the dependency array argument:
89258                     //
89259                     //     ["require", "exports", module1", "module2", ...]
89260                     ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
89261                         ts.createLiteral("require"),
89262                         ts.createLiteral("exports")
89263                     ], aliasedModuleNames, unaliasedModuleNames)),
89264                     // Add the module body function argument:
89265                     //
89266                     //     function (require, exports, module1, module2) ...
89267                     jsonSourceFile ?
89268                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
89269                         ts.createFunctionExpression(
89270                         /*modifiers*/ undefined, 
89271                         /*asteriskToken*/ undefined, 
89272                         /*name*/ undefined, 
89273                         /*typeParameters*/ undefined, __spreadArrays([
89274                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89275                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89276                         ], importAliasNames), 
89277                         /*type*/ undefined, transformAsynchronousModuleBody(node))
89278                 ])))
89279             ]), 
89280             /*location*/ node.statements));
89281             ts.addEmitHelpers(updated, context.readEmitHelpers());
89282             return updated;
89283         }
89284         /**
89285          * Transforms a SourceFile into a UMD module.
89286          *
89287          * @param node The SourceFile node.
89288          */
89289         function transformUMDModule(node) {
89290             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89291             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89292             var umdHeader = ts.createFunctionExpression(
89293             /*modifiers*/ undefined, 
89294             /*asteriskToken*/ undefined, 
89295             /*name*/ undefined, 
89296             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
89297             /*type*/ undefined, ts.setTextRange(ts.createBlock([
89298                 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
89299                     ts.createVariableStatement(
89300                     /*modifiers*/ undefined, [
89301                         ts.createVariableDeclaration("v", 
89302                         /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
89303                         /*typeArguments*/ undefined, [
89304                             ts.createIdentifier("require"),
89305                             ts.createIdentifier("exports")
89306                         ]))
89307                     ]),
89308                     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 */)
89309                 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
89310                     ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
89311                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89312                         ts.createArrayLiteral(__spreadArrays([
89313                             ts.createLiteral("require"),
89314                             ts.createLiteral("exports")
89315                         ], aliasedModuleNames, unaliasedModuleNames)),
89316                         ts.createIdentifier("factory")
89317                     ])))
89318                 ])))
89319             ], 
89320             /*multiLine*/ true), 
89321             /*location*/ undefined));
89322             // Create an updated SourceFile:
89323             //
89324             //  (function (factory) {
89325             //      if (typeof module === "object" && typeof module.exports === "object") {
89326             //          var v = factory(require, exports);
89327             //          if (v !== undefined) module.exports = v;
89328             //      }
89329             //      else if (typeof define === 'function' && define.amd) {
89330             //          define(["require", "exports"], factory);
89331             //      }
89332             //  })(function ...)
89333             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89334                 ts.createExpressionStatement(ts.createCall(umdHeader, 
89335                 /*typeArguments*/ undefined, [
89336                     // Add the module body function argument:
89337                     //
89338                     //     function (require, exports) ...
89339                     ts.createFunctionExpression(
89340                     /*modifiers*/ undefined, 
89341                     /*asteriskToken*/ undefined, 
89342                     /*name*/ undefined, 
89343                     /*typeParameters*/ undefined, __spreadArrays([
89344                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89345                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89346                     ], importAliasNames), 
89347                     /*type*/ undefined, transformAsynchronousModuleBody(node))
89348                 ]))
89349             ]), 
89350             /*location*/ node.statements));
89351             ts.addEmitHelpers(updated, context.readEmitHelpers());
89352             return updated;
89353         }
89354         /**
89355          * Collect the additional asynchronous dependencies for the module.
89356          *
89357          * @param node The source file.
89358          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
89359          */
89360         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
89361             // names of modules with corresponding parameter in the factory function
89362             var aliasedModuleNames = [];
89363             // names of modules with no corresponding parameters in factory function
89364             var unaliasedModuleNames = [];
89365             // names of the parameters in the factory function; these
89366             // parameters need to match the indexes of the corresponding
89367             // module names in aliasedModuleNames.
89368             var importAliasNames = [];
89369             // Fill in amd-dependency tags
89370             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
89371                 var amdDependency = _a[_i];
89372                 if (amdDependency.name) {
89373                     aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89374                     importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
89375                 }
89376                 else {
89377                     unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89378                 }
89379             }
89380             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
89381                 var importNode = _c[_b];
89382                 // Find the name of the external module
89383                 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89384                 // Find the name of the module alias, if there is one
89385                 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
89386                 // It is possible that externalModuleName is undefined if it is not string literal.
89387                 // This can happen in the invalid import syntax.
89388                 // E.g : "import * from alias from 'someLib';"
89389                 if (externalModuleName) {
89390                     if (includeNonAmdDependencies && importAliasName) {
89391                         // Set emitFlags on the name of the classDeclaration
89392                         // This is so that when printer will not substitute the identifier
89393                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
89394                         aliasedModuleNames.push(externalModuleName);
89395                         importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
89396                     }
89397                     else {
89398                         unaliasedModuleNames.push(externalModuleName);
89399                     }
89400                 }
89401             }
89402             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
89403         }
89404         function getAMDImportExpressionForImport(node) {
89405             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
89406                 return undefined;
89407             }
89408             var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
89409             var expr = getHelperExpressionForImport(node, name);
89410             if (expr === name) {
89411                 return undefined;
89412             }
89413             return ts.createExpressionStatement(ts.createAssignment(name, expr));
89414         }
89415         /**
89416          * Transforms a SourceFile into an AMD or UMD module body.
89417          *
89418          * @param node The SourceFile node.
89419          */
89420         function transformAsynchronousModuleBody(node) {
89421             startLexicalEnvironment();
89422             var statements = [];
89423             var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
89424             if (shouldEmitUnderscoreUnderscoreESModule()) {
89425                 ts.append(statements, createUnderscoreUnderscoreESModule());
89426             }
89427             if (ts.length(currentModuleInfo.exportedNames)) {
89428                 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())));
89429             }
89430             // Visit each statement of the module body.
89431             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89432             if (moduleKind === ts.ModuleKind.AMD) {
89433                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
89434             }
89435             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89436             // Append the 'export =' statement if provided.
89437             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
89438             // End the lexical environment for the module body
89439             // and merge any new lexical declarations.
89440             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89441             var body = ts.createBlock(statements, /*multiLine*/ true);
89442             if (needUMDDynamicImportHelper) {
89443                 ts.addEmitHelper(body, dynamicImportUMDHelper);
89444             }
89445             return body;
89446         }
89447         /**
89448          * Adds the down-level representation of `export=` to the statement list if one exists
89449          * in the source file.
89450          *
89451          * @param statements The Statement list to modify.
89452          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
89453          * return statement.
89454          */
89455         function addExportEqualsIfNeeded(statements, emitAsReturn) {
89456             if (currentModuleInfo.exportEquals) {
89457                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
89458                 if (expressionResult) {
89459                     if (emitAsReturn) {
89460                         var statement = ts.createReturn(expressionResult);
89461                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89462                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
89463                         statements.push(statement);
89464                     }
89465                     else {
89466                         var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
89467                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89468                         ts.setEmitFlags(statement, 1536 /* NoComments */);
89469                         statements.push(statement);
89470                     }
89471                 }
89472             }
89473         }
89474         //
89475         // Top-Level Source Element Visitors
89476         //
89477         /**
89478          * Visits a node at the top level of the source file.
89479          *
89480          * @param node The node to visit.
89481          */
89482         function sourceElementVisitor(node) {
89483             switch (node.kind) {
89484                 case 254 /* ImportDeclaration */:
89485                     return visitImportDeclaration(node);
89486                 case 253 /* ImportEqualsDeclaration */:
89487                     return visitImportEqualsDeclaration(node);
89488                 case 260 /* ExportDeclaration */:
89489                     return visitExportDeclaration(node);
89490                 case 259 /* ExportAssignment */:
89491                     return visitExportAssignment(node);
89492                 case 225 /* VariableStatement */:
89493                     return visitVariableStatement(node);
89494                 case 244 /* FunctionDeclaration */:
89495                     return visitFunctionDeclaration(node);
89496                 case 245 /* ClassDeclaration */:
89497                     return visitClassDeclaration(node);
89498                 case 328 /* MergeDeclarationMarker */:
89499                     return visitMergeDeclarationMarker(node);
89500                 case 329 /* EndOfDeclarationMarker */:
89501                     return visitEndOfDeclarationMarker(node);
89502                 default:
89503                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89504             }
89505         }
89506         function moduleExpressionElementVisitor(node) {
89507             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
89508             // as export/import statements are only transformed at the top level of a file.
89509             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
89510                 return node;
89511             }
89512             if (ts.isImportCall(node)) {
89513                 return visitImportCallExpression(node);
89514             }
89515             else if (ts.isDestructuringAssignment(node)) {
89516                 return visitDestructuringAssignment(node);
89517             }
89518             else {
89519                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89520             }
89521         }
89522         function destructuringNeedsFlattening(node) {
89523             if (ts.isObjectLiteralExpression(node)) {
89524                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
89525                     var elem = _a[_i];
89526                     switch (elem.kind) {
89527                         case 281 /* PropertyAssignment */:
89528                             if (destructuringNeedsFlattening(elem.initializer)) {
89529                                 return true;
89530                             }
89531                             break;
89532                         case 282 /* ShorthandPropertyAssignment */:
89533                             if (destructuringNeedsFlattening(elem.name)) {
89534                                 return true;
89535                             }
89536                             break;
89537                         case 283 /* SpreadAssignment */:
89538                             if (destructuringNeedsFlattening(elem.expression)) {
89539                                 return true;
89540                             }
89541                             break;
89542                         case 161 /* MethodDeclaration */:
89543                         case 163 /* GetAccessor */:
89544                         case 164 /* SetAccessor */:
89545                             return false;
89546                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
89547                     }
89548                 }
89549             }
89550             else if (ts.isArrayLiteralExpression(node)) {
89551                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
89552                     var elem = _c[_b];
89553                     if (ts.isSpreadElement(elem)) {
89554                         if (destructuringNeedsFlattening(elem.expression)) {
89555                             return true;
89556                         }
89557                     }
89558                     else if (destructuringNeedsFlattening(elem)) {
89559                         return true;
89560                     }
89561                 }
89562             }
89563             else if (ts.isIdentifier(node)) {
89564                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
89565             }
89566             return false;
89567         }
89568         function visitDestructuringAssignment(node) {
89569             if (destructuringNeedsFlattening(node.left)) {
89570                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
89571             }
89572             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89573         }
89574         function visitImportCallExpression(node) {
89575             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
89576             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
89577             switch (compilerOptions.module) {
89578                 case ts.ModuleKind.AMD:
89579                     return createImportCallExpressionAMD(argument, containsLexicalThis);
89580                 case ts.ModuleKind.UMD:
89581                     return createImportCallExpressionUMD(argument, containsLexicalThis);
89582                 case ts.ModuleKind.CommonJS:
89583                 default:
89584                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
89585             }
89586         }
89587         function createImportCallExpressionUMD(arg, containsLexicalThis) {
89588             // (function (factory) {
89589             //      ... (regular UMD)
89590             // }
89591             // })(function (require, exports, useSyncRequire) {
89592             //      "use strict";
89593             //      Object.defineProperty(exports, "__esModule", { value: true });
89594             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
89595             //      var __resolved = new Promise(function (resolve) { resolve(); });
89596             //      .....
89597             //      __syncRequire
89598             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
89599             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89600             // });
89601             needUMDDynamicImportHelper = true;
89602             if (ts.isSimpleCopiableExpression(arg)) {
89603                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
89604                 return ts.createConditional(
89605                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89606                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
89607                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
89608             }
89609             else {
89610                 var temp = ts.createTempVariable(hoistVariableDeclaration);
89611                 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
89612                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89613                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
89614                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
89615             }
89616         }
89617         function createImportCallExpressionAMD(arg, containsLexicalThis) {
89618             // improt("./blah")
89619             // emit as
89620             // define(["require", "exports", "blah"], function (require, exports) {
89621             //     ...
89622             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89623             // });
89624             var resolve = ts.createUniqueName("resolve");
89625             var reject = ts.createUniqueName("reject");
89626             var parameters = [
89627                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
89628                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
89629             ];
89630             var body = ts.createBlock([
89631                 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
89632                 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
89633             ]);
89634             var func;
89635             if (languageVersion >= 2 /* ES2015 */) {
89636                 func = ts.createArrowFunction(
89637                 /*modifiers*/ undefined, 
89638                 /*typeParameters*/ undefined, parameters, 
89639                 /*type*/ undefined, 
89640                 /*equalsGreaterThanToken*/ undefined, body);
89641             }
89642             else {
89643                 func = ts.createFunctionExpression(
89644                 /*modifiers*/ undefined, 
89645                 /*asteriskToken*/ undefined, 
89646                 /*name*/ undefined, 
89647                 /*typeParameters*/ undefined, parameters, 
89648                 /*type*/ undefined, body);
89649                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89650                 // that this new function expression indicates it captures 'this' so that the
89651                 // es2015 transformer will properly substitute 'this' with '_this'.
89652                 if (containsLexicalThis) {
89653                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89654                 }
89655             }
89656             var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
89657             if (compilerOptions.esModuleInterop) {
89658                 context.requestEmitHelper(ts.importStarHelper);
89659                 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
89660             }
89661             return promise;
89662         }
89663         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
89664             // import("./blah")
89665             // emit as
89666             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
89667             // We have to wrap require in then callback so that require is done in asynchronously
89668             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
89669             var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
89670             var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
89671             if (compilerOptions.esModuleInterop) {
89672                 context.requestEmitHelper(ts.importStarHelper);
89673                 requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
89674             }
89675             var func;
89676             if (languageVersion >= 2 /* ES2015 */) {
89677                 func = ts.createArrowFunction(
89678                 /*modifiers*/ undefined, 
89679                 /*typeParameters*/ undefined, 
89680                 /*parameters*/ [], 
89681                 /*type*/ undefined, 
89682                 /*equalsGreaterThanToken*/ undefined, requireCall);
89683             }
89684             else {
89685                 func = ts.createFunctionExpression(
89686                 /*modifiers*/ undefined, 
89687                 /*asteriskToken*/ undefined, 
89688                 /*name*/ undefined, 
89689                 /*typeParameters*/ undefined, 
89690                 /*parameters*/ [], 
89691                 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
89692                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89693                 // that this new function expression indicates it captures 'this' so that the
89694                 // es2015 transformer will properly substitute 'this' with '_this'.
89695                 if (containsLexicalThis) {
89696                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89697                 }
89698             }
89699             return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
89700         }
89701         function getHelperExpressionForExport(node, innerExpr) {
89702             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89703                 return innerExpr;
89704             }
89705             if (ts.getExportNeedsImportStarHelper(node)) {
89706                 context.requestEmitHelper(ts.importStarHelper);
89707                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89708             }
89709             return innerExpr;
89710         }
89711         function getHelperExpressionForImport(node, innerExpr) {
89712             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89713                 return innerExpr;
89714             }
89715             if (ts.getImportNeedsImportStarHelper(node)) {
89716                 context.requestEmitHelper(ts.importStarHelper);
89717                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89718             }
89719             if (ts.getImportNeedsImportDefaultHelper(node)) {
89720                 context.requestEmitHelper(ts.importDefaultHelper);
89721                 return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
89722             }
89723             return innerExpr;
89724         }
89725         /**
89726          * Visits an ImportDeclaration node.
89727          *
89728          * @param node The node to visit.
89729          */
89730         function visitImportDeclaration(node) {
89731             var statements;
89732             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
89733             if (moduleKind !== ts.ModuleKind.AMD) {
89734                 if (!node.importClause) {
89735                     // import "mod";
89736                     return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
89737                 }
89738                 else {
89739                     var variables = [];
89740                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
89741                         // import * as n from "mod";
89742                         variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89743                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89744                     }
89745                     else {
89746                         // import d from "mod";
89747                         // import { x, y } from "mod";
89748                         // import d, { x, y } from "mod";
89749                         // import d, * as n from "mod";
89750                         variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
89751                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89752                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
89753                             variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89754                             /*type*/ undefined, ts.getGeneratedNameForNode(node)));
89755                         }
89756                     }
89757                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89758                     /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
89759                     /*location*/ node), 
89760                     /*original*/ node));
89761                 }
89762             }
89763             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
89764                 // import d, * as n from "mod";
89765                 statements = ts.append(statements, ts.createVariableStatement(
89766                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
89767                     ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89768                     /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
89769                     /*location*/ node), 
89770                     /*original*/ node)
89771                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
89772             }
89773             if (hasAssociatedEndOfDeclarationMarker(node)) {
89774                 // Defer exports until we encounter an EndOfDeclarationMarker node
89775                 var id = ts.getOriginalNodeId(node);
89776                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
89777             }
89778             else {
89779                 statements = appendExportsOfImportDeclaration(statements, node);
89780             }
89781             return ts.singleOrMany(statements);
89782         }
89783         /**
89784          * Creates a `require()` call to import an external module.
89785          *
89786          * @param importNode The declararation to import.
89787          */
89788         function createRequireCall(importNode) {
89789             var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89790             var args = [];
89791             if (moduleName) {
89792                 args.push(moduleName);
89793             }
89794             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
89795         }
89796         /**
89797          * Visits an ImportEqualsDeclaration node.
89798          *
89799          * @param node The node to visit.
89800          */
89801         function visitImportEqualsDeclaration(node) {
89802             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
89803             var statements;
89804             if (moduleKind !== ts.ModuleKind.AMD) {
89805                 if (ts.hasModifier(node, 1 /* Export */)) {
89806                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
89807                 }
89808                 else {
89809                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89810                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89811                         ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
89812                         /*type*/ undefined, createRequireCall(node))
89813                     ], 
89814                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
89815                 }
89816             }
89817             else {
89818                 if (ts.hasModifier(node, 1 /* Export */)) {
89819                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
89820                 }
89821             }
89822             if (hasAssociatedEndOfDeclarationMarker(node)) {
89823                 // Defer exports until we encounter an EndOfDeclarationMarker node
89824                 var id = ts.getOriginalNodeId(node);
89825                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
89826             }
89827             else {
89828                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
89829             }
89830             return ts.singleOrMany(statements);
89831         }
89832         /**
89833          * Visits an ExportDeclaration node.
89834          *
89835          * @param The node to visit.
89836          */
89837         function visitExportDeclaration(node) {
89838             if (!node.moduleSpecifier) {
89839                 // Elide export declarations with no module specifier as they are handled
89840                 // elsewhere.
89841                 return undefined;
89842             }
89843             var generatedName = ts.getGeneratedNameForNode(node);
89844             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
89845                 var statements = [];
89846                 // export { x, y } from "mod";
89847                 if (moduleKind !== ts.ModuleKind.AMD) {
89848                     statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89849                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89850                         ts.createVariableDeclaration(generatedName, 
89851                         /*type*/ undefined, createRequireCall(node))
89852                     ])), 
89853                     /*location*/ node), 
89854                     /* original */ node));
89855                 }
89856                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
89857                     var specifier = _a[_i];
89858                     if (languageVersion === 0 /* ES3 */) {
89859                         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));
89860                     }
89861                     else {
89862                         var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
89863                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
89864                     }
89865                 }
89866                 return ts.singleOrMany(statements);
89867             }
89868             else if (node.exportClause) {
89869                 var statements = [];
89870                 // export * as ns from "mod";
89871                 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
89872                     getHelperExpressionForExport(node, createRequireCall(node)) :
89873                     ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
89874                 return ts.singleOrMany(statements);
89875             }
89876             else {
89877                 // export * from "mod";
89878                 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
89879             }
89880         }
89881         /**
89882          * Visits an ExportAssignment node.
89883          *
89884          * @param node The node to visit.
89885          */
89886         function visitExportAssignment(node) {
89887             if (node.isExportEquals) {
89888                 return undefined;
89889             }
89890             var statements;
89891             var original = node.original;
89892             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
89893                 // Defer exports until we encounter an EndOfDeclarationMarker node
89894                 var id = ts.getOriginalNodeId(node);
89895                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89896             }
89897             else {
89898                 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89899             }
89900             return ts.singleOrMany(statements);
89901         }
89902         /**
89903          * Visits a FunctionDeclaration node.
89904          *
89905          * @param node The node to visit.
89906          */
89907         function visitFunctionDeclaration(node) {
89908             var statements;
89909             if (ts.hasModifier(node, 1 /* Export */)) {
89910                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
89911                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89912                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
89913                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
89914                 /*location*/ node), 
89915                 /*original*/ node));
89916             }
89917             else {
89918                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89919             }
89920             if (hasAssociatedEndOfDeclarationMarker(node)) {
89921                 // Defer exports until we encounter an EndOfDeclarationMarker node
89922                 var id = ts.getOriginalNodeId(node);
89923                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89924             }
89925             else {
89926                 statements = appendExportsOfHoistedDeclaration(statements, node);
89927             }
89928             return ts.singleOrMany(statements);
89929         }
89930         /**
89931          * Visits a ClassDeclaration node.
89932          *
89933          * @param node The node to visit.
89934          */
89935         function visitClassDeclaration(node) {
89936             var statements;
89937             if (ts.hasModifier(node, 1 /* Export */)) {
89938                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
89939                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89940                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
89941             }
89942             else {
89943                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89944             }
89945             if (hasAssociatedEndOfDeclarationMarker(node)) {
89946                 // Defer exports until we encounter an EndOfDeclarationMarker node
89947                 var id = ts.getOriginalNodeId(node);
89948                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89949             }
89950             else {
89951                 statements = appendExportsOfHoistedDeclaration(statements, node);
89952             }
89953             return ts.singleOrMany(statements);
89954         }
89955         /**
89956          * Visits a VariableStatement node.
89957          *
89958          * @param node The node to visit.
89959          */
89960         function visitVariableStatement(node) {
89961             var statements;
89962             var variables;
89963             var expressions;
89964             if (ts.hasModifier(node, 1 /* Export */)) {
89965                 var modifiers = void 0;
89966                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
89967                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89968                     var variable = _a[_i];
89969                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
89970                         if (!modifiers) {
89971                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
89972                         }
89973                         variables = ts.append(variables, variable);
89974                     }
89975                     else if (variable.initializer) {
89976                         expressions = ts.append(expressions, transformInitializedVariable(variable));
89977                     }
89978                 }
89979                 if (variables) {
89980                     statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
89981                 }
89982                 if (expressions) {
89983                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
89984                 }
89985             }
89986             else {
89987                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89988             }
89989             if (hasAssociatedEndOfDeclarationMarker(node)) {
89990                 // Defer exports until we encounter an EndOfDeclarationMarker node
89991                 var id = ts.getOriginalNodeId(node);
89992                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
89993             }
89994             else {
89995                 statements = appendExportsOfVariableStatement(statements, node);
89996             }
89997             return ts.singleOrMany(statements);
89998         }
89999         function createAllExportExpressions(name, value, location) {
90000             var exportedNames = getExports(name);
90001             if (exportedNames) {
90002                 // For each additional export of the declaration, apply an export assignment.
90003                 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
90004                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
90005                     var exportName = exportedNames_1[_i];
90006                     // Mark the node to prevent triggering substitution.
90007                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
90008                     expression = createExportExpression(exportName, expression, /*location*/ location);
90009                 }
90010                 return expression;
90011             }
90012             return ts.createAssignment(name, value);
90013         }
90014         /**
90015          * Transforms an exported variable with an initializer into an expression.
90016          *
90017          * @param node The node to transform.
90018          */
90019         function transformInitializedVariable(node) {
90020             if (ts.isBindingPattern(node.name)) {
90021                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
90022                 /*visitor*/ undefined, context, 0 /* All */, 
90023                 /*needsValue*/ false, createAllExportExpressions);
90024             }
90025             else {
90026                 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
90027                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero());
90028             }
90029         }
90030         /**
90031          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
90032          * and transformed declaration.
90033          *
90034          * @param node The node to visit.
90035          */
90036         function visitMergeDeclarationMarker(node) {
90037             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
90038             // declaration we do not emit a leading variable declaration. To preserve the
90039             // begin/end semantics of the declararation and to properly handle exports
90040             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
90041             //
90042             // To balance the declaration, add the exports of the elided variable
90043             // statement.
90044             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
90045                 var id = ts.getOriginalNodeId(node);
90046                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
90047             }
90048             return node;
90049         }
90050         /**
90051          * Determines whether a node has an associated EndOfDeclarationMarker.
90052          *
90053          * @param node The node to test.
90054          */
90055         function hasAssociatedEndOfDeclarationMarker(node) {
90056             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
90057         }
90058         /**
90059          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
90060          * declaration.
90061          *
90062          * @param node The node to visit.
90063          */
90064         function visitEndOfDeclarationMarker(node) {
90065             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
90066             // end of the transformed declaration. We use this marker to emit any deferred exports
90067             // of the declaration.
90068             var id = ts.getOriginalNodeId(node);
90069             var statements = deferredExports[id];
90070             if (statements) {
90071                 delete deferredExports[id];
90072                 return ts.append(statements, node);
90073             }
90074             return node;
90075         }
90076         /**
90077          * Appends the exports of an ImportDeclaration to a statement list, returning the
90078          * statement list.
90079          *
90080          * @param statements A statement list to which the down-level export statements are to be
90081          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90082          * appended.
90083          * @param decl The declaration whose exports are to be recorded.
90084          */
90085         function appendExportsOfImportDeclaration(statements, decl) {
90086             if (currentModuleInfo.exportEquals) {
90087                 return statements;
90088             }
90089             var importClause = decl.importClause;
90090             if (!importClause) {
90091                 return statements;
90092             }
90093             if (importClause.name) {
90094                 statements = appendExportsOfDeclaration(statements, importClause);
90095             }
90096             var namedBindings = importClause.namedBindings;
90097             if (namedBindings) {
90098                 switch (namedBindings.kind) {
90099                     case 256 /* NamespaceImport */:
90100                         statements = appendExportsOfDeclaration(statements, namedBindings);
90101                         break;
90102                     case 257 /* NamedImports */:
90103                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
90104                             var importBinding = _a[_i];
90105                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
90106                         }
90107                         break;
90108                 }
90109             }
90110             return statements;
90111         }
90112         /**
90113          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
90114          * statement list.
90115          *
90116          * @param statements A statement list to which the down-level export statements are to be
90117          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90118          * appended.
90119          * @param decl The declaration whose exports are to be recorded.
90120          */
90121         function appendExportsOfImportEqualsDeclaration(statements, decl) {
90122             if (currentModuleInfo.exportEquals) {
90123                 return statements;
90124             }
90125             return appendExportsOfDeclaration(statements, decl);
90126         }
90127         /**
90128          * Appends the exports of a VariableStatement to a statement list, returning the statement
90129          * list.
90130          *
90131          * @param statements A statement list to which the down-level export statements are to be
90132          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90133          * appended.
90134          * @param node The VariableStatement whose exports are to be recorded.
90135          */
90136         function appendExportsOfVariableStatement(statements, node) {
90137             if (currentModuleInfo.exportEquals) {
90138                 return statements;
90139             }
90140             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90141                 var decl = _a[_i];
90142                 statements = appendExportsOfBindingElement(statements, decl);
90143             }
90144             return statements;
90145         }
90146         /**
90147          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
90148          * returning the statement list.
90149          *
90150          * @param statements A statement list to which the down-level export statements are to be
90151          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90152          * appended.
90153          * @param decl The declaration whose exports are to be recorded.
90154          */
90155         function appendExportsOfBindingElement(statements, decl) {
90156             if (currentModuleInfo.exportEquals) {
90157                 return statements;
90158             }
90159             if (ts.isBindingPattern(decl.name)) {
90160                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
90161                     var element = _a[_i];
90162                     if (!ts.isOmittedExpression(element)) {
90163                         statements = appendExportsOfBindingElement(statements, element);
90164                     }
90165                 }
90166             }
90167             else if (!ts.isGeneratedIdentifier(decl.name)) {
90168                 statements = appendExportsOfDeclaration(statements, decl);
90169             }
90170             return statements;
90171         }
90172         /**
90173          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
90174          * returning the statement list.
90175          *
90176          * @param statements A statement list to which the down-level export statements are to be
90177          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90178          * appended.
90179          * @param decl The declaration whose exports are to be recorded.
90180          */
90181         function appendExportsOfHoistedDeclaration(statements, decl) {
90182             if (currentModuleInfo.exportEquals) {
90183                 return statements;
90184             }
90185             if (ts.hasModifier(decl, 1 /* Export */)) {
90186                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
90187                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
90188             }
90189             if (decl.name) {
90190                 statements = appendExportsOfDeclaration(statements, decl);
90191             }
90192             return statements;
90193         }
90194         /**
90195          * Appends the exports of a declaration to a statement list, returning the statement list.
90196          *
90197          * @param statements A statement list to which the down-level export statements are to be
90198          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90199          * appended.
90200          * @param decl The declaration to export.
90201          */
90202         function appendExportsOfDeclaration(statements, decl, liveBinding) {
90203             var name = ts.getDeclarationName(decl);
90204             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
90205             if (exportSpecifiers) {
90206                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
90207                     var exportSpecifier = exportSpecifiers_1[_i];
90208                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
90209                 }
90210             }
90211             return statements;
90212         }
90213         /**
90214          * Appends the down-level representation of an export to a statement list, returning the
90215          * statement list.
90216          *
90217          * @param statements A statement list to which the down-level export statements are to be
90218          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90219          * appended.
90220          * @param exportName The name of the export.
90221          * @param expression The expression to export.
90222          * @param location The location to use for source maps and comments for the export.
90223          * @param allowComments Whether to allow comments on the export.
90224          */
90225         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
90226             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
90227             return statements;
90228         }
90229         function createUnderscoreUnderscoreESModule() {
90230             var statement;
90231             if (languageVersion === 0 /* ES3 */) {
90232                 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
90233             }
90234             else {
90235                 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90236                 /*typeArguments*/ undefined, [
90237                     ts.createIdentifier("exports"),
90238                     ts.createLiteral("__esModule"),
90239                     ts.createObjectLiteral([
90240                         ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
90241                     ])
90242                 ]));
90243             }
90244             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
90245             return statement;
90246         }
90247         /**
90248          * Creates a call to the current file's export function to export a value.
90249          *
90250          * @param name The bound name of the export.
90251          * @param value The exported value.
90252          * @param location The location to use for source maps and comments for the export.
90253          * @param allowComments An optional value indicating whether to emit comments for the statement.
90254          */
90255         function createExportStatement(name, value, location, allowComments, liveBinding) {
90256             var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
90257             ts.startOnNewLine(statement);
90258             if (!allowComments) {
90259                 ts.setEmitFlags(statement, 1536 /* NoComments */);
90260             }
90261             return statement;
90262         }
90263         /**
90264          * Creates a call to the current file's export function to export a value.
90265          *
90266          * @param name The bound name of the export.
90267          * @param value The exported value.
90268          * @param location The location to use for source maps and comments for the export.
90269          */
90270         function createExportExpression(name, value, location, liveBinding) {
90271             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90272             /*typeArguments*/ undefined, [
90273                 ts.createIdentifier("exports"),
90274                 ts.createLiteral(name),
90275                 ts.createObjectLiteral([
90276                     ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)),
90277                     ts.createPropertyAssignment("get", ts.createFunctionExpression(
90278                     /*modifiers*/ undefined, 
90279                     /*asteriskToken*/ undefined, 
90280                     /*name*/ undefined, 
90281                     /*typeParameters*/ undefined, 
90282                     /*parameters*/ [], 
90283                     /*type*/ undefined, ts.createBlock([ts.createReturn(value)])))
90284                 ])
90285             ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
90286         }
90287         //
90288         // Modifier Visitors
90289         //
90290         /**
90291          * Visit nodes to elide module-specific modifiers.
90292          *
90293          * @param node The node to visit.
90294          */
90295         function modifierVisitor(node) {
90296             // Elide module-specific modifiers.
90297             switch (node.kind) {
90298                 case 89 /* ExportKeyword */:
90299                 case 84 /* DefaultKeyword */:
90300                     return undefined;
90301             }
90302             return node;
90303         }
90304         //
90305         // Emit Notification
90306         //
90307         /**
90308          * Hook for node emit notifications.
90309          *
90310          * @param hint A hint as to the intended usage of the node.
90311          * @param node The node to emit.
90312          * @param emit A callback used to emit the node in the printer.
90313          */
90314         function onEmitNode(hint, node, emitCallback) {
90315             if (node.kind === 290 /* SourceFile */) {
90316                 currentSourceFile = node;
90317                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
90318                 noSubstitution = [];
90319                 previousOnEmitNode(hint, node, emitCallback);
90320                 currentSourceFile = undefined;
90321                 currentModuleInfo = undefined;
90322                 noSubstitution = undefined;
90323             }
90324             else {
90325                 previousOnEmitNode(hint, node, emitCallback);
90326             }
90327         }
90328         //
90329         // Substitutions
90330         //
90331         /**
90332          * Hooks node substitutions.
90333          *
90334          * @param hint A hint as to the intended usage of the node.
90335          * @param node The node to substitute.
90336          */
90337         function onSubstituteNode(hint, node) {
90338             node = previousOnSubstituteNode(hint, node);
90339             if (node.id && noSubstitution[node.id]) {
90340                 return node;
90341             }
90342             if (hint === 1 /* Expression */) {
90343                 return substituteExpression(node);
90344             }
90345             else if (ts.isShorthandPropertyAssignment(node)) {
90346                 return substituteShorthandPropertyAssignment(node);
90347             }
90348             return node;
90349         }
90350         /**
90351          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
90352          * or exported symbol.
90353          *
90354          * @param node The node to substitute.
90355          */
90356         function substituteShorthandPropertyAssignment(node) {
90357             var name = node.name;
90358             var exportedOrImportedName = substituteExpressionIdentifier(name);
90359             if (exportedOrImportedName !== name) {
90360                 // A shorthand property with an assignment initializer is probably part of a
90361                 // destructuring assignment
90362                 if (node.objectAssignmentInitializer) {
90363                     var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
90364                     return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
90365                 }
90366                 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
90367             }
90368             return node;
90369         }
90370         /**
90371          * Substitution for an Expression that may contain an imported or exported symbol.
90372          *
90373          * @param node The node to substitute.
90374          */
90375         function substituteExpression(node) {
90376             switch (node.kind) {
90377                 case 75 /* Identifier */:
90378                     return substituteExpressionIdentifier(node);
90379                 case 209 /* BinaryExpression */:
90380                     return substituteBinaryExpression(node);
90381                 case 208 /* PostfixUnaryExpression */:
90382                 case 207 /* PrefixUnaryExpression */:
90383                     return substituteUnaryExpression(node);
90384             }
90385             return node;
90386         }
90387         /**
90388          * Substitution for an Identifier expression that may contain an imported or exported
90389          * symbol.
90390          *
90391          * @param node The node to substitute.
90392          */
90393         function substituteExpressionIdentifier(node) {
90394             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
90395                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
90396                 if (externalHelpersModuleName) {
90397                     return ts.createPropertyAccess(externalHelpersModuleName, node);
90398                 }
90399                 return node;
90400             }
90401             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
90402                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
90403                 if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
90404                     return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
90405                     /*location*/ node);
90406                 }
90407                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
90408                 if (importDeclaration) {
90409                     if (ts.isImportClause(importDeclaration)) {
90410                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
90411                         /*location*/ node);
90412                     }
90413                     else if (ts.isImportSpecifier(importDeclaration)) {
90414                         var name = importDeclaration.propertyName || importDeclaration.name;
90415                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
90416                         /*location*/ node);
90417                     }
90418                 }
90419             }
90420             return node;
90421         }
90422         /**
90423          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
90424          *
90425          * @param node The node to substitute.
90426          */
90427         function substituteBinaryExpression(node) {
90428             // When we see an assignment expression whose left-hand side is an exported symbol,
90429             // we should ensure all exports of that symbol are updated with the correct value.
90430             //
90431             // - We do not substitute generated identifiers for any reason.
90432             // - We do not substitute identifiers tagged with the LocalName flag.
90433             // - We do not substitute identifiers that were originally the name of an enum or
90434             //   namespace due to how they are transformed in TypeScript.
90435             // - We only substitute identifiers that are exported at the top level.
90436             if (ts.isAssignmentOperator(node.operatorToken.kind)
90437                 && ts.isIdentifier(node.left)
90438                 && !ts.isGeneratedIdentifier(node.left)
90439                 && !ts.isLocalName(node.left)
90440                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
90441                 var exportedNames = getExports(node.left);
90442                 if (exportedNames) {
90443                     // For each additional export of the declaration, apply an export assignment.
90444                     var expression = node;
90445                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
90446                         var exportName = exportedNames_2[_i];
90447                         // Mark the node to prevent triggering this rule again.
90448                         noSubstitution[ts.getNodeId(expression)] = true;
90449                         expression = createExportExpression(exportName, expression, /*location*/ node);
90450                     }
90451                     return expression;
90452                 }
90453             }
90454             return node;
90455         }
90456         /**
90457          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
90458          *
90459          * @param node The node to substitute.
90460          */
90461         function substituteUnaryExpression(node) {
90462             // When we see a prefix or postfix increment expression whose operand is an exported
90463             // symbol, we should ensure all exports of that symbol are updated with the correct
90464             // value.
90465             //
90466             // - We do not substitute generated identifiers for any reason.
90467             // - We do not substitute identifiers tagged with the LocalName flag.
90468             // - We do not substitute identifiers that were originally the name of an enum or
90469             //   namespace due to how they are transformed in TypeScript.
90470             // - We only substitute identifiers that are exported at the top level.
90471             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
90472                 && ts.isIdentifier(node.operand)
90473                 && !ts.isGeneratedIdentifier(node.operand)
90474                 && !ts.isLocalName(node.operand)
90475                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
90476                 var exportedNames = getExports(node.operand);
90477                 if (exportedNames) {
90478                     var expression = node.kind === 208 /* PostfixUnaryExpression */
90479                         ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)), 
90480                         /*location*/ node)
90481                         : node;
90482                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
90483                         var exportName = exportedNames_3[_i];
90484                         // Mark the node to prevent triggering this rule again.
90485                         noSubstitution[ts.getNodeId(expression)] = true;
90486                         expression = createExportExpression(exportName, expression);
90487                     }
90488                     return expression;
90489                 }
90490             }
90491             return node;
90492         }
90493         /**
90494          * Gets the additional exports of a name.
90495          *
90496          * @param name The name.
90497          */
90498         function getExports(name) {
90499             if (!ts.isGeneratedIdentifier(name)) {
90500                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
90501                     || resolver.getReferencedValueDeclaration(name);
90502                 if (valueDeclaration) {
90503                     return currentModuleInfo
90504                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
90505                 }
90506             }
90507         }
90508     }
90509     ts.transformModule = transformModule;
90510     ts.createBindingHelper = {
90511         name: "typescript:commonjscreatebinding",
90512         importName: "__createBinding",
90513         scoped: false,
90514         priority: 1,
90515         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}));"
90516     };
90517     function createCreateBindingHelper(context, module, inputName, outputName) {
90518         context.requestEmitHelper(ts.createBindingHelper);
90519         return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
90520     }
90521     ts.setModuleDefaultHelper = {
90522         name: "typescript:commonjscreatevalue",
90523         importName: "__setModuleDefault",
90524         scoped: false,
90525         priority: 1,
90526         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});"
90527     };
90528     // emit output for the __export helper function
90529     var exportStarHelper = {
90530         name: "typescript:export-star",
90531         importName: "__exportStar",
90532         scoped: false,
90533         dependencies: [ts.createBindingHelper],
90534         priority: 2,
90535         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            };"
90536     };
90537     function createExportStarHelper(context, module) {
90538         context.requestEmitHelper(exportStarHelper);
90539         return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]);
90540     }
90541     // emit helper for dynamic import
90542     var dynamicImportUMDHelper = {
90543         name: "typescript:dynamicimport-sync-require",
90544         scoped: true,
90545         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
90546     };
90547     // emit helper for `import * as Name from "foo"`
90548     ts.importStarHelper = {
90549         name: "typescript:commonjsimportstar",
90550         importName: "__importStar",
90551         scoped: false,
90552         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
90553         priority: 2,
90554         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};"
90555     };
90556     // emit helper for `import Name from "foo"`
90557     ts.importDefaultHelper = {
90558         name: "typescript:commonjsimportdefault",
90559         importName: "__importDefault",
90560         scoped: false,
90561         text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
90562     };
90563 })(ts || (ts = {}));
90564 /*@internal*/
90565 var ts;
90566 (function (ts) {
90567     function transformSystemModule(context) {
90568         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
90569         var compilerOptions = context.getCompilerOptions();
90570         var resolver = context.getEmitResolver();
90571         var host = context.getEmitHost();
90572         var previousOnSubstituteNode = context.onSubstituteNode;
90573         var previousOnEmitNode = context.onEmitNode;
90574         context.onSubstituteNode = onSubstituteNode;
90575         context.onEmitNode = onEmitNode;
90576         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
90577         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
90578         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
90579         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
90580         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
90581         context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
90582         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
90583         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
90584         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
90585         var exportFunctionsMap = []; // The export function associated with a source file.
90586         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
90587         var contextObjectMap = []; // The context object associated with a source file.
90588         var currentSourceFile; // The current file.
90589         var moduleInfo; // ExternalModuleInfo for the current file.
90590         var exportFunction; // The export function for the current file.
90591         var contextObject; // The context object for the current file.
90592         var hoistedStatements;
90593         var enclosingBlockScopedContainer;
90594         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
90595         return ts.chainBundle(transformSourceFile);
90596         /**
90597          * Transforms the module aspects of a SourceFile.
90598          *
90599          * @param node The SourceFile node.
90600          */
90601         function transformSourceFile(node) {
90602             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
90603                 return node;
90604             }
90605             var id = ts.getOriginalNodeId(node);
90606             currentSourceFile = node;
90607             enclosingBlockScopedContainer = node;
90608             // System modules have the following shape:
90609             //
90610             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
90611             //
90612             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
90613             // is used to publish exported values. 'exports' returns its 'value' argument so in
90614             // most cases expressions that mutate exported values can be rewritten as:
90615             //
90616             //     expr -> exports('name', expr)
90617             //
90618             // The only exception in this rule is postfix unary operators,
90619             // see comment to 'substitutePostfixUnaryExpression' for more details
90620             // Collect information about the external module and dependency groups.
90621             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
90622             // Make sure that the name of the 'exports' function does not conflict with
90623             // existing identifiers.
90624             exportFunction = ts.createUniqueName("exports");
90625             exportFunctionsMap[id] = exportFunction;
90626             contextObject = contextObjectMap[id] = ts.createUniqueName("context");
90627             // Add the body of the module.
90628             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
90629             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
90630             var moduleBodyFunction = ts.createFunctionExpression(
90631             /*modifiers*/ undefined, 
90632             /*asteriskToken*/ undefined, 
90633             /*name*/ undefined, 
90634             /*typeParameters*/ undefined, [
90635                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
90636                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
90637             ], 
90638             /*type*/ undefined, moduleBodyBlock);
90639             // Write the call to `System.register`
90640             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
90641             // So the helper will be emit at the correct position instead of at the top of the source-file
90642             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
90643             var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
90644             var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
90645                 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
90646                 /*typeArguments*/ undefined, moduleName
90647                     ? [moduleName, dependencies, moduleBodyFunction]
90648                     : [dependencies, moduleBodyFunction]))
90649             ]), node.statements)), 1024 /* NoTrailingComments */);
90650             if (!(compilerOptions.outFile || compilerOptions.out)) {
90651                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
90652             }
90653             if (noSubstitution) {
90654                 noSubstitutionMap[id] = noSubstitution;
90655                 noSubstitution = undefined;
90656             }
90657             currentSourceFile = undefined;
90658             moduleInfo = undefined;
90659             exportFunction = undefined;
90660             contextObject = undefined;
90661             hoistedStatements = undefined;
90662             enclosingBlockScopedContainer = undefined;
90663             return ts.aggregateTransformFlags(updated);
90664         }
90665         /**
90666          * Collects the dependency groups for this files imports.
90667          *
90668          * @param externalImports The imports for the file.
90669          */
90670         function collectDependencyGroups(externalImports) {
90671             var groupIndices = ts.createMap();
90672             var dependencyGroups = [];
90673             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
90674                 var externalImport = externalImports_1[_i];
90675                 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
90676                 if (externalModuleName) {
90677                     var text = externalModuleName.text;
90678                     var groupIndex = groupIndices.get(text);
90679                     if (groupIndex !== undefined) {
90680                         // deduplicate/group entries in dependency list by the dependency name
90681                         dependencyGroups[groupIndex].externalImports.push(externalImport);
90682                     }
90683                     else {
90684                         groupIndices.set(text, dependencyGroups.length);
90685                         dependencyGroups.push({
90686                             name: externalModuleName,
90687                             externalImports: [externalImport]
90688                         });
90689                     }
90690                 }
90691             }
90692             return dependencyGroups;
90693         }
90694         /**
90695          * Adds the statements for the module body function for the source file.
90696          *
90697          * @param node The source file for the module.
90698          * @param dependencyGroups The grouped dependencies of the module.
90699          */
90700         function createSystemModuleBody(node, dependencyGroups) {
90701             // Shape of the body in system modules:
90702             //
90703             //  function (exports) {
90704             //      <list of local aliases for imports>
90705             //      <hoisted variable declarations>
90706             //      <hoisted function declarations>
90707             //      return {
90708             //          setters: [
90709             //              <list of setter function for imports>
90710             //          ],
90711             //          execute: function() {
90712             //              <module statements>
90713             //          }
90714             //      }
90715             //      <temp declarations>
90716             //  }
90717             //
90718             // i.e:
90719             //
90720             //   import {x} from 'file1'
90721             //   var y = 1;
90722             //   export function foo() { return y + x(); }
90723             //   console.log(y);
90724             //
90725             // Will be transformed to:
90726             //
90727             //  function(exports) {
90728             //      function foo() { return y + file_1.x(); }
90729             //      exports("foo", foo);
90730             //      var file_1, y;
90731             //      return {
90732             //          setters: [
90733             //              function(v) { file_1 = v }
90734             //          ],
90735             //          execute(): function() {
90736             //              y = 1;
90737             //              console.log(y);
90738             //          }
90739             //      };
90740             //  }
90741             var statements = [];
90742             // We start a new lexical environment in this function body, but *not* in the
90743             // body of the execute function. This allows us to emit temporary declarations
90744             // only in the outer module body and not in the inner one.
90745             startLexicalEnvironment();
90746             // Add any prologue directives.
90747             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
90748             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
90749             // var __moduleName = context_1 && context_1.id;
90750             statements.push(ts.createVariableStatement(
90751             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90752                 ts.createVariableDeclaration("__moduleName", 
90753                 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
90754             ])));
90755             // Visit the synthetic external helpers import declaration if present
90756             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
90757             // Visit the statements of the source file, emitting any transformations into
90758             // the `executeStatements` array. We do this *before* we fill the `setters` array
90759             // as we both emit transformations as well as aggregate some data used when creating
90760             // setters. This allows us to reduce the number of times we need to loop through the
90761             // statements of the source file.
90762             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
90763             // Emit early exports for function declarations.
90764             ts.addRange(statements, hoistedStatements);
90765             // We emit hoisted variables early to align roughly with our previous emit output.
90766             // Two key differences in this approach are:
90767             // - Temporary variables will appear at the top rather than at the bottom of the file
90768             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90769             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
90770             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
90771                 ts.createModifiersFromModifierFlags(256 /* Async */) :
90772                 undefined;
90773             var moduleObject = ts.createObjectLiteral([
90774                 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
90775                 ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers, 
90776                 /*asteriskToken*/ undefined, 
90777                 /*name*/ undefined, 
90778                 /*typeParameters*/ undefined, 
90779                 /*parameters*/ [], 
90780                 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
90781             ]);
90782             moduleObject.multiLine = true;
90783             statements.push(ts.createReturn(moduleObject));
90784             return ts.createBlock(statements, /*multiLine*/ true);
90785         }
90786         /**
90787          * Adds an exportStar function to a statement list if it is needed for the file.
90788          *
90789          * @param statements A statement list.
90790          */
90791         function addExportStarIfNeeded(statements) {
90792             if (!moduleInfo.hasExportStarsToExportValues) {
90793                 return;
90794             }
90795             // when resolving exports local exported entries/indirect exported entries in the module
90796             // should always win over entries with similar names that were added via star exports
90797             // to support this we store names of local/indirect exported entries in a set.
90798             // this set is used to filter names brought by star expors.
90799             // local names set should only be added if we have anything exported
90800             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
90801                 // no exported declarations (export var ...) or export specifiers (export {x})
90802                 // check if we have any non star export declarations.
90803                 var hasExportDeclarationWithExportClause = false;
90804                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
90805                     var externalImport = _a[_i];
90806                     if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
90807                         hasExportDeclarationWithExportClause = true;
90808                         break;
90809                     }
90810                 }
90811                 if (!hasExportDeclarationWithExportClause) {
90812                     // we still need to emit exportStar helper
90813                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
90814                     statements.push(exportStarFunction_1);
90815                     return exportStarFunction_1.name;
90816                 }
90817             }
90818             var exportedNames = [];
90819             if (moduleInfo.exportedNames) {
90820                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
90821                     var exportedLocalName = _c[_b];
90822                     if (exportedLocalName.escapedText === "default") {
90823                         continue;
90824                     }
90825                     // write name of exported declaration, i.e 'export var x...'
90826                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
90827                 }
90828             }
90829             for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
90830                 var externalImport = _e[_d];
90831                 if (externalImport.kind !== 260 /* ExportDeclaration */) {
90832                     continue;
90833                 }
90834                 if (!externalImport.exportClause) {
90835                     // export * from ...
90836                     continue;
90837                 }
90838                 if (ts.isNamedExports(externalImport.exportClause)) {
90839                     for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
90840                         var element = _g[_f];
90841                         // write name of indirectly exported entry, i.e. 'export {x} from ...'
90842                         exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
90843                     }
90844                 }
90845                 else {
90846                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
90847                 }
90848             }
90849             var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
90850             statements.push(ts.createVariableStatement(
90851             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90852                 ts.createVariableDeclaration(exportedNamesStorageRef, 
90853                 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
90854             ])));
90855             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
90856             statements.push(exportStarFunction);
90857             return exportStarFunction.name;
90858         }
90859         /**
90860          * Creates an exportStar function for the file, with an optional set of excluded local
90861          * names.
90862          *
90863          * @param localNames An optional reference to an object containing a set of excluded local
90864          * names.
90865          */
90866         function createExportStarFunction(localNames) {
90867             var exportStarFunction = ts.createUniqueName("exportStar");
90868             var m = ts.createIdentifier("m");
90869             var n = ts.createIdentifier("n");
90870             var exports = ts.createIdentifier("exports");
90871             var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
90872             if (localNames) {
90873                 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
90874                 /*typeArguments*/ undefined, [n])));
90875             }
90876             return ts.createFunctionDeclaration(
90877             /*decorators*/ undefined, 
90878             /*modifiers*/ undefined, 
90879             /*asteriskToken*/ undefined, exportStarFunction, 
90880             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
90881             /*type*/ undefined, ts.createBlock([
90882                 ts.createVariableStatement(
90883                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
90884                     ts.createVariableDeclaration(exports, 
90885                     /*type*/ undefined, ts.createObjectLiteral([]))
90886                 ])),
90887                 ts.createForIn(ts.createVariableDeclarationList([
90888                     ts.createVariableDeclaration(n, /*type*/ undefined)
90889                 ]), m, ts.createBlock([
90890                     ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
90891                 ])),
90892                 ts.createExpressionStatement(ts.createCall(exportFunction, 
90893                 /*typeArguments*/ undefined, [exports]))
90894             ], /*multiline*/ true));
90895         }
90896         /**
90897          * Creates an array setter callbacks for each dependency group.
90898          *
90899          * @param exportStarFunction A reference to an exportStarFunction for the file.
90900          * @param dependencyGroups An array of grouped dependencies.
90901          */
90902         function createSettersArray(exportStarFunction, dependencyGroups) {
90903             var setters = [];
90904             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
90905                 var group_2 = dependencyGroups_1[_i];
90906                 // derive a unique name for parameter from the first named entry in the group
90907                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
90908                 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
90909                 var statements = [];
90910                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
90911                     var entry = _b[_a];
90912                     var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
90913                     switch (entry.kind) {
90914                         case 254 /* ImportDeclaration */:
90915                             if (!entry.importClause) {
90916                                 // 'import "..."' case
90917                                 // module is imported only for side-effects, no emit required
90918                                 break;
90919                             }
90920                         // falls through
90921                         case 253 /* ImportEqualsDeclaration */:
90922                             ts.Debug.assert(importVariableName !== undefined);
90923                             // save import into the local
90924                             statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
90925                             break;
90926                         case 260 /* ExportDeclaration */:
90927                             ts.Debug.assert(importVariableName !== undefined);
90928                             if (entry.exportClause) {
90929                                 if (ts.isNamedExports(entry.exportClause)) {
90930                                     //  export {a, b as c} from 'foo'
90931                                     //
90932                                     // emit as:
90933                                     //
90934                                     //  exports_({
90935                                     //     "a": _["a"],
90936                                     //     "c": _["b"]
90937                                     //  });
90938                                     var properties = [];
90939                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
90940                                         var e = _d[_c];
90941                                         properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
90942                                     }
90943                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90944                                     /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
90945                                 }
90946                                 else {
90947                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90948                                     /*typeArguments*/ undefined, [
90949                                         ts.createLiteral(ts.idText(entry.exportClause.name)),
90950                                         parameterName
90951                                     ])));
90952                                 }
90953                             }
90954                             else {
90955                                 //  export * from 'foo'
90956                                 //
90957                                 // emit as:
90958                                 //
90959                                 //  exportStar(foo_1_1);
90960                                 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
90961                                 /*typeArguments*/ undefined, [parameterName])));
90962                             }
90963                             break;
90964                     }
90965                 }
90966                 setters.push(ts.createFunctionExpression(
90967                 /*modifiers*/ undefined, 
90968                 /*asteriskToken*/ undefined, 
90969                 /*name*/ undefined, 
90970                 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90971                 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
90972             }
90973             return ts.createArrayLiteral(setters, /*multiLine*/ true);
90974         }
90975         //
90976         // Top-level Source Element Visitors
90977         //
90978         /**
90979          * Visit source elements at the top-level of a module.
90980          *
90981          * @param node The node to visit.
90982          */
90983         function sourceElementVisitor(node) {
90984             switch (node.kind) {
90985                 case 254 /* ImportDeclaration */:
90986                     return visitImportDeclaration(node);
90987                 case 253 /* ImportEqualsDeclaration */:
90988                     return visitImportEqualsDeclaration(node);
90989                 case 260 /* ExportDeclaration */:
90990                     return visitExportDeclaration(node);
90991                 case 259 /* ExportAssignment */:
90992                     return visitExportAssignment(node);
90993                 default:
90994                     return nestedElementVisitor(node);
90995             }
90996         }
90997         /**
90998          * Visits an ImportDeclaration node.
90999          *
91000          * @param node The node to visit.
91001          */
91002         function visitImportDeclaration(node) {
91003             var statements;
91004             if (node.importClause) {
91005                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
91006             }
91007             if (hasAssociatedEndOfDeclarationMarker(node)) {
91008                 // Defer exports until we encounter an EndOfDeclarationMarker node
91009                 var id = ts.getOriginalNodeId(node);
91010                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
91011             }
91012             else {
91013                 statements = appendExportsOfImportDeclaration(statements, node);
91014             }
91015             return ts.singleOrMany(statements);
91016         }
91017         function visitExportDeclaration(node) {
91018             ts.Debug.assertIsDefined(node);
91019             return undefined;
91020         }
91021         /**
91022          * Visits an ImportEqualsDeclaration node.
91023          *
91024          * @param node The node to visit.
91025          */
91026         function visitImportEqualsDeclaration(node) {
91027             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
91028             var statements;
91029             hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
91030             if (hasAssociatedEndOfDeclarationMarker(node)) {
91031                 // Defer exports until we encounter an EndOfDeclarationMarker node
91032                 var id = ts.getOriginalNodeId(node);
91033                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
91034             }
91035             else {
91036                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
91037             }
91038             return ts.singleOrMany(statements);
91039         }
91040         /**
91041          * Visits an ExportAssignment node.
91042          *
91043          * @param node The node to visit.
91044          */
91045         function visitExportAssignment(node) {
91046             if (node.isExportEquals) {
91047                 // Elide `export=` as it is illegal in a SystemJS module.
91048                 return undefined;
91049             }
91050             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
91051             var original = node.original;
91052             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
91053                 // Defer exports until we encounter an EndOfDeclarationMarker node
91054                 var id = ts.getOriginalNodeId(node);
91055                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
91056             }
91057             else {
91058                 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
91059             }
91060         }
91061         /**
91062          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
91063          *
91064          * @param node The node to visit.
91065          */
91066         function visitFunctionDeclaration(node) {
91067             if (ts.hasModifier(node, 1 /* Export */)) {
91068                 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), 
91069                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
91070                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
91071             }
91072             else {
91073                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
91074             }
91075             if (hasAssociatedEndOfDeclarationMarker(node)) {
91076                 // Defer exports until we encounter an EndOfDeclarationMarker node
91077                 var id = ts.getOriginalNodeId(node);
91078                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
91079             }
91080             else {
91081                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
91082             }
91083             return undefined;
91084         }
91085         /**
91086          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
91087          *
91088          * @param node The node to visit.
91089          */
91090         function visitClassDeclaration(node) {
91091             var statements;
91092             // Hoist the name of the class declaration to the outer module body function.
91093             var name = ts.getLocalName(node);
91094             hoistVariableDeclaration(name);
91095             // Rewrite the class declaration into an assignment of a class expression.
91096             statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
91097             /*modifiers*/ undefined, node.name, 
91098             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
91099             if (hasAssociatedEndOfDeclarationMarker(node)) {
91100                 // Defer exports until we encounter an EndOfDeclarationMarker node
91101                 var id = ts.getOriginalNodeId(node);
91102                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
91103             }
91104             else {
91105                 statements = appendExportsOfHoistedDeclaration(statements, node);
91106             }
91107             return ts.singleOrMany(statements);
91108         }
91109         /**
91110          * Visits a variable statement, hoisting declared names to the top-level module body.
91111          * Each declaration is rewritten into an assignment expression.
91112          *
91113          * @param node The node to visit.
91114          */
91115         function visitVariableStatement(node) {
91116             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
91117                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
91118             }
91119             var expressions;
91120             var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
91121             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
91122             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91123                 var variable = _a[_i];
91124                 if (variable.initializer) {
91125                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
91126                 }
91127                 else {
91128                     hoistBindingElement(variable);
91129                 }
91130             }
91131             var statements;
91132             if (expressions) {
91133                 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
91134             }
91135             if (isMarkedDeclaration) {
91136                 // Defer exports until we encounter an EndOfDeclarationMarker node
91137                 var id = ts.getOriginalNodeId(node);
91138                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
91139             }
91140             else {
91141                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
91142             }
91143             return ts.singleOrMany(statements);
91144         }
91145         /**
91146          * Hoists the declared names of a VariableDeclaration or BindingElement.
91147          *
91148          * @param node The declaration to hoist.
91149          */
91150         function hoistBindingElement(node) {
91151             if (ts.isBindingPattern(node.name)) {
91152                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
91153                     var element = _a[_i];
91154                     if (!ts.isOmittedExpression(element)) {
91155                         hoistBindingElement(element);
91156                     }
91157                 }
91158             }
91159             else {
91160                 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
91161             }
91162         }
91163         /**
91164          * Determines whether a VariableDeclarationList should be hoisted.
91165          *
91166          * @param node The node to test.
91167          */
91168         function shouldHoistVariableDeclarationList(node) {
91169             // hoist only non-block scoped declarations or block scoped declarations parented by source file
91170             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
91171                 && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
91172                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
91173         }
91174         /**
91175          * Transform an initialized variable declaration into an expression.
91176          *
91177          * @param node The node to transform.
91178          * @param isExportedDeclaration A value indicating whether the variable is exported.
91179          */
91180         function transformInitializedVariable(node, isExportedDeclaration) {
91181             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
91182             return ts.isBindingPattern(node.name)
91183                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91184                 /*needsValue*/ false, createAssignment)
91185                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
91186         }
91187         /**
91188          * Creates an assignment expression for an exported variable declaration.
91189          *
91190          * @param name The name of the variable.
91191          * @param value The value of the variable's initializer.
91192          * @param location The source map location for the assignment.
91193          */
91194         function createExportedVariableAssignment(name, value, location) {
91195             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
91196         }
91197         /**
91198          * Creates an assignment expression for a non-exported variable declaration.
91199          *
91200          * @param name The name of the variable.
91201          * @param value The value of the variable's initializer.
91202          * @param location The source map location for the assignment.
91203          */
91204         function createNonExportedVariableAssignment(name, value, location) {
91205             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
91206         }
91207         /**
91208          * Creates an assignment expression for a variable declaration.
91209          *
91210          * @param name The name of the variable.
91211          * @param value The value of the variable's initializer.
91212          * @param location The source map location for the assignment.
91213          * @param isExportedDeclaration A value indicating whether the variable is exported.
91214          */
91215         function createVariableAssignment(name, value, location, isExportedDeclaration) {
91216             hoistVariableDeclaration(ts.getSynthesizedClone(name));
91217             return isExportedDeclaration
91218                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
91219                 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
91220         }
91221         /**
91222          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
91223          * and transformed declaration.
91224          *
91225          * @param node The node to visit.
91226          */
91227         function visitMergeDeclarationMarker(node) {
91228             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91229             // declaration we do not emit a leading variable declaration. To preserve the
91230             // begin/end semantics of the declararation and to properly handle exports
91231             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
91232             //
91233             // To balance the declaration, we defer the exports of the elided variable
91234             // statement until we visit this declaration's `EndOfDeclarationMarker`.
91235             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
91236                 var id = ts.getOriginalNodeId(node);
91237                 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
91238                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
91239             }
91240             return node;
91241         }
91242         /**
91243          * Determines whether a node has an associated EndOfDeclarationMarker.
91244          *
91245          * @param node The node to test.
91246          */
91247         function hasAssociatedEndOfDeclarationMarker(node) {
91248             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
91249         }
91250         /**
91251          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
91252          * declaration.
91253          *
91254          * @param node The node to visit.
91255          */
91256         function visitEndOfDeclarationMarker(node) {
91257             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
91258             // end of the transformed declaration. We use this marker to emit any deferred exports
91259             // of the declaration.
91260             var id = ts.getOriginalNodeId(node);
91261             var statements = deferredExports[id];
91262             if (statements) {
91263                 delete deferredExports[id];
91264                 return ts.append(statements, node);
91265             }
91266             else {
91267                 var original = ts.getOriginalNode(node);
91268                 if (ts.isModuleOrEnumDeclaration(original)) {
91269                     return ts.append(appendExportsOfDeclaration(statements, original), node);
91270                 }
91271             }
91272             return node;
91273         }
91274         /**
91275          * Appends the exports of an ImportDeclaration to a statement list, returning the
91276          * statement list.
91277          *
91278          * @param statements A statement list to which the down-level export statements are to be
91279          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91280          * appended.
91281          * @param decl The declaration whose exports are to be recorded.
91282          */
91283         function appendExportsOfImportDeclaration(statements, decl) {
91284             if (moduleInfo.exportEquals) {
91285                 return statements;
91286             }
91287             var importClause = decl.importClause;
91288             if (!importClause) {
91289                 return statements;
91290             }
91291             if (importClause.name) {
91292                 statements = appendExportsOfDeclaration(statements, importClause);
91293             }
91294             var namedBindings = importClause.namedBindings;
91295             if (namedBindings) {
91296                 switch (namedBindings.kind) {
91297                     case 256 /* NamespaceImport */:
91298                         statements = appendExportsOfDeclaration(statements, namedBindings);
91299                         break;
91300                     case 257 /* NamedImports */:
91301                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
91302                             var importBinding = _a[_i];
91303                             statements = appendExportsOfDeclaration(statements, importBinding);
91304                         }
91305                         break;
91306                 }
91307             }
91308             return statements;
91309         }
91310         /**
91311          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
91312          * statement list.
91313          *
91314          * @param statements A statement list to which the down-level export statements are to be
91315          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91316          * appended.
91317          * @param decl The declaration whose exports are to be recorded.
91318          */
91319         function appendExportsOfImportEqualsDeclaration(statements, decl) {
91320             if (moduleInfo.exportEquals) {
91321                 return statements;
91322             }
91323             return appendExportsOfDeclaration(statements, decl);
91324         }
91325         /**
91326          * Appends the exports of a VariableStatement to a statement list, returning the statement
91327          * list.
91328          *
91329          * @param statements A statement list to which the down-level export statements are to be
91330          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91331          * appended.
91332          * @param node The VariableStatement whose exports are to be recorded.
91333          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
91334          * `nodes` declaration list.
91335          */
91336         function appendExportsOfVariableStatement(statements, node, exportSelf) {
91337             if (moduleInfo.exportEquals) {
91338                 return statements;
91339             }
91340             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91341                 var decl = _a[_i];
91342                 if (decl.initializer || exportSelf) {
91343                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
91344                 }
91345             }
91346             return statements;
91347         }
91348         /**
91349          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
91350          * returning the statement list.
91351          *
91352          * @param statements A statement list to which the down-level export statements are to be
91353          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91354          * appended.
91355          * @param decl The declaration whose exports are to be recorded.
91356          * @param exportSelf A value indicating whether to also export the declaration itself.
91357          */
91358         function appendExportsOfBindingElement(statements, decl, exportSelf) {
91359             if (moduleInfo.exportEquals) {
91360                 return statements;
91361             }
91362             if (ts.isBindingPattern(decl.name)) {
91363                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
91364                     var element = _a[_i];
91365                     if (!ts.isOmittedExpression(element)) {
91366                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
91367                     }
91368                 }
91369             }
91370             else if (!ts.isGeneratedIdentifier(decl.name)) {
91371                 var excludeName = void 0;
91372                 if (exportSelf) {
91373                     statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
91374                     excludeName = ts.idText(decl.name);
91375                 }
91376                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91377             }
91378             return statements;
91379         }
91380         /**
91381          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
91382          * returning the statement list.
91383          *
91384          * @param statements A statement list to which the down-level export statements are to be
91385          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91386          * appended.
91387          * @param decl The declaration whose exports are to be recorded.
91388          */
91389         function appendExportsOfHoistedDeclaration(statements, decl) {
91390             if (moduleInfo.exportEquals) {
91391                 return statements;
91392             }
91393             var excludeName;
91394             if (ts.hasModifier(decl, 1 /* Export */)) {
91395                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
91396                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
91397                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
91398             }
91399             if (decl.name) {
91400                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91401             }
91402             return statements;
91403         }
91404         /**
91405          * Appends the exports of a declaration to a statement list, returning the statement list.
91406          *
91407          * @param statements A statement list to which the down-level export statements are to be
91408          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91409          * appended.
91410          * @param decl The declaration to export.
91411          * @param excludeName An optional name to exclude from exports.
91412          */
91413         function appendExportsOfDeclaration(statements, decl, excludeName) {
91414             if (moduleInfo.exportEquals) {
91415                 return statements;
91416             }
91417             var name = ts.getDeclarationName(decl);
91418             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
91419             if (exportSpecifiers) {
91420                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
91421                     var exportSpecifier = exportSpecifiers_2[_i];
91422                     if (exportSpecifier.name.escapedText !== excludeName) {
91423                         statements = appendExportStatement(statements, exportSpecifier.name, name);
91424                     }
91425                 }
91426             }
91427             return statements;
91428         }
91429         /**
91430          * Appends the down-level representation of an export to a statement list, returning the
91431          * statement list.
91432          *
91433          * @param statements A statement list to which the down-level export statements are to be
91434          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91435          * appended.
91436          * @param exportName The name of the export.
91437          * @param expression The expression to export.
91438          * @param allowComments Whether to allow comments on the export.
91439          */
91440         function appendExportStatement(statements, exportName, expression, allowComments) {
91441             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
91442             return statements;
91443         }
91444         /**
91445          * Creates a call to the current file's export function to export a value.
91446          *
91447          * @param name The bound name of the export.
91448          * @param value The exported value.
91449          * @param allowComments An optional value indicating whether to emit comments for the statement.
91450          */
91451         function createExportStatement(name, value, allowComments) {
91452             var statement = ts.createExpressionStatement(createExportExpression(name, value));
91453             ts.startOnNewLine(statement);
91454             if (!allowComments) {
91455                 ts.setEmitFlags(statement, 1536 /* NoComments */);
91456             }
91457             return statement;
91458         }
91459         /**
91460          * Creates a call to the current file's export function to export a value.
91461          *
91462          * @param name The bound name of the export.
91463          * @param value The exported value.
91464          */
91465         function createExportExpression(name, value) {
91466             var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
91467             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
91468             return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
91469         }
91470         //
91471         // Top-Level or Nested Source Element Visitors
91472         //
91473         /**
91474          * Visit nested elements at the top-level of a module.
91475          *
91476          * @param node The node to visit.
91477          */
91478         function nestedElementVisitor(node) {
91479             switch (node.kind) {
91480                 case 225 /* VariableStatement */:
91481                     return visitVariableStatement(node);
91482                 case 244 /* FunctionDeclaration */:
91483                     return visitFunctionDeclaration(node);
91484                 case 245 /* ClassDeclaration */:
91485                     return visitClassDeclaration(node);
91486                 case 230 /* ForStatement */:
91487                     return visitForStatement(node);
91488                 case 231 /* ForInStatement */:
91489                     return visitForInStatement(node);
91490                 case 232 /* ForOfStatement */:
91491                     return visitForOfStatement(node);
91492                 case 228 /* DoStatement */:
91493                     return visitDoStatement(node);
91494                 case 229 /* WhileStatement */:
91495                     return visitWhileStatement(node);
91496                 case 238 /* LabeledStatement */:
91497                     return visitLabeledStatement(node);
91498                 case 236 /* WithStatement */:
91499                     return visitWithStatement(node);
91500                 case 237 /* SwitchStatement */:
91501                     return visitSwitchStatement(node);
91502                 case 251 /* CaseBlock */:
91503                     return visitCaseBlock(node);
91504                 case 277 /* CaseClause */:
91505                     return visitCaseClause(node);
91506                 case 278 /* DefaultClause */:
91507                     return visitDefaultClause(node);
91508                 case 240 /* TryStatement */:
91509                     return visitTryStatement(node);
91510                 case 280 /* CatchClause */:
91511                     return visitCatchClause(node);
91512                 case 223 /* Block */:
91513                     return visitBlock(node);
91514                 case 328 /* MergeDeclarationMarker */:
91515                     return visitMergeDeclarationMarker(node);
91516                 case 329 /* EndOfDeclarationMarker */:
91517                     return visitEndOfDeclarationMarker(node);
91518                 default:
91519                     return destructuringAndImportCallVisitor(node);
91520             }
91521         }
91522         /**
91523          * Visits the body of a ForStatement to hoist declarations.
91524          *
91525          * @param node The node to visit.
91526          */
91527         function visitForStatement(node) {
91528             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91529             enclosingBlockScopedContainer = node;
91530             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));
91531             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91532             return node;
91533         }
91534         /**
91535          * Visits the body of a ForInStatement to hoist declarations.
91536          *
91537          * @param node The node to visit.
91538          */
91539         function visitForInStatement(node) {
91540             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91541             enclosingBlockScopedContainer = node;
91542             node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91543             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91544             return node;
91545         }
91546         /**
91547          * Visits the body of a ForOfStatement to hoist declarations.
91548          *
91549          * @param node The node to visit.
91550          */
91551         function visitForOfStatement(node) {
91552             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91553             enclosingBlockScopedContainer = node;
91554             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));
91555             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91556             return node;
91557         }
91558         /**
91559          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
91560          * ForOfStatement.
91561          *
91562          * @param node The node to test.
91563          */
91564         function shouldHoistForInitializer(node) {
91565             return ts.isVariableDeclarationList(node)
91566                 && shouldHoistVariableDeclarationList(node);
91567         }
91568         /**
91569          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
91570          *
91571          * @param node The node to visit.
91572          */
91573         function visitForInitializer(node) {
91574             if (shouldHoistForInitializer(node)) {
91575                 var expressions = void 0;
91576                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
91577                     var variable = _a[_i];
91578                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
91579                     if (!variable.initializer) {
91580                         hoistBindingElement(variable);
91581                     }
91582                 }
91583                 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
91584             }
91585             else {
91586                 return ts.visitEachChild(node, nestedElementVisitor, context);
91587             }
91588         }
91589         /**
91590          * Visits the body of a DoStatement to hoist declarations.
91591          *
91592          * @param node The node to visit.
91593          */
91594         function visitDoStatement(node) {
91595             return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
91596         }
91597         /**
91598          * Visits the body of a WhileStatement to hoist declarations.
91599          *
91600          * @param node The node to visit.
91601          */
91602         function visitWhileStatement(node) {
91603             return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91604         }
91605         /**
91606          * Visits the body of a LabeledStatement to hoist declarations.
91607          *
91608          * @param node The node to visit.
91609          */
91610         function visitLabeledStatement(node) {
91611             return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91612         }
91613         /**
91614          * Visits the body of a WithStatement to hoist declarations.
91615          *
91616          * @param node The node to visit.
91617          */
91618         function visitWithStatement(node) {
91619             return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91620         }
91621         /**
91622          * Visits the body of a SwitchStatement to hoist declarations.
91623          *
91624          * @param node The node to visit.
91625          */
91626         function visitSwitchStatement(node) {
91627             return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
91628         }
91629         /**
91630          * Visits the body of a CaseBlock to hoist declarations.
91631          *
91632          * @param node The node to visit.
91633          */
91634         function visitCaseBlock(node) {
91635             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91636             enclosingBlockScopedContainer = node;
91637             node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
91638             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91639             return node;
91640         }
91641         /**
91642          * Visits the body of a CaseClause to hoist declarations.
91643          *
91644          * @param node The node to visit.
91645          */
91646         function visitCaseClause(node) {
91647             return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
91648         }
91649         /**
91650          * Visits the body of a DefaultClause to hoist declarations.
91651          *
91652          * @param node The node to visit.
91653          */
91654         function visitDefaultClause(node) {
91655             return ts.visitEachChild(node, nestedElementVisitor, context);
91656         }
91657         /**
91658          * Visits the body of a TryStatement to hoist declarations.
91659          *
91660          * @param node The node to visit.
91661          */
91662         function visitTryStatement(node) {
91663             return ts.visitEachChild(node, nestedElementVisitor, context);
91664         }
91665         /**
91666          * Visits the body of a CatchClause to hoist declarations.
91667          *
91668          * @param node The node to visit.
91669          */
91670         function visitCatchClause(node) {
91671             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91672             enclosingBlockScopedContainer = node;
91673             node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
91674             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91675             return node;
91676         }
91677         /**
91678          * Visits the body of a Block to hoist declarations.
91679          *
91680          * @param node The node to visit.
91681          */
91682         function visitBlock(node) {
91683             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91684             enclosingBlockScopedContainer = node;
91685             node = ts.visitEachChild(node, nestedElementVisitor, context);
91686             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91687             return node;
91688         }
91689         //
91690         // Destructuring Assignment Visitors
91691         //
91692         /**
91693          * Visit nodes to flatten destructuring assignments to exported symbols.
91694          *
91695          * @param node The node to visit.
91696          */
91697         function destructuringAndImportCallVisitor(node) {
91698             if (ts.isDestructuringAssignment(node)) {
91699                 return visitDestructuringAssignment(node);
91700             }
91701             else if (ts.isImportCall(node)) {
91702                 return visitImportCallExpression(node);
91703             }
91704             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
91705                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91706             }
91707             else {
91708                 return node;
91709             }
91710         }
91711         function visitImportCallExpression(node) {
91712             // import("./blah")
91713             // emit as
91714             // System.register([], function (_export, _context) {
91715             //     return {
91716             //         setters: [],
91717             //         execute: () => {
91718             //             _context.import('./blah');
91719             //         }
91720             //     };
91721             // });
91722             return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
91723             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
91724         }
91725         /**
91726          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
91727          *
91728          * @param node The node to visit.
91729          */
91730         function visitDestructuringAssignment(node) {
91731             if (hasExportedReferenceInDestructuringTarget(node.left)) {
91732                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91733                 /*needsValue*/ true);
91734             }
91735             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91736         }
91737         /**
91738          * Determines whether the target of a destructuring assigment refers to an exported symbol.
91739          *
91740          * @param node The destructuring target.
91741          */
91742         function hasExportedReferenceInDestructuringTarget(node) {
91743             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
91744                 return hasExportedReferenceInDestructuringTarget(node.left);
91745             }
91746             else if (ts.isSpreadElement(node)) {
91747                 return hasExportedReferenceInDestructuringTarget(node.expression);
91748             }
91749             else if (ts.isObjectLiteralExpression(node)) {
91750                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
91751             }
91752             else if (ts.isArrayLiteralExpression(node)) {
91753                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
91754             }
91755             else if (ts.isShorthandPropertyAssignment(node)) {
91756                 return hasExportedReferenceInDestructuringTarget(node.name);
91757             }
91758             else if (ts.isPropertyAssignment(node)) {
91759                 return hasExportedReferenceInDestructuringTarget(node.initializer);
91760             }
91761             else if (ts.isIdentifier(node)) {
91762                 var container = resolver.getReferencedExportContainer(node);
91763                 return container !== undefined && container.kind === 290 /* SourceFile */;
91764             }
91765             else {
91766                 return false;
91767             }
91768         }
91769         //
91770         // Modifier Visitors
91771         //
91772         /**
91773          * Visit nodes to elide module-specific modifiers.
91774          *
91775          * @param node The node to visit.
91776          */
91777         function modifierVisitor(node) {
91778             switch (node.kind) {
91779                 case 89 /* ExportKeyword */:
91780                 case 84 /* DefaultKeyword */:
91781                     return undefined;
91782             }
91783             return node;
91784         }
91785         //
91786         // Emit Notification
91787         //
91788         /**
91789          * Hook for node emit notifications.
91790          *
91791          * @param hint A hint as to the intended usage of the node.
91792          * @param node The node to emit.
91793          * @param emitCallback A callback used to emit the node in the printer.
91794          */
91795         function onEmitNode(hint, node, emitCallback) {
91796             if (node.kind === 290 /* SourceFile */) {
91797                 var id = ts.getOriginalNodeId(node);
91798                 currentSourceFile = node;
91799                 moduleInfo = moduleInfoMap[id];
91800                 exportFunction = exportFunctionsMap[id];
91801                 noSubstitution = noSubstitutionMap[id];
91802                 contextObject = contextObjectMap[id];
91803                 if (noSubstitution) {
91804                     delete noSubstitutionMap[id];
91805                 }
91806                 previousOnEmitNode(hint, node, emitCallback);
91807                 currentSourceFile = undefined;
91808                 moduleInfo = undefined;
91809                 exportFunction = undefined;
91810                 contextObject = undefined;
91811                 noSubstitution = undefined;
91812             }
91813             else {
91814                 previousOnEmitNode(hint, node, emitCallback);
91815             }
91816         }
91817         //
91818         // Substitutions
91819         //
91820         /**
91821          * Hooks node substitutions.
91822          *
91823          * @param hint A hint as to the intended usage of the node.
91824          * @param node The node to substitute.
91825          */
91826         function onSubstituteNode(hint, node) {
91827             node = previousOnSubstituteNode(hint, node);
91828             if (isSubstitutionPrevented(node)) {
91829                 return node;
91830             }
91831             if (hint === 1 /* Expression */) {
91832                 return substituteExpression(node);
91833             }
91834             else if (hint === 4 /* Unspecified */) {
91835                 return substituteUnspecified(node);
91836             }
91837             return node;
91838         }
91839         /**
91840          * Substitute the node, if necessary.
91841          *
91842          * @param node The node to substitute.
91843          */
91844         function substituteUnspecified(node) {
91845             switch (node.kind) {
91846                 case 282 /* ShorthandPropertyAssignment */:
91847                     return substituteShorthandPropertyAssignment(node);
91848             }
91849             return node;
91850         }
91851         /**
91852          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
91853          *
91854          * @param node The node to substitute.
91855          */
91856         function substituteShorthandPropertyAssignment(node) {
91857             var name = node.name;
91858             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
91859                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
91860                 if (importDeclaration) {
91861                     if (ts.isImportClause(importDeclaration)) {
91862                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
91863                         /*location*/ node);
91864                     }
91865                     else if (ts.isImportSpecifier(importDeclaration)) {
91866                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
91867                         /*location*/ node);
91868                     }
91869                 }
91870             }
91871             return node;
91872         }
91873         /**
91874          * Substitute the expression, if necessary.
91875          *
91876          * @param node The node to substitute.
91877          */
91878         function substituteExpression(node) {
91879             switch (node.kind) {
91880                 case 75 /* Identifier */:
91881                     return substituteExpressionIdentifier(node);
91882                 case 209 /* BinaryExpression */:
91883                     return substituteBinaryExpression(node);
91884                 case 207 /* PrefixUnaryExpression */:
91885                 case 208 /* PostfixUnaryExpression */:
91886                     return substituteUnaryExpression(node);
91887                 case 219 /* MetaProperty */:
91888                     return substituteMetaProperty(node);
91889             }
91890             return node;
91891         }
91892         /**
91893          * Substitution for an Identifier expression that may contain an imported or exported symbol.
91894          *
91895          * @param node The node to substitute.
91896          */
91897         function substituteExpressionIdentifier(node) {
91898             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
91899                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
91900                 if (externalHelpersModuleName) {
91901                     return ts.createPropertyAccess(externalHelpersModuleName, node);
91902                 }
91903                 return node;
91904             }
91905             // When we see an identifier in an expression position that
91906             // points to an imported symbol, we should substitute a qualified
91907             // reference to the imported symbol if one is needed.
91908             //
91909             // - We do not substitute generated identifiers for any reason.
91910             // - We do not substitute identifiers tagged with the LocalName flag.
91911             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91912                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
91913                 if (importDeclaration) {
91914                     if (ts.isImportClause(importDeclaration)) {
91915                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
91916                         /*location*/ node);
91917                     }
91918                     else if (ts.isImportSpecifier(importDeclaration)) {
91919                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
91920                         /*location*/ node);
91921                     }
91922                 }
91923             }
91924             return node;
91925         }
91926         /**
91927          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
91928          *
91929          * @param node The node to substitute.
91930          */
91931         function substituteBinaryExpression(node) {
91932             // When we see an assignment expression whose left-hand side is an exported symbol,
91933             // we should ensure all exports of that symbol are updated with the correct value.
91934             //
91935             // - We do not substitute generated identifiers for any reason.
91936             // - We do not substitute identifiers tagged with the LocalName flag.
91937             // - We do not substitute identifiers that were originally the name of an enum or
91938             //   namespace due to how they are transformed in TypeScript.
91939             // - We only substitute identifiers that are exported at the top level.
91940             if (ts.isAssignmentOperator(node.operatorToken.kind)
91941                 && ts.isIdentifier(node.left)
91942                 && !ts.isGeneratedIdentifier(node.left)
91943                 && !ts.isLocalName(node.left)
91944                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
91945                 var exportedNames = getExports(node.left);
91946                 if (exportedNames) {
91947                     // For each additional export of the declaration, apply an export assignment.
91948                     var expression = node;
91949                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
91950                         var exportName = exportedNames_4[_i];
91951                         expression = createExportExpression(exportName, preventSubstitution(expression));
91952                     }
91953                     return expression;
91954                 }
91955             }
91956             return node;
91957         }
91958         /**
91959          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
91960          *
91961          * @param node The node to substitute.
91962          */
91963         function substituteUnaryExpression(node) {
91964             // When we see a prefix or postfix increment expression whose operand is an exported
91965             // symbol, we should ensure all exports of that symbol are updated with the correct
91966             // value.
91967             //
91968             // - We do not substitute generated identifiers for any reason.
91969             // - We do not substitute identifiers tagged with the LocalName flag.
91970             // - We do not substitute identifiers that were originally the name of an enum or
91971             //   namespace due to how they are transformed in TypeScript.
91972             // - We only substitute identifiers that are exported at the top level.
91973             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
91974                 && ts.isIdentifier(node.operand)
91975                 && !ts.isGeneratedIdentifier(node.operand)
91976                 && !ts.isLocalName(node.operand)
91977                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
91978                 var exportedNames = getExports(node.operand);
91979                 if (exportedNames) {
91980                     var expression = node.kind === 208 /* PostfixUnaryExpression */
91981                         ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
91982                         : node;
91983                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
91984                         var exportName = exportedNames_5[_i];
91985                         expression = createExportExpression(exportName, preventSubstitution(expression));
91986                     }
91987                     if (node.kind === 208 /* PostfixUnaryExpression */) {
91988                         expression = node.operator === 45 /* PlusPlusToken */
91989                             ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
91990                             : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
91991                     }
91992                     return expression;
91993                 }
91994             }
91995             return node;
91996         }
91997         function substituteMetaProperty(node) {
91998             if (ts.isImportMeta(node)) {
91999                 return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
92000             }
92001             return node;
92002         }
92003         /**
92004          * Gets the exports of a name.
92005          *
92006          * @param name The name.
92007          */
92008         function getExports(name) {
92009             var exportedNames;
92010             if (!ts.isGeneratedIdentifier(name)) {
92011                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
92012                     || resolver.getReferencedValueDeclaration(name);
92013                 if (valueDeclaration) {
92014                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
92015                     if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
92016                         exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
92017                     }
92018                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
92019                 }
92020             }
92021             return exportedNames;
92022         }
92023         /**
92024          * Prevent substitution of a node for this transformer.
92025          *
92026          * @param node The node which should not be substituted.
92027          */
92028         function preventSubstitution(node) {
92029             if (noSubstitution === undefined)
92030                 noSubstitution = [];
92031             noSubstitution[ts.getNodeId(node)] = true;
92032             return node;
92033         }
92034         /**
92035          * Determines whether a node should not be substituted.
92036          *
92037          * @param node The node to test.
92038          */
92039         function isSubstitutionPrevented(node) {
92040             return noSubstitution && node.id && noSubstitution[node.id];
92041         }
92042     }
92043     ts.transformSystemModule = transformSystemModule;
92044 })(ts || (ts = {}));
92045 /*@internal*/
92046 var ts;
92047 (function (ts) {
92048     function transformECMAScriptModule(context) {
92049         var compilerOptions = context.getCompilerOptions();
92050         var previousOnEmitNode = context.onEmitNode;
92051         var previousOnSubstituteNode = context.onSubstituteNode;
92052         context.onEmitNode = onEmitNode;
92053         context.onSubstituteNode = onSubstituteNode;
92054         context.enableEmitNotification(290 /* SourceFile */);
92055         context.enableSubstitution(75 /* Identifier */);
92056         var helperNameSubstitutions;
92057         return ts.chainBundle(transformSourceFile);
92058         function transformSourceFile(node) {
92059             if (node.isDeclarationFile) {
92060                 return node;
92061             }
92062             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
92063                 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
92064                 if (externalHelpersImportDeclaration) {
92065                     var statements = [];
92066                     var statementOffset = ts.addPrologue(statements, node.statements);
92067                     ts.append(statements, externalHelpersImportDeclaration);
92068                     ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
92069                     return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
92070                 }
92071                 else {
92072                     return ts.visitEachChild(node, visitor, context);
92073                 }
92074             }
92075             return node;
92076         }
92077         function visitor(node) {
92078             switch (node.kind) {
92079                 case 253 /* ImportEqualsDeclaration */:
92080                     // Elide `import=` as it is not legal with --module ES6
92081                     return undefined;
92082                 case 259 /* ExportAssignment */:
92083                     return visitExportAssignment(node);
92084                 case 260 /* ExportDeclaration */:
92085                     var exportDecl = node;
92086                     return visitExportDeclaration(exportDecl);
92087             }
92088             return node;
92089         }
92090         function visitExportAssignment(node) {
92091             // Elide `export=` as it is not legal with --module ES6
92092             return node.isExportEquals ? undefined : node;
92093         }
92094         function visitExportDeclaration(node) {
92095             // `export * as ns` only needs to be transformed in ES2015
92096             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
92097                 return node;
92098             }
92099             // Either ill-formed or don't need to be tranformed.
92100             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
92101                 return node;
92102             }
92103             var oldIdentifier = node.exportClause.name;
92104             var synthName = ts.getGeneratedNameForNode(oldIdentifier);
92105             var importDecl = ts.createImportDeclaration(
92106             /*decorators*/ undefined, 
92107             /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
92108             ts.setOriginalNode(importDecl, node.exportClause);
92109             var exportDecl = ts.createExportDeclaration(
92110             /*decorators*/ undefined, 
92111             /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
92112             ts.setOriginalNode(exportDecl, node);
92113             return [importDecl, exportDecl];
92114         }
92115         //
92116         // Emit Notification
92117         //
92118         /**
92119          * Hook for node emit.
92120          *
92121          * @param hint A hint as to the intended usage of the node.
92122          * @param node The node to emit.
92123          * @param emit A callback used to emit the node in the printer.
92124          */
92125         function onEmitNode(hint, node, emitCallback) {
92126             if (ts.isSourceFile(node)) {
92127                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
92128                     helperNameSubstitutions = ts.createMap();
92129                 }
92130                 previousOnEmitNode(hint, node, emitCallback);
92131                 helperNameSubstitutions = undefined;
92132             }
92133             else {
92134                 previousOnEmitNode(hint, node, emitCallback);
92135             }
92136         }
92137         //
92138         // Substitutions
92139         //
92140         /**
92141          * Hooks node substitutions.
92142          *
92143          * @param hint A hint as to the intended usage of the node.
92144          * @param node The node to substitute.
92145          */
92146         function onSubstituteNode(hint, node) {
92147             node = previousOnSubstituteNode(hint, node);
92148             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
92149                 return substituteHelperName(node);
92150             }
92151             return node;
92152         }
92153         function substituteHelperName(node) {
92154             var name = ts.idText(node);
92155             var substitution = helperNameSubstitutions.get(name);
92156             if (!substitution) {
92157                 helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
92158             }
92159             return substitution;
92160         }
92161     }
92162     ts.transformECMAScriptModule = transformECMAScriptModule;
92163 })(ts || (ts = {}));
92164 /* @internal */
92165 var ts;
92166 (function (ts) {
92167     function canProduceDiagnostics(node) {
92168         return ts.isVariableDeclaration(node) ||
92169             ts.isPropertyDeclaration(node) ||
92170             ts.isPropertySignature(node) ||
92171             ts.isBindingElement(node) ||
92172             ts.isSetAccessor(node) ||
92173             ts.isGetAccessor(node) ||
92174             ts.isConstructSignatureDeclaration(node) ||
92175             ts.isCallSignatureDeclaration(node) ||
92176             ts.isMethodDeclaration(node) ||
92177             ts.isMethodSignature(node) ||
92178             ts.isFunctionDeclaration(node) ||
92179             ts.isParameter(node) ||
92180             ts.isTypeParameterDeclaration(node) ||
92181             ts.isExpressionWithTypeArguments(node) ||
92182             ts.isImportEqualsDeclaration(node) ||
92183             ts.isTypeAliasDeclaration(node) ||
92184             ts.isConstructorDeclaration(node) ||
92185             ts.isIndexSignatureDeclaration(node) ||
92186             ts.isPropertyAccessExpression(node);
92187     }
92188     ts.canProduceDiagnostics = canProduceDiagnostics;
92189     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
92190         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92191             return getAccessorNameVisibilityError;
92192         }
92193         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
92194             return getMethodNameVisibilityError;
92195         }
92196         else {
92197             return createGetSymbolAccessibilityDiagnosticForNode(node);
92198         }
92199         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
92200             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92201             return diagnosticMessage !== undefined ? {
92202                 diagnosticMessage: diagnosticMessage,
92203                 errorNode: node,
92204                 typeName: node.name
92205             } : undefined;
92206         }
92207         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92208             if (ts.hasModifier(node, 32 /* Static */)) {
92209                 return symbolAccessibilityResult.errorModuleName ?
92210                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92211                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92212                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92213                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92214             }
92215             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92216                 return symbolAccessibilityResult.errorModuleName ?
92217                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92218                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92219                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92220                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92221             }
92222             else {
92223                 return symbolAccessibilityResult.errorModuleName ?
92224                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92225                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92226             }
92227         }
92228         function getMethodNameVisibilityError(symbolAccessibilityResult) {
92229             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92230             return diagnosticMessage !== undefined ? {
92231                 diagnosticMessage: diagnosticMessage,
92232                 errorNode: node,
92233                 typeName: node.name
92234             } : undefined;
92235         }
92236         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92237             if (ts.hasModifier(node, 32 /* Static */)) {
92238                 return symbolAccessibilityResult.errorModuleName ?
92239                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92240                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92241                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92242                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
92243             }
92244             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92245                 return symbolAccessibilityResult.errorModuleName ?
92246                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92247                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92248                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92249                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
92250             }
92251             else {
92252                 return symbolAccessibilityResult.errorModuleName ?
92253                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92254                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
92255             }
92256         }
92257     }
92258     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
92259     function createGetSymbolAccessibilityDiagnosticForNode(node) {
92260         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
92261             return getVariableDeclarationTypeVisibilityError;
92262         }
92263         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92264             return getAccessorDeclarationTypeVisibilityError;
92265         }
92266         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
92267             return getReturnTypeVisibilityError;
92268         }
92269         else if (ts.isParameter(node)) {
92270             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
92271                 return getVariableDeclarationTypeVisibilityError;
92272             }
92273             return getParameterDeclarationTypeVisibilityError;
92274         }
92275         else if (ts.isTypeParameterDeclaration(node)) {
92276             return getTypeParameterConstraintVisibilityError;
92277         }
92278         else if (ts.isExpressionWithTypeArguments(node)) {
92279             return getHeritageClauseVisibilityError;
92280         }
92281         else if (ts.isImportEqualsDeclaration(node)) {
92282             return getImportEntityNameVisibilityError;
92283         }
92284         else if (ts.isTypeAliasDeclaration(node)) {
92285             return getTypeAliasDeclarationVisibilityError;
92286         }
92287         else {
92288             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
92289         }
92290         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92291             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92292                 return symbolAccessibilityResult.errorModuleName ?
92293                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92294                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92295                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
92296                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
92297             }
92298             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
92299             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
92300             else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
92301                 (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
92302                 // TODO(jfreeman): Deal with computed properties in error reporting.
92303                 if (ts.hasModifier(node, 32 /* Static */)) {
92304                     return symbolAccessibilityResult.errorModuleName ?
92305                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92306                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92307                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92308                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92309                 }
92310                 else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
92311                     return symbolAccessibilityResult.errorModuleName ?
92312                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92313                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92314                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92315                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92316                 }
92317                 else {
92318                     // Interfaces cannot have types that cannot be named
92319                     return symbolAccessibilityResult.errorModuleName ?
92320                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92321                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92322                 }
92323             }
92324         }
92325         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92326             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92327             return diagnosticMessage !== undefined ? {
92328                 diagnosticMessage: diagnosticMessage,
92329                 errorNode: node,
92330                 typeName: node.name
92331             } : undefined;
92332         }
92333         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92334             var diagnosticMessage;
92335             if (node.kind === 164 /* SetAccessor */) {
92336                 // Getters can infer the return type from the returned expression, but setters cannot, so the
92337                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
92338                 if (ts.hasModifier(node, 32 /* Static */)) {
92339                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92340                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92341                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
92342                 }
92343                 else {
92344                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92345                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92346                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
92347                 }
92348             }
92349             else {
92350                 if (ts.hasModifier(node, 32 /* Static */)) {
92351                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92352                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92353                             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 :
92354                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92355                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
92356                 }
92357                 else {
92358                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92359                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92360                             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 :
92361                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92362                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
92363                 }
92364             }
92365             return {
92366                 diagnosticMessage: diagnosticMessage,
92367                 errorNode: node.name,
92368                 typeName: node.name
92369             };
92370         }
92371         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
92372             var diagnosticMessage;
92373             switch (node.kind) {
92374                 case 166 /* ConstructSignature */:
92375                     // Interfaces cannot have return types that cannot be named
92376                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92377                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92378                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
92379                     break;
92380                 case 165 /* CallSignature */:
92381                     // Interfaces cannot have return types that cannot be named
92382                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92383                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92384                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
92385                     break;
92386                 case 167 /* IndexSignature */:
92387                     // Interfaces cannot have return types that cannot be named
92388                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92389                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92390                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
92391                     break;
92392                 case 161 /* MethodDeclaration */:
92393                 case 160 /* MethodSignature */:
92394                     if (ts.hasModifier(node, 32 /* Static */)) {
92395                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92396                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92397                                 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 :
92398                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92399                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
92400                     }
92401                     else if (node.parent.kind === 245 /* ClassDeclaration */) {
92402                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92403                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92404                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92405                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92406                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
92407                     }
92408                     else {
92409                         // Interfaces cannot have return types that cannot be named
92410                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92411                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92412                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
92413                     }
92414                     break;
92415                 case 244 /* FunctionDeclaration */:
92416                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92417                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92418                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92419                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
92420                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
92421                     break;
92422                 default:
92423                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
92424             }
92425             return {
92426                 diagnosticMessage: diagnosticMessage,
92427                 errorNode: node.name || node
92428             };
92429         }
92430         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92431             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92432             return diagnosticMessage !== undefined ? {
92433                 diagnosticMessage: diagnosticMessage,
92434                 errorNode: node,
92435                 typeName: node.name
92436             } : undefined;
92437         }
92438         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92439             switch (node.parent.kind) {
92440                 case 162 /* Constructor */:
92441                     return symbolAccessibilityResult.errorModuleName ?
92442                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92443                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92444                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92445                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
92446                 case 166 /* ConstructSignature */:
92447                 case 171 /* ConstructorType */:
92448                     // Interfaces cannot have parameter types that cannot be named
92449                     return symbolAccessibilityResult.errorModuleName ?
92450                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92451                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92452                 case 165 /* CallSignature */:
92453                     // Interfaces cannot have parameter types that cannot be named
92454                     return symbolAccessibilityResult.errorModuleName ?
92455                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92456                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92457                 case 167 /* IndexSignature */:
92458                     // Interfaces cannot have parameter types that cannot be named
92459                     return symbolAccessibilityResult.errorModuleName ?
92460                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92461                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
92462                 case 161 /* MethodDeclaration */:
92463                 case 160 /* MethodSignature */:
92464                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92465                         return symbolAccessibilityResult.errorModuleName ?
92466                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92467                                 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 :
92468                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92469                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92470                     }
92471                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92472                         return symbolAccessibilityResult.errorModuleName ?
92473                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92474                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92475                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92476                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92477                     }
92478                     else {
92479                         // Interfaces cannot have parameter types that cannot be named
92480                         return symbolAccessibilityResult.errorModuleName ?
92481                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92482                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92483                     }
92484                 case 244 /* FunctionDeclaration */:
92485                 case 170 /* FunctionType */:
92486                     return symbolAccessibilityResult.errorModuleName ?
92487                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92488                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92489                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
92490                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
92491                 case 164 /* SetAccessor */:
92492                 case 163 /* GetAccessor */:
92493                     return symbolAccessibilityResult.errorModuleName ?
92494                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92495                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92496                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
92497                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
92498                 default:
92499                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
92500             }
92501         }
92502         function getTypeParameterConstraintVisibilityError() {
92503             // Type parameter constraints are named by user so we should always be able to name it
92504             var diagnosticMessage;
92505             switch (node.parent.kind) {
92506                 case 245 /* ClassDeclaration */:
92507                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
92508                     break;
92509                 case 246 /* InterfaceDeclaration */:
92510                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
92511                     break;
92512                 case 186 /* MappedType */:
92513                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
92514                     break;
92515                 case 171 /* ConstructorType */:
92516                 case 166 /* ConstructSignature */:
92517                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92518                     break;
92519                 case 165 /* CallSignature */:
92520                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92521                     break;
92522                 case 161 /* MethodDeclaration */:
92523                 case 160 /* MethodSignature */:
92524                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92525                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92526                     }
92527                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92528                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92529                     }
92530                     else {
92531                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92532                     }
92533                     break;
92534                 case 170 /* FunctionType */:
92535                 case 244 /* FunctionDeclaration */:
92536                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
92537                     break;
92538                 case 247 /* TypeAliasDeclaration */:
92539                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
92540                     break;
92541                 default:
92542                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
92543             }
92544             return {
92545                 diagnosticMessage: diagnosticMessage,
92546                 errorNode: node,
92547                 typeName: node.name
92548             };
92549         }
92550         function getHeritageClauseVisibilityError() {
92551             var diagnosticMessage;
92552             // Heritage clause is written by user so it can always be named
92553             if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92554                 // Class or Interface implemented/extended is inaccessible
92555                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
92556                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
92557                     ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
92558             }
92559             else {
92560                 // interface is inaccessible
92561                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
92562             }
92563             return {
92564                 diagnosticMessage: diagnosticMessage,
92565                 errorNode: node,
92566                 typeName: ts.getNameOfDeclaration(node.parent.parent)
92567             };
92568         }
92569         function getImportEntityNameVisibilityError() {
92570             return {
92571                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
92572                 errorNode: node,
92573                 typeName: node.name
92574             };
92575         }
92576         function getTypeAliasDeclarationVisibilityError() {
92577             return {
92578                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
92579                 errorNode: node.type,
92580                 typeName: node.name
92581             };
92582         }
92583     }
92584     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
92585 })(ts || (ts = {}));
92586 /*@internal*/
92587 var ts;
92588 (function (ts) {
92589     function getDeclarationDiagnostics(host, resolver, file) {
92590         if (file && ts.isJsonSourceFile(file)) {
92591             return []; // No declaration diagnostics for json for now
92592         }
92593         var compilerOptions = host.getCompilerOptions();
92594         var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
92595         return result.diagnostics;
92596     }
92597     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
92598     function hasInternalAnnotation(range, currentSourceFile) {
92599         var comment = currentSourceFile.text.substring(range.pos, range.end);
92600         return ts.stringContains(comment, "@internal");
92601     }
92602     function isInternalDeclaration(node, currentSourceFile) {
92603         var parseTreeNode = ts.getParseTreeNode(node);
92604         if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
92605             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
92606             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
92607             var text = currentSourceFile.text;
92608             var commentRanges = previousSibling
92609                 ? ts.concatenate(
92610                 // to handle
92611                 // ... parameters, /* @internal */
92612                 // public param: string
92613                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
92614                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
92615             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
92616         }
92617         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
92618         return !!ts.forEach(leadingCommentRanges, function (range) {
92619             return hasInternalAnnotation(range, currentSourceFile);
92620         });
92621     }
92622     ts.isInternalDeclaration = isInternalDeclaration;
92623     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
92624         2048 /* WriteClassExpressionAsTypeLiteral */ |
92625         4096 /* UseTypeOfFunction */ |
92626         8 /* UseStructuralFallback */ |
92627         524288 /* AllowEmptyTuple */ |
92628         4 /* GenerateNamesForShadowedTypeParams */ |
92629         1 /* NoTruncation */;
92630     /**
92631      * Transforms a ts file into a .d.ts file
92632      * This process requires type information, which is retrieved through the emit resolver. Because of this,
92633      * in many places this transformer assumes it will be operating on parse tree nodes directly.
92634      * This means that _no transforms should be allowed to occur before this one_.
92635      */
92636     function transformDeclarations(context) {
92637         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
92638         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
92639         var needsDeclare = true;
92640         var isBundledEmit = false;
92641         var resultHasExternalModuleIndicator = false;
92642         var needsScopeFixMarker = false;
92643         var resultHasScopeMarker = false;
92644         var enclosingDeclaration;
92645         var necessaryTypeReferences;
92646         var lateMarkedStatements;
92647         var lateStatementReplacementMap;
92648         var suppressNewDiagnosticContexts;
92649         var exportedModulesFromDeclarationEmit;
92650         var host = context.getEmitHost();
92651         var symbolTracker = {
92652             trackSymbol: trackSymbol,
92653             reportInaccessibleThisError: reportInaccessibleThisError,
92654             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
92655             reportCyclicStructureError: reportCyclicStructureError,
92656             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
92657             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
92658             moduleResolverHost: host,
92659             trackReferencedAmbientModule: trackReferencedAmbientModule,
92660             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
92661             reportNonlocalAugmentation: reportNonlocalAugmentation
92662         };
92663         var errorNameNode;
92664         var currentSourceFile;
92665         var refs;
92666         var libs;
92667         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
92668         var resolver = context.getEmitResolver();
92669         var options = context.getCompilerOptions();
92670         var noResolve = options.noResolve, stripInternal = options.stripInternal;
92671         return transformRoot;
92672         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
92673             if (!typeReferenceDirectives) {
92674                 return;
92675             }
92676             necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
92677             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
92678                 var ref = typeReferenceDirectives_2[_i];
92679                 necessaryTypeReferences.set(ref, true);
92680             }
92681         }
92682         function trackReferencedAmbientModule(node, symbol) {
92683             // If it is visible via `// <reference types="..."/>`, then we should just use that
92684             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
92685             if (ts.length(directives)) {
92686                 return recordTypeReferenceDirectivesIfNecessary(directives);
92687             }
92688             // Otherwise we should emit a path-based reference
92689             var container = ts.getSourceFileOfNode(node);
92690             refs.set("" + ts.getOriginalNodeId(container), container);
92691         }
92692         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
92693             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
92694                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
92695                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
92696                     if (!lateMarkedStatements) {
92697                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
92698                     }
92699                     else {
92700                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
92701                             var ref = _a[_i];
92702                             ts.pushIfUnique(lateMarkedStatements, ref);
92703                         }
92704                     }
92705                 }
92706                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
92707             }
92708             else {
92709                 // Report error
92710                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
92711                 if (errorInfo) {
92712                     if (errorInfo.typeName) {
92713                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92714                     }
92715                     else {
92716                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92717                     }
92718                 }
92719             }
92720         }
92721         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
92722             if (!isBundledEmit) {
92723                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92724             }
92725         }
92726         function trackSymbol(symbol, enclosingDeclaration, meaning) {
92727             if (symbol.flags & 262144 /* TypeParameter */)
92728                 return;
92729             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
92730             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
92731         }
92732         function reportPrivateInBaseOfClassExpression(propertyName) {
92733             if (errorNameNode) {
92734                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
92735             }
92736         }
92737         function reportInaccessibleUniqueSymbolError() {
92738             if (errorNameNode) {
92739                 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"));
92740             }
92741         }
92742         function reportCyclicStructureError() {
92743             if (errorNameNode) {
92744                 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)));
92745             }
92746         }
92747         function reportInaccessibleThisError() {
92748             if (errorNameNode) {
92749                 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"));
92750             }
92751         }
92752         function reportLikelyUnsafeImportRequiredError(specifier) {
92753             if (errorNameNode) {
92754                 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));
92755             }
92756         }
92757         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
92758             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
92759             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
92760             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
92761                 var augmentations = augmentingDeclarations_1[_i];
92762                 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)));
92763             }
92764         }
92765         function transformDeclarationsForJS(sourceFile, bundled) {
92766             var oldDiag = getSymbolAccessibilityDiagnostic;
92767             getSymbolAccessibilityDiagnostic = function (s) { return ({
92768                 diagnosticMessage: s.errorModuleName
92769                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
92770                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
92771                 errorNode: s.errorNode || sourceFile
92772             }); };
92773             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
92774             getSymbolAccessibilityDiagnostic = oldDiag;
92775             return result;
92776         }
92777         function transformRoot(node) {
92778             if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
92779                 return node;
92780             }
92781             if (node.kind === 291 /* Bundle */) {
92782                 isBundledEmit = true;
92783                 refs = ts.createMap();
92784                 libs = ts.createMap();
92785                 var hasNoDefaultLib_1 = false;
92786                 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
92787                     if (sourceFile.isDeclarationFile)
92788                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
92789                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
92790                     currentSourceFile = sourceFile;
92791                     enclosingDeclaration = sourceFile;
92792                     lateMarkedStatements = undefined;
92793                     suppressNewDiagnosticContexts = false;
92794                     lateStatementReplacementMap = ts.createMap();
92795                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
92796                     needsScopeFixMarker = false;
92797                     resultHasScopeMarker = false;
92798                     collectReferences(sourceFile, refs);
92799                     collectLibs(sourceFile, libs);
92800                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
92801                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
92802                         needsDeclare = false;
92803                         var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92804                         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*/ []);
92805                         return newFile;
92806                     }
92807                     needsDeclare = true;
92808                     var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92809                     return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92810                 }), ts.mapDefined(node.prepends, function (prepend) {
92811                     if (prepend.kind === 293 /* InputFiles */) {
92812                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
92813                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
92814                         collectReferences(sourceFile, refs);
92815                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
92816                         collectLibs(sourceFile, libs);
92817                         return sourceFile;
92818                     }
92819                     return prepend;
92820                 }));
92821                 bundle.syntheticFileReferences = [];
92822                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
92823                 bundle.syntheticLibReferences = getLibReferences();
92824                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
92825                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92826                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
92827                 refs.forEach(referenceVisitor_1);
92828                 return bundle;
92829             }
92830             // Single source file
92831             needsDeclare = true;
92832             needsScopeFixMarker = false;
92833             resultHasScopeMarker = false;
92834             enclosingDeclaration = node;
92835             currentSourceFile = node;
92836             getSymbolAccessibilityDiagnostic = throwDiagnostic;
92837             isBundledEmit = false;
92838             resultHasExternalModuleIndicator = false;
92839             suppressNewDiagnosticContexts = false;
92840             lateMarkedStatements = undefined;
92841             lateStatementReplacementMap = ts.createMap();
92842             necessaryTypeReferences = undefined;
92843             refs = collectReferences(currentSourceFile, ts.createMap());
92844             libs = collectLibs(currentSourceFile, ts.createMap());
92845             var references = [];
92846             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92847             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
92848             var combinedStatements;
92849             if (ts.isSourceFileJS(currentSourceFile)) {
92850                 combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
92851                 refs.forEach(referenceVisitor);
92852                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92853             }
92854             else {
92855                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
92856                 combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
92857                 refs.forEach(referenceVisitor);
92858                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92859                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
92860                     combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
92861                 }
92862             }
92863             var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
92864             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
92865             return updated;
92866             function getLibReferences() {
92867                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
92868             }
92869             function getFileReferencesForUsedTypeReferences() {
92870                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
92871             }
92872             function getFileReferenceForTypeName(typeName) {
92873                 // Elide type references for which we have imports
92874                 if (emittedImports) {
92875                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
92876                         var importStatement = emittedImports_1[_i];
92877                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
92878                             var expr = importStatement.moduleReference.expression;
92879                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
92880                                 return undefined;
92881                             }
92882                         }
92883                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
92884                             return undefined;
92885                         }
92886                     }
92887                 }
92888                 return { fileName: typeName, pos: -1, end: -1 };
92889             }
92890             function mapReferencesIntoArray(references, outputFilePath) {
92891                 return function (file) {
92892                     var declFileName;
92893                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
92894                         declFileName = file.fileName;
92895                     }
92896                     else {
92897                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
92898                             return; // Omit references to files which are being merged
92899                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
92900                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
92901                     }
92902                     if (declFileName) {
92903                         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, 
92904                         /*preferences*/ undefined);
92905                         if (!ts.pathIsRelative(specifier)) {
92906                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
92907                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
92908                             // a relative path to the declaration file
92909                             recordTypeReferenceDirectivesIfNecessary([specifier]);
92910                             return;
92911                         }
92912                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
92913                         /*isAbsolutePathAnUrl*/ false);
92914                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
92915                             fileName = fileName.substring(2);
92916                         }
92917                         // omit references to files from node_modules (npm may disambiguate module
92918                         // references when installing this package, making the path is unreliable).
92919                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
92920                             return;
92921                         }
92922                         references.push({ pos: -1, end: -1, fileName: fileName });
92923                     }
92924                 };
92925             }
92926         }
92927         function collectReferences(sourceFile, ret) {
92928             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
92929                 return ret;
92930             ts.forEach(sourceFile.referencedFiles, function (f) {
92931                 var elem = host.getSourceFileFromReference(sourceFile, f);
92932                 if (elem) {
92933                     ret.set("" + ts.getOriginalNodeId(elem), elem);
92934                 }
92935             });
92936             return ret;
92937         }
92938         function collectLibs(sourceFile, ret) {
92939             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
92940                 var lib = host.getLibFileFromReference(ref);
92941                 if (lib) {
92942                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
92943                 }
92944             });
92945             return ret;
92946         }
92947         function filterBindingPatternInitializers(name) {
92948             if (name.kind === 75 /* Identifier */) {
92949                 return name;
92950             }
92951             else {
92952                 if (name.kind === 190 /* ArrayBindingPattern */) {
92953                     return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92954                 }
92955                 else {
92956                     return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92957                 }
92958             }
92959             function visitBindingElement(elem) {
92960                 if (elem.kind === 215 /* OmittedExpression */) {
92961                     return elem;
92962                 }
92963                 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
92964             }
92965         }
92966         function ensureParameter(p, modifierMask, type) {
92967             var oldDiag;
92968             if (!suppressNewDiagnosticContexts) {
92969                 oldDiag = getSymbolAccessibilityDiagnostic;
92970                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
92971             }
92972             var newParam = ts.updateParameter(p, 
92973             /*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
92974             ensureNoInitializer(p));
92975             if (!suppressNewDiagnosticContexts) {
92976                 getSymbolAccessibilityDiagnostic = oldDiag;
92977             }
92978             return newParam;
92979         }
92980         function shouldPrintWithInitializer(node) {
92981             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
92982         }
92983         function ensureNoInitializer(node) {
92984             if (shouldPrintWithInitializer(node)) {
92985                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
92986             }
92987             return undefined;
92988         }
92989         function ensureType(node, type, ignorePrivate) {
92990             if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
92991                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
92992                 return;
92993             }
92994             if (shouldPrintWithInitializer(node)) {
92995                 // Literal const declarations will have an initializer ensured rather than a type
92996                 return;
92997             }
92998             var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
92999                 (resolver.isRequiredInitializedParameter(node) ||
93000                     resolver.isOptionalUninitializedParameterProperty(node));
93001             if (type && !shouldUseResolverType) {
93002                 return ts.visitNode(type, visitDeclarationSubtree);
93003             }
93004             if (!ts.getParseTreeNode(node)) {
93005                 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
93006             }
93007             if (node.kind === 164 /* SetAccessor */) {
93008                 // 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
93009                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
93010                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
93011             }
93012             errorNameNode = node.name;
93013             var oldDiag;
93014             if (!suppressNewDiagnosticContexts) {
93015                 oldDiag = getSymbolAccessibilityDiagnostic;
93016                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
93017             }
93018             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
93019                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
93020             }
93021             if (node.kind === 156 /* Parameter */
93022                 || node.kind === 159 /* PropertyDeclaration */
93023                 || node.kind === 158 /* PropertySignature */) {
93024                 if (!node.initializer)
93025                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
93026                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
93027             }
93028             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
93029             function cleanup(returnValue) {
93030                 errorNameNode = undefined;
93031                 if (!suppressNewDiagnosticContexts) {
93032                     getSymbolAccessibilityDiagnostic = oldDiag;
93033                 }
93034                 return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
93035             }
93036         }
93037         function isDeclarationAndNotVisible(node) {
93038             node = ts.getParseTreeNode(node);
93039             switch (node.kind) {
93040                 case 244 /* FunctionDeclaration */:
93041                 case 249 /* ModuleDeclaration */:
93042                 case 246 /* InterfaceDeclaration */:
93043                 case 245 /* ClassDeclaration */:
93044                 case 247 /* TypeAliasDeclaration */:
93045                 case 248 /* EnumDeclaration */:
93046                     return !resolver.isDeclarationVisible(node);
93047                 // The following should be doing their own visibility checks based on filtering their members
93048                 case 242 /* VariableDeclaration */:
93049                     return !getBindingNameVisible(node);
93050                 case 253 /* ImportEqualsDeclaration */:
93051                 case 254 /* ImportDeclaration */:
93052                 case 260 /* ExportDeclaration */:
93053                 case 259 /* ExportAssignment */:
93054                     return false;
93055             }
93056             return false;
93057         }
93058         function getBindingNameVisible(elem) {
93059             if (ts.isOmittedExpression(elem)) {
93060                 return false;
93061             }
93062             if (ts.isBindingPattern(elem.name)) {
93063                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
93064                 return ts.some(elem.name.elements, getBindingNameVisible);
93065             }
93066             else {
93067                 return resolver.isDeclarationVisible(elem);
93068             }
93069         }
93070         function updateParamsList(node, params, modifierMask) {
93071             if (ts.hasModifier(node, 8 /* Private */)) {
93072                 return undefined; // TODO: GH#18217
93073             }
93074             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
93075             if (!newParams) {
93076                 return undefined; // TODO: GH#18217
93077             }
93078             return ts.createNodeArray(newParams, params.hasTrailingComma);
93079         }
93080         function updateAccessorParamsList(input, isPrivate) {
93081             var newParams;
93082             if (!isPrivate) {
93083                 var thisParameter = ts.getThisParameter(input);
93084                 if (thisParameter) {
93085                     newParams = [ensureParameter(thisParameter)];
93086                 }
93087             }
93088             if (ts.isSetAccessorDeclaration(input)) {
93089                 var newValueParameter = void 0;
93090                 if (!isPrivate) {
93091                     var valueParameter = ts.getSetAccessorValueParameter(input);
93092                     if (valueParameter) {
93093                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93094                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
93095                     }
93096                 }
93097                 if (!newValueParameter) {
93098                     newValueParameter = ts.createParameter(
93099                     /*decorators*/ undefined, 
93100                     /*modifiers*/ undefined, 
93101                     /*dotDotDotToken*/ undefined, "value");
93102                 }
93103                 newParams = ts.append(newParams, newValueParameter);
93104             }
93105             return ts.createNodeArray(newParams || ts.emptyArray);
93106         }
93107         function ensureTypeParams(node, params) {
93108             return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
93109         }
93110         function isEnclosingDeclaration(node) {
93111             return ts.isSourceFile(node)
93112                 || ts.isTypeAliasDeclaration(node)
93113                 || ts.isModuleDeclaration(node)
93114                 || ts.isClassDeclaration(node)
93115                 || ts.isInterfaceDeclaration(node)
93116                 || ts.isFunctionLike(node)
93117                 || ts.isIndexSignatureDeclaration(node)
93118                 || ts.isMappedTypeNode(node);
93119         }
93120         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
93121             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
93122             handleSymbolAccessibilityError(visibilityResult);
93123             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
93124         }
93125         function preserveJsDoc(updated, original) {
93126             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
93127                 updated.jsDoc = original.jsDoc;
93128             }
93129             return ts.setCommentRange(updated, ts.getCommentRange(original));
93130         }
93131         function rewriteModuleSpecifier(parent, input) {
93132             if (!input)
93133                 return undefined; // TODO: GH#18217
93134             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
93135             if (ts.isStringLiteralLike(input)) {
93136                 if (isBundledEmit) {
93137                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
93138                     if (newName) {
93139                         return ts.createLiteral(newName);
93140                     }
93141                 }
93142                 else {
93143                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
93144                     if (symbol) {
93145                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
93146                     }
93147                 }
93148             }
93149             return input;
93150         }
93151         function transformImportEqualsDeclaration(decl) {
93152             if (!resolver.isDeclarationVisible(decl))
93153                 return;
93154             if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
93155                 // Rewrite external module names if necessary
93156                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
93157                 return ts.updateImportEqualsDeclaration(decl, 
93158                 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
93159             }
93160             else {
93161                 var oldDiag = getSymbolAccessibilityDiagnostic;
93162                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
93163                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
93164                 getSymbolAccessibilityDiagnostic = oldDiag;
93165                 return decl;
93166             }
93167         }
93168         function transformImportDeclaration(decl) {
93169             if (!decl.importClause) {
93170                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
93171                 return ts.updateImportDeclaration(decl, 
93172                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93173             }
93174             // The `importClause` visibility corresponds to the default's visibility.
93175             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
93176             if (!decl.importClause.namedBindings) {
93177                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
93178                 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
93179                 /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93180             }
93181             if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
93182                 // Namespace import (optionally with visible default)
93183                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
93184                 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
93185             }
93186             // Named imports (optionally with visible default)
93187             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
93188             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
93189                 return ts.updateImportDeclaration(decl, 
93190                 /*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));
93191             }
93192             // Augmentation of export depends on import
93193             if (resolver.isImportRequiredByAugmentation(decl)) {
93194                 return ts.updateImportDeclaration(decl, 
93195                 /*decorators*/ undefined, decl.modifiers, 
93196                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93197             }
93198             // Nothing visible
93199         }
93200         function transformAndReplaceLatePaintedStatements(statements) {
93201             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
93202             // error handling which must now be included in the output and themselves checked for errors.
93203             // For example:
93204             // ```
93205             // module A {
93206             //   export module Q {}
93207             //   import B = Q;
93208             //   import C = B;
93209             //   export import D = C;
93210             // }
93211             // ```
93212             // 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
93213             // 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
93214             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
93215             while (ts.length(lateMarkedStatements)) {
93216                 var i = lateMarkedStatements.shift();
93217                 if (!ts.isLateVisibilityPaintedStatement(i)) {
93218                     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));
93219                 }
93220                 var priorNeedsDeclare = needsDeclare;
93221                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
93222                 var result = transformTopLevelDeclaration(i);
93223                 needsDeclare = priorNeedsDeclare;
93224                 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
93225             }
93226             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
93227             // (and remove them from the set to examine for outter declarations)
93228             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
93229             function visitLateVisibilityMarkedStatements(statement) {
93230                 if (ts.isLateVisibilityPaintedStatement(statement)) {
93231                     var key = "" + ts.getOriginalNodeId(statement);
93232                     if (lateStatementReplacementMap.has(key)) {
93233                         var result = lateStatementReplacementMap.get(key);
93234                         lateStatementReplacementMap.delete(key);
93235                         if (result) {
93236                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
93237                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
93238                                 needsScopeFixMarker = true;
93239                             }
93240                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
93241                                 resultHasExternalModuleIndicator = true;
93242                             }
93243                         }
93244                         return result;
93245                     }
93246                 }
93247                 return statement;
93248             }
93249         }
93250         function visitDeclarationSubtree(input) {
93251             if (shouldStripInternal(input))
93252                 return;
93253             if (ts.isDeclaration(input)) {
93254                 if (isDeclarationAndNotVisible(input))
93255                     return;
93256                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
93257                     return;
93258                 }
93259             }
93260             // Elide implementation signatures from overload sets
93261             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93262                 return;
93263             // Elide semicolon class statements
93264             if (ts.isSemicolonClassElement(input))
93265                 return;
93266             var previousEnclosingDeclaration;
93267             if (isEnclosingDeclaration(input)) {
93268                 previousEnclosingDeclaration = enclosingDeclaration;
93269                 enclosingDeclaration = input;
93270             }
93271             var oldDiag = getSymbolAccessibilityDiagnostic;
93272             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
93273             // We'd see a TDZ violation at runtime
93274             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
93275             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
93276             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
93277             // Emit methods which are private as properties with no type information
93278             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
93279                 if (ts.hasModifier(input, 8 /* Private */)) {
93280                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
93281                         return; // Elide all but the first overload
93282                     return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
93283                 }
93284             }
93285             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93286                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93287             }
93288             if (ts.isTypeQueryNode(input)) {
93289                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
93290             }
93291             if (shouldEnterSuppressNewDiagnosticsContextContext) {
93292                 // 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.
93293                 suppressNewDiagnosticContexts = true;
93294             }
93295             if (isProcessedComponent(input)) {
93296                 switch (input.kind) {
93297                     case 216 /* ExpressionWithTypeArguments */: {
93298                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
93299                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
93300                         }
93301                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93302                         return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
93303                     }
93304                     case 169 /* TypeReference */: {
93305                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
93306                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93307                         return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
93308                     }
93309                     case 166 /* ConstructSignature */:
93310                         return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93311                     case 162 /* Constructor */: {
93312                         // A constructor declaration may not have a type annotation
93313                         var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */), 
93314                         /*type*/ undefined);
93315                         ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
93316                         return cleanup(ctor);
93317                     }
93318                     case 161 /* MethodDeclaration */: {
93319                         if (ts.isPrivateIdentifier(input.name)) {
93320                             return cleanup(/*returnValue*/ undefined);
93321                         }
93322                         var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
93323                         sig.name = input.name;
93324                         sig.modifiers = ts.createNodeArray(ensureModifiers(input));
93325                         sig.questionToken = input.questionToken;
93326                         return cleanup(sig);
93327                     }
93328                     case 163 /* GetAccessor */: {
93329                         if (ts.isPrivateIdentifier(input.name)) {
93330                             return cleanup(/*returnValue*/ undefined);
93331                         }
93332                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93333                         return cleanup(ts.updateGetAccessor(input, 
93334                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
93335                         /*body*/ undefined));
93336                     }
93337                     case 164 /* SetAccessor */: {
93338                         if (ts.isPrivateIdentifier(input.name)) {
93339                             return cleanup(/*returnValue*/ undefined);
93340                         }
93341                         return cleanup(ts.updateSetAccessor(input, 
93342                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), 
93343                         /*body*/ undefined));
93344                     }
93345                     case 159 /* PropertyDeclaration */:
93346                         if (ts.isPrivateIdentifier(input.name)) {
93347                             return cleanup(/*returnValue*/ undefined);
93348                         }
93349                         return cleanup(ts.updateProperty(input, 
93350                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93351                     case 158 /* PropertySignature */:
93352                         if (ts.isPrivateIdentifier(input.name)) {
93353                             return cleanup(/*returnValue*/ undefined);
93354                         }
93355                         return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93356                     case 160 /* MethodSignature */: {
93357                         if (ts.isPrivateIdentifier(input.name)) {
93358                             return cleanup(/*returnValue*/ undefined);
93359                         }
93360                         return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
93361                     }
93362                     case 165 /* CallSignature */: {
93363                         return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93364                     }
93365                     case 167 /* IndexSignature */: {
93366                         return cleanup(ts.updateIndexSignature(input, 
93367                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
93368                     }
93369                     case 242 /* VariableDeclaration */: {
93370                         if (ts.isBindingPattern(input.name)) {
93371                             return recreateBindingPattern(input.name);
93372                         }
93373                         shouldEnterSuppressNewDiagnosticsContextContext = true;
93374                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
93375                         return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
93376                     }
93377                     case 155 /* TypeParameter */: {
93378                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
93379                             return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
93380                         }
93381                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93382                     }
93383                     case 180 /* ConditionalType */: {
93384                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
93385                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
93386                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
93387                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
93388                         var oldEnclosingDecl = enclosingDeclaration;
93389                         enclosingDeclaration = input.trueType;
93390                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
93391                         enclosingDeclaration = oldEnclosingDecl;
93392                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
93393                         return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
93394                     }
93395                     case 170 /* FunctionType */: {
93396                         return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93397                     }
93398                     case 171 /* ConstructorType */: {
93399                         return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93400                     }
93401                     case 188 /* ImportType */: {
93402                         if (!ts.isLiteralImportTypeNode(input))
93403                             return cleanup(input);
93404                         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));
93405                     }
93406                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
93407                 }
93408             }
93409             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93410             function cleanup(returnValue) {
93411                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
93412                     checkName(input);
93413                 }
93414                 if (isEnclosingDeclaration(input)) {
93415                     enclosingDeclaration = previousEnclosingDeclaration;
93416                 }
93417                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93418                     getSymbolAccessibilityDiagnostic = oldDiag;
93419                 }
93420                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
93421                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
93422                 }
93423                 if (returnValue === input) {
93424                     return returnValue;
93425                 }
93426                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
93427             }
93428         }
93429         function isPrivateMethodTypeParameter(node) {
93430             return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
93431         }
93432         function visitDeclarationStatements(input) {
93433             if (!isPreservedDeclarationStatement(input)) {
93434                 // return undefined for unmatched kinds to omit them from the tree
93435                 return;
93436             }
93437             if (shouldStripInternal(input))
93438                 return;
93439             switch (input.kind) {
93440                 case 260 /* ExportDeclaration */: {
93441                     if (ts.isSourceFile(input.parent)) {
93442                         resultHasExternalModuleIndicator = true;
93443                     }
93444                     resultHasScopeMarker = true;
93445                     // Always visible if the parent node isn't dropped for being not visible
93446                     // Rewrite external module names if necessary
93447                     return ts.updateExportDeclaration(input, 
93448                     /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
93449                 }
93450                 case 259 /* ExportAssignment */: {
93451                     // Always visible if the parent node isn't dropped for being not visible
93452                     if (ts.isSourceFile(input.parent)) {
93453                         resultHasExternalModuleIndicator = true;
93454                     }
93455                     resultHasScopeMarker = true;
93456                     if (input.expression.kind === 75 /* Identifier */) {
93457                         return input;
93458                     }
93459                     else {
93460                         var newId = ts.createOptimisticUniqueName("_default");
93461                         getSymbolAccessibilityDiagnostic = function () { return ({
93462                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
93463                             errorNode: input
93464                         }); };
93465                         var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93466                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93467                         return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
93468                     }
93469                 }
93470             }
93471             var result = transformTopLevelDeclaration(input);
93472             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
93473             lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
93474             return input;
93475         }
93476         function stripExportModifiers(statement) {
93477             if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
93478                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
93479                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
93480                 return statement;
93481             }
93482             var clone = ts.getMutableClone(statement);
93483             var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
93484             clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
93485             return clone;
93486         }
93487         function transformTopLevelDeclaration(input) {
93488             if (shouldStripInternal(input))
93489                 return;
93490             switch (input.kind) {
93491                 case 253 /* ImportEqualsDeclaration */: {
93492                     return transformImportEqualsDeclaration(input);
93493                 }
93494                 case 254 /* ImportDeclaration */: {
93495                     return transformImportDeclaration(input);
93496                 }
93497             }
93498             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
93499                 return;
93500             // Elide implementation signatures from overload sets
93501             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93502                 return;
93503             var previousEnclosingDeclaration;
93504             if (isEnclosingDeclaration(input)) {
93505                 previousEnclosingDeclaration = enclosingDeclaration;
93506                 enclosingDeclaration = input;
93507             }
93508             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
93509             var oldDiag = getSymbolAccessibilityDiagnostic;
93510             if (canProdiceDiagnostic) {
93511                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93512             }
93513             var previousNeedsDeclare = needsDeclare;
93514             switch (input.kind) {
93515                 case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
93516                     return cleanup(ts.updateTypeAliasDeclaration(input, 
93517                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
93518                 case 246 /* InterfaceDeclaration */: {
93519                     return cleanup(ts.updateInterfaceDeclaration(input, 
93520                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
93521                 }
93522                 case 244 /* FunctionDeclaration */: {
93523                     // Generators lose their generator-ness, excepting their return type
93524                     var clean = cleanup(ts.updateFunctionDeclaration(input, 
93525                     /*decorators*/ undefined, ensureModifiers(input), 
93526                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
93527                     /*body*/ undefined));
93528                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
93529                         var props = resolver.getPropertiesOfContainerFunction(input);
93530                         var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
93531                         fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
93532                         fakespace_1.parent = enclosingDeclaration;
93533                         fakespace_1.locals = ts.createSymbolTable(props);
93534                         fakespace_1.symbol = props[0].parent;
93535                         var declarations = ts.mapDefined(props, function (p) {
93536                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
93537                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
93538                             }
93539                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
93540                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
93541                             getSymbolAccessibilityDiagnostic = oldDiag;
93542                             var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
93543                             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
93544                         });
93545                         var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
93546                         if (!ts.hasModifier(clean, 512 /* Default */)) {
93547                             return [clean, namespaceDecl];
93548                         }
93549                         var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
93550                         var cleanDeclaration = ts.updateFunctionDeclaration(clean, 
93551                         /*decorators*/ undefined, modifiers, 
93552                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
93553                         /*body*/ undefined);
93554                         var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl, 
93555                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
93556                         var exportDefaultDeclaration = ts.createExportAssignment(
93557                         /*decorators*/ undefined, 
93558                         /*modifiers*/ undefined, 
93559                         /*isExportEquals*/ false, namespaceDecl.name);
93560                         if (ts.isSourceFile(input.parent)) {
93561                             resultHasExternalModuleIndicator = true;
93562                         }
93563                         resultHasScopeMarker = true;
93564                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
93565                     }
93566                     else {
93567                         return clean;
93568                     }
93569                 }
93570                 case 249 /* ModuleDeclaration */: {
93571                     needsDeclare = false;
93572                     var inner = input.body;
93573                     if (inner && inner.kind === 250 /* ModuleBlock */) {
93574                         var oldNeedsScopeFix = needsScopeFixMarker;
93575                         var oldHasScopeFix = resultHasScopeMarker;
93576                         resultHasScopeMarker = false;
93577                         needsScopeFixMarker = false;
93578                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
93579                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
93580                         if (input.flags & 8388608 /* Ambient */) {
93581                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
93582                         }
93583                         // With the final list of statements, there are 3 possibilities:
93584                         // 1. There's an export assignment or export declaration in the namespace - do nothing
93585                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
93586                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
93587                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
93588                             if (needsScopeFixMarker) {
93589                                 lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
93590                             }
93591                             else {
93592                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
93593                             }
93594                         }
93595                         var body = ts.updateModuleBlock(inner, lateStatements);
93596                         needsDeclare = previousNeedsDeclare;
93597                         needsScopeFixMarker = oldNeedsScopeFix;
93598                         resultHasScopeMarker = oldHasScopeFix;
93599                         var mods = ensureModifiers(input);
93600                         return cleanup(ts.updateModuleDeclaration(input, 
93601                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
93602                     }
93603                     else {
93604                         needsDeclare = previousNeedsDeclare;
93605                         var mods = ensureModifiers(input);
93606                         needsDeclare = false;
93607                         ts.visitNode(inner, visitDeclarationStatements);
93608                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
93609                         var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
93610                         var body = lateStatementReplacementMap.get(id);
93611                         lateStatementReplacementMap.delete(id);
93612                         return cleanup(ts.updateModuleDeclaration(input, 
93613                         /*decorators*/ undefined, mods, input.name, body));
93614                     }
93615                 }
93616                 case 245 /* ClassDeclaration */: {
93617                     var modifiers = ts.createNodeArray(ensureModifiers(input));
93618                     var typeParameters = ensureTypeParams(input, input.typeParameters);
93619                     var ctor = ts.getFirstConstructorWithBody(input);
93620                     var parameterProperties = void 0;
93621                     if (ctor) {
93622                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
93623                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
93624                             if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
93625                                 return;
93626                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
93627                             if (param.name.kind === 75 /* Identifier */) {
93628                                 return preserveJsDoc(ts.createProperty(
93629                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
93630                             }
93631                             else {
93632                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
93633                                 return walkBindingPattern(param.name);
93634                             }
93635                             function walkBindingPattern(pattern) {
93636                                 var elems;
93637                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
93638                                     var elem = _a[_i];
93639                                     if (ts.isOmittedExpression(elem))
93640                                         continue;
93641                                     if (ts.isBindingPattern(elem.name)) {
93642                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
93643                                     }
93644                                     elems = elems || [];
93645                                     elems.push(ts.createProperty(
93646                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
93647                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
93648                                     /*initializer*/ undefined));
93649                                 }
93650                                 return elems;
93651                             }
93652                         }));
93653                         getSymbolAccessibilityDiagnostic = oldDiag_1;
93654                     }
93655                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
93656                     var privateIdentifier = hasPrivateIdentifier ? [
93657                         ts.createProperty(
93658                         /*decorators*/ undefined, 
93659                         /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
93660                         /*questionToken*/ undefined, 
93661                         /*type*/ undefined, 
93662                         /*initializer*/ undefined)
93663                     ] : undefined;
93664                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
93665                     var members = ts.createNodeArray(memberNodes);
93666                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
93667                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
93668                         // We must add a temporary declaration for the extends clause expression
93669                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
93670                         var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
93671                         getSymbolAccessibilityDiagnostic = function () { return ({
93672                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
93673                             errorNode: extendsClause_1,
93674                             typeName: input.name
93675                         }); };
93676                         var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93677                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93678                         var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
93679                             if (clause.token === 90 /* ExtendsKeyword */) {
93680                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
93681                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
93682                                 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
93683                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
93684                                 return newClause;
93685                             }
93686                             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));
93687                         }));
93688                         return [statement, cleanup(ts.updateClassDeclaration(input, 
93689                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
93690                     }
93691                     else {
93692                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
93693                         return cleanup(ts.updateClassDeclaration(input, 
93694                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
93695                     }
93696                 }
93697                 case 225 /* VariableStatement */: {
93698                     return cleanup(transformVariableStatement(input));
93699                 }
93700                 case 248 /* EnumDeclaration */: {
93701                     return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
93702                         if (shouldStripInternal(m))
93703                             return;
93704                         // Rewrite enum values to their constants, if available
93705                         var constValue = resolver.getConstantValue(m);
93706                         return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
93707                     }))));
93708                 }
93709             }
93710             // Anything left unhandled is an error, so this should be unreachable
93711             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
93712             function cleanup(node) {
93713                 if (isEnclosingDeclaration(input)) {
93714                     enclosingDeclaration = previousEnclosingDeclaration;
93715                 }
93716                 if (canProdiceDiagnostic) {
93717                     getSymbolAccessibilityDiagnostic = oldDiag;
93718                 }
93719                 if (input.kind === 249 /* ModuleDeclaration */) {
93720                     needsDeclare = previousNeedsDeclare;
93721                 }
93722                 if (node === input) {
93723                     return node;
93724                 }
93725                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
93726             }
93727         }
93728         function transformVariableStatement(input) {
93729             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
93730                 return;
93731             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
93732             if (!ts.length(nodes))
93733                 return;
93734             return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
93735         }
93736         function recreateBindingPattern(d) {
93737             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
93738         }
93739         function recreateBindingElement(e) {
93740             if (e.kind === 215 /* OmittedExpression */) {
93741                 return;
93742             }
93743             if (e.name) {
93744                 if (!getBindingNameVisible(e))
93745                     return;
93746                 if (ts.isBindingPattern(e.name)) {
93747                     return recreateBindingPattern(e.name);
93748                 }
93749                 else {
93750                     return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
93751                 }
93752             }
93753         }
93754         function checkName(node) {
93755             var oldDiag;
93756             if (!suppressNewDiagnosticContexts) {
93757                 oldDiag = getSymbolAccessibilityDiagnostic;
93758                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
93759             }
93760             errorNameNode = node.name;
93761             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
93762             var decl = node;
93763             var entityName = decl.name.expression;
93764             checkEntityNameVisibility(entityName, enclosingDeclaration);
93765             if (!suppressNewDiagnosticContexts) {
93766                 getSymbolAccessibilityDiagnostic = oldDiag;
93767             }
93768             errorNameNode = undefined;
93769         }
93770         function shouldStripInternal(node) {
93771             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
93772         }
93773         function isScopeMarker(node) {
93774             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
93775         }
93776         function hasScopeMarker(statements) {
93777             return ts.some(statements, isScopeMarker);
93778         }
93779         function ensureModifiers(node) {
93780             var currentFlags = ts.getModifierFlags(node);
93781             var newFlags = ensureModifierFlags(node);
93782             if (currentFlags === newFlags) {
93783                 return node.modifiers;
93784             }
93785             return ts.createModifiersFromModifierFlags(newFlags);
93786         }
93787         function ensureModifierFlags(node) {
93788             var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
93789             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
93790             var parentIsFile = node.parent.kind === 290 /* SourceFile */;
93791             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
93792                 mask ^= 2 /* Ambient */;
93793                 additions = 0 /* None */;
93794             }
93795             return maskModifierFlags(node, mask, additions);
93796         }
93797         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
93798             var accessorType = getTypeAnnotationFromAccessor(node);
93799             if (!accessorType && node !== accessors.firstAccessor) {
93800                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
93801                 // 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
93802                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
93803             }
93804             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
93805                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
93806                 // 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
93807                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
93808             }
93809             return accessorType;
93810         }
93811         function transformHeritageClauses(nodes) {
93812             return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
93813                 return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
93814             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
93815         }
93816     }
93817     ts.transformDeclarations = transformDeclarations;
93818     function isAlwaysType(node) {
93819         if (node.kind === 246 /* InterfaceDeclaration */) {
93820             return true;
93821         }
93822         return false;
93823     }
93824     // Elide "public" modifier, as it is the default
93825     function maskModifiers(node, modifierMask, modifierAdditions) {
93826         return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
93827     }
93828     function maskModifierFlags(node, modifierMask, modifierAdditions) {
93829         if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
93830         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
93831         var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
93832         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
93833             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
93834             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
93835             flags ^= 1 /* Export */;
93836         }
93837         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
93838             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
93839         }
93840         return flags;
93841     }
93842     function getTypeAnnotationFromAccessor(accessor) {
93843         if (accessor) {
93844             return accessor.kind === 163 /* GetAccessor */
93845                 ? accessor.type // Getter - return type
93846                 : accessor.parameters.length > 0
93847                     ? accessor.parameters[0].type // Setter parameter type
93848                     : undefined;
93849         }
93850     }
93851     function canHaveLiteralInitializer(node) {
93852         switch (node.kind) {
93853             case 159 /* PropertyDeclaration */:
93854             case 158 /* PropertySignature */:
93855                 return !ts.hasModifier(node, 8 /* Private */);
93856             case 156 /* Parameter */:
93857             case 242 /* VariableDeclaration */:
93858                 return true;
93859         }
93860         return false;
93861     }
93862     function isPreservedDeclarationStatement(node) {
93863         switch (node.kind) {
93864             case 244 /* FunctionDeclaration */:
93865             case 249 /* ModuleDeclaration */:
93866             case 253 /* ImportEqualsDeclaration */:
93867             case 246 /* InterfaceDeclaration */:
93868             case 245 /* ClassDeclaration */:
93869             case 247 /* TypeAliasDeclaration */:
93870             case 248 /* EnumDeclaration */:
93871             case 225 /* VariableStatement */:
93872             case 254 /* ImportDeclaration */:
93873             case 260 /* ExportDeclaration */:
93874             case 259 /* ExportAssignment */:
93875                 return true;
93876         }
93877         return false;
93878     }
93879     function isProcessedComponent(node) {
93880         switch (node.kind) {
93881             case 166 /* ConstructSignature */:
93882             case 162 /* Constructor */:
93883             case 161 /* MethodDeclaration */:
93884             case 163 /* GetAccessor */:
93885             case 164 /* SetAccessor */:
93886             case 159 /* PropertyDeclaration */:
93887             case 158 /* PropertySignature */:
93888             case 160 /* MethodSignature */:
93889             case 165 /* CallSignature */:
93890             case 167 /* IndexSignature */:
93891             case 242 /* VariableDeclaration */:
93892             case 155 /* TypeParameter */:
93893             case 216 /* ExpressionWithTypeArguments */:
93894             case 169 /* TypeReference */:
93895             case 180 /* ConditionalType */:
93896             case 170 /* FunctionType */:
93897             case 171 /* ConstructorType */:
93898             case 188 /* ImportType */:
93899                 return true;
93900         }
93901         return false;
93902     }
93903 })(ts || (ts = {}));
93904 /* @internal */
93905 var ts;
93906 (function (ts) {
93907     function getModuleTransformer(moduleKind) {
93908         switch (moduleKind) {
93909             case ts.ModuleKind.ESNext:
93910             case ts.ModuleKind.ES2020:
93911             case ts.ModuleKind.ES2015:
93912                 return ts.transformECMAScriptModule;
93913             case ts.ModuleKind.System:
93914                 return ts.transformSystemModule;
93915             default:
93916                 return ts.transformModule;
93917         }
93918     }
93919     var TransformationState;
93920     (function (TransformationState) {
93921         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
93922         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
93923         TransformationState[TransformationState["Completed"] = 2] = "Completed";
93924         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
93925     })(TransformationState || (TransformationState = {}));
93926     var SyntaxKindFeatureFlags;
93927     (function (SyntaxKindFeatureFlags) {
93928         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
93929         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
93930     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
93931     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
93932     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93933         return {
93934             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
93935             declarationTransformers: getDeclarationTransformers(customTransformers),
93936         };
93937     }
93938     ts.getTransformers = getTransformers;
93939     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93940         if (emitOnlyDtsFiles)
93941             return ts.emptyArray;
93942         var jsx = compilerOptions.jsx;
93943         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93944         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93945         var transformers = [];
93946         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
93947         transformers.push(ts.transformTypeScript);
93948         transformers.push(ts.transformClassFields);
93949         if (jsx === 2 /* React */) {
93950             transformers.push(ts.transformJsx);
93951         }
93952         if (languageVersion < 99 /* ESNext */) {
93953             transformers.push(ts.transformESNext);
93954         }
93955         if (languageVersion < 7 /* ES2020 */) {
93956             transformers.push(ts.transformES2020);
93957         }
93958         if (languageVersion < 6 /* ES2019 */) {
93959             transformers.push(ts.transformES2019);
93960         }
93961         if (languageVersion < 5 /* ES2018 */) {
93962             transformers.push(ts.transformES2018);
93963         }
93964         if (languageVersion < 4 /* ES2017 */) {
93965             transformers.push(ts.transformES2017);
93966         }
93967         if (languageVersion < 3 /* ES2016 */) {
93968             transformers.push(ts.transformES2016);
93969         }
93970         if (languageVersion < 2 /* ES2015 */) {
93971             transformers.push(ts.transformES2015);
93972             transformers.push(ts.transformGenerators);
93973         }
93974         transformers.push(getModuleTransformer(moduleKind));
93975         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
93976         // for ES3.
93977         if (languageVersion < 1 /* ES5 */) {
93978             transformers.push(ts.transformES5);
93979         }
93980         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
93981         return transformers;
93982     }
93983     function getDeclarationTransformers(customTransformers) {
93984         var transformers = [];
93985         transformers.push(ts.transformDeclarations);
93986         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
93987         return transformers;
93988     }
93989     /**
93990      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
93991      */
93992     function wrapCustomTransformer(transformer) {
93993         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
93994     }
93995     /**
93996      * Wrap a transformer factory that may return a custom script or declaration transformer object.
93997      */
93998     function wrapCustomTransformerFactory(transformer, handleDefault) {
93999         return function (context) {
94000             var customTransformer = transformer(context);
94001             return typeof customTransformer === "function"
94002                 ? handleDefault(customTransformer)
94003                 : wrapCustomTransformer(customTransformer);
94004         };
94005     }
94006     function wrapScriptTransformerFactory(transformer) {
94007         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
94008     }
94009     function wrapDeclarationTransformerFactory(transformer) {
94010         return wrapCustomTransformerFactory(transformer, ts.identity);
94011     }
94012     function noEmitSubstitution(_hint, node) {
94013         return node;
94014     }
94015     ts.noEmitSubstitution = noEmitSubstitution;
94016     function noEmitNotification(hint, node, callback) {
94017         callback(hint, node);
94018     }
94019     ts.noEmitNotification = noEmitNotification;
94020     /**
94021      * Transforms an array of SourceFiles by passing them through each transformer.
94022      *
94023      * @param resolver The emit resolver provided by the checker.
94024      * @param host The emit host object used to interact with the file system.
94025      * @param options Compiler options to surface in the `TransformationContext`.
94026      * @param nodes An array of nodes to transform.
94027      * @param transforms An array of `TransformerFactory` callbacks.
94028      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
94029      */
94030     function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
94031         var enabledSyntaxKindFeatures = new Array(331 /* Count */);
94032         var lexicalEnvironmentVariableDeclarations;
94033         var lexicalEnvironmentFunctionDeclarations;
94034         var lexicalEnvironmentStatements;
94035         var lexicalEnvironmentFlags = 0 /* None */;
94036         var lexicalEnvironmentVariableDeclarationsStack = [];
94037         var lexicalEnvironmentFunctionDeclarationsStack = [];
94038         var lexicalEnvironmentStatementsStack = [];
94039         var lexicalEnvironmentFlagsStack = [];
94040         var lexicalEnvironmentStackOffset = 0;
94041         var lexicalEnvironmentSuspended = false;
94042         var emitHelpers;
94043         var onSubstituteNode = noEmitSubstitution;
94044         var onEmitNode = noEmitNotification;
94045         var state = 0 /* Uninitialized */;
94046         var diagnostics = [];
94047         // The transformation context is provided to each transformer as part of transformer
94048         // initialization.
94049         var context = {
94050             getCompilerOptions: function () { return options; },
94051             getEmitResolver: function () { return resolver; },
94052             getEmitHost: function () { return host; },
94053             startLexicalEnvironment: startLexicalEnvironment,
94054             suspendLexicalEnvironment: suspendLexicalEnvironment,
94055             resumeLexicalEnvironment: resumeLexicalEnvironment,
94056             endLexicalEnvironment: endLexicalEnvironment,
94057             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
94058             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
94059             hoistVariableDeclaration: hoistVariableDeclaration,
94060             hoistFunctionDeclaration: hoistFunctionDeclaration,
94061             addInitializationStatement: addInitializationStatement,
94062             requestEmitHelper: requestEmitHelper,
94063             readEmitHelpers: readEmitHelpers,
94064             enableSubstitution: enableSubstitution,
94065             enableEmitNotification: enableEmitNotification,
94066             isSubstitutionEnabled: isSubstitutionEnabled,
94067             isEmitNotificationEnabled: isEmitNotificationEnabled,
94068             get onSubstituteNode() { return onSubstituteNode; },
94069             set onSubstituteNode(value) {
94070                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
94071                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
94072                 onSubstituteNode = value;
94073             },
94074             get onEmitNode() { return onEmitNode; },
94075             set onEmitNode(value) {
94076                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
94077                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
94078                 onEmitNode = value;
94079             },
94080             addDiagnostic: function (diag) {
94081                 diagnostics.push(diag);
94082             }
94083         };
94084         // Ensure the parse tree is clean before applying transformations
94085         for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
94086             var node = nodes_4[_i];
94087             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94088         }
94089         ts.performance.mark("beforeTransform");
94090         // Chain together and initialize each transformer.
94091         var transformersWithContext = transformers.map(function (t) { return t(context); });
94092         var transformation = function (node) {
94093             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
94094                 var transform = transformersWithContext_1[_i];
94095                 node = transform(node);
94096             }
94097             return node;
94098         };
94099         // prevent modification of transformation hooks.
94100         state = 1 /* Initialized */;
94101         // Transform each node.
94102         var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
94103         // prevent modification of the lexical environment.
94104         state = 2 /* Completed */;
94105         ts.performance.mark("afterTransform");
94106         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
94107         return {
94108             transformed: transformed,
94109             substituteNode: substituteNode,
94110             emitNodeWithNotification: emitNodeWithNotification,
94111             isEmitNotificationEnabled: isEmitNotificationEnabled,
94112             dispose: dispose,
94113             diagnostics: diagnostics
94114         };
94115         function transformRoot(node) {
94116             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
94117         }
94118         /**
94119          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
94120          */
94121         function enableSubstitution(kind) {
94122             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94123             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
94124         }
94125         /**
94126          * Determines whether expression substitutions are enabled for the provided node.
94127          */
94128         function isSubstitutionEnabled(node) {
94129             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
94130                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
94131         }
94132         /**
94133          * Emits a node with possible substitution.
94134          *
94135          * @param hint A hint as to the intended usage of the node.
94136          * @param node The node to emit.
94137          * @param emitCallback The callback used to emit the node or its substitute.
94138          */
94139         function substituteNode(hint, node) {
94140             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
94141             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
94142         }
94143         /**
94144          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
94145          */
94146         function enableEmitNotification(kind) {
94147             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94148             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
94149         }
94150         /**
94151          * Determines whether before/after emit notifications should be raised in the pretty
94152          * printer when it emits a node.
94153          */
94154         function isEmitNotificationEnabled(node) {
94155             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
94156                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
94157         }
94158         /**
94159          * Emits a node with possible emit notification.
94160          *
94161          * @param hint A hint as to the intended usage of the node.
94162          * @param node The node to emit.
94163          * @param emitCallback The callback used to emit the node.
94164          */
94165         function emitNodeWithNotification(hint, node, emitCallback) {
94166             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
94167             if (node) {
94168                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
94169                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
94170                 if (isEmitNotificationEnabled(node)) {
94171                     onEmitNode(hint, node, emitCallback);
94172                 }
94173                 else {
94174                     emitCallback(hint, node);
94175                 }
94176             }
94177         }
94178         /**
94179          * Records a hoisted variable declaration for the provided name within a lexical environment.
94180          */
94181         function hoistVariableDeclaration(name) {
94182             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94183             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94184             var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
94185             if (!lexicalEnvironmentVariableDeclarations) {
94186                 lexicalEnvironmentVariableDeclarations = [decl];
94187             }
94188             else {
94189                 lexicalEnvironmentVariableDeclarations.push(decl);
94190             }
94191             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
94192                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
94193             }
94194         }
94195         /**
94196          * Records a hoisted function declaration within a lexical environment.
94197          */
94198         function hoistFunctionDeclaration(func) {
94199             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94200             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94201             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
94202             if (!lexicalEnvironmentFunctionDeclarations) {
94203                 lexicalEnvironmentFunctionDeclarations = [func];
94204             }
94205             else {
94206                 lexicalEnvironmentFunctionDeclarations.push(func);
94207             }
94208         }
94209         /**
94210          * Adds an initialization statement to the top of the lexical environment.
94211          */
94212         function addInitializationStatement(node) {
94213             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94214             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94215             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
94216             if (!lexicalEnvironmentStatements) {
94217                 lexicalEnvironmentStatements = [node];
94218             }
94219             else {
94220                 lexicalEnvironmentStatements.push(node);
94221             }
94222         }
94223         /**
94224          * Starts a new lexical environment. Any existing hoisted variable or function declarations
94225          * are pushed onto a stack, and the related storage variables are reset.
94226          */
94227         function startLexicalEnvironment() {
94228             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94229             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94230             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94231             // Save the current lexical environment. Rather than resizing the array we adjust the
94232             // stack size variable. This allows us to reuse existing array slots we've
94233             // already allocated between transformations to avoid allocation and GC overhead during
94234             // transformation.
94235             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
94236             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
94237             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
94238             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
94239             lexicalEnvironmentStackOffset++;
94240             lexicalEnvironmentVariableDeclarations = undefined;
94241             lexicalEnvironmentFunctionDeclarations = undefined;
94242             lexicalEnvironmentStatements = undefined;
94243             lexicalEnvironmentFlags = 0 /* None */;
94244         }
94245         /** Suspends the current lexical environment, usually after visiting a parameter list. */
94246         function suspendLexicalEnvironment() {
94247             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94248             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94249             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
94250             lexicalEnvironmentSuspended = true;
94251         }
94252         /** Resumes a suspended lexical environment, usually before visiting a function body. */
94253         function resumeLexicalEnvironment() {
94254             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94255             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94256             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
94257             lexicalEnvironmentSuspended = false;
94258         }
94259         /**
94260          * Ends a lexical environment. The previous set of hoisted declarations are restored and
94261          * any hoisted declarations added in this environment are returned.
94262          */
94263         function endLexicalEnvironment() {
94264             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94265             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94266             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94267             var statements;
94268             if (lexicalEnvironmentVariableDeclarations ||
94269                 lexicalEnvironmentFunctionDeclarations ||
94270                 lexicalEnvironmentStatements) {
94271                 if (lexicalEnvironmentFunctionDeclarations) {
94272                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
94273                 }
94274                 if (lexicalEnvironmentVariableDeclarations) {
94275                     var statement = ts.createVariableStatement(
94276                     /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
94277                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94278                     if (!statements) {
94279                         statements = [statement];
94280                     }
94281                     else {
94282                         statements.push(statement);
94283                     }
94284                 }
94285                 if (lexicalEnvironmentStatements) {
94286                     if (!statements) {
94287                         statements = __spreadArrays(lexicalEnvironmentStatements);
94288                     }
94289                     else {
94290                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
94291                     }
94292                 }
94293             }
94294             // Restore the previous lexical environment.
94295             lexicalEnvironmentStackOffset--;
94296             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
94297             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
94298             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
94299             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
94300             if (lexicalEnvironmentStackOffset === 0) {
94301                 lexicalEnvironmentVariableDeclarationsStack = [];
94302                 lexicalEnvironmentFunctionDeclarationsStack = [];
94303                 lexicalEnvironmentStatementsStack = [];
94304                 lexicalEnvironmentFlagsStack = [];
94305             }
94306             return statements;
94307         }
94308         function setLexicalEnvironmentFlags(flags, value) {
94309             lexicalEnvironmentFlags = value ?
94310                 lexicalEnvironmentFlags | flags :
94311                 lexicalEnvironmentFlags & ~flags;
94312         }
94313         function getLexicalEnvironmentFlags() {
94314             return lexicalEnvironmentFlags;
94315         }
94316         function requestEmitHelper(helper) {
94317             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94318             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94319             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
94320             if (helper.dependencies) {
94321                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
94322                     var h = _a[_i];
94323                     requestEmitHelper(h);
94324                 }
94325             }
94326             emitHelpers = ts.append(emitHelpers, helper);
94327         }
94328         function readEmitHelpers() {
94329             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94330             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94331             var helpers = emitHelpers;
94332             emitHelpers = undefined;
94333             return helpers;
94334         }
94335         function dispose() {
94336             if (state < 3 /* Disposed */) {
94337                 // Clean up emit nodes on parse tree
94338                 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
94339                     var node = nodes_5[_i];
94340                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94341                 }
94342                 // Release references to external entries for GC purposes.
94343                 lexicalEnvironmentVariableDeclarations = undefined;
94344                 lexicalEnvironmentVariableDeclarationsStack = undefined;
94345                 lexicalEnvironmentFunctionDeclarations = undefined;
94346                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
94347                 onSubstituteNode = undefined;
94348                 onEmitNode = undefined;
94349                 emitHelpers = undefined;
94350                 // Prevent further use of the transformation result.
94351                 state = 3 /* Disposed */;
94352             }
94353         }
94354     }
94355     ts.transformNodes = transformNodes;
94356 })(ts || (ts = {}));
94357 var ts;
94358 (function (ts) {
94359     var brackets = createBracketsMap();
94360     var syntheticParent = { pos: -1, end: -1 };
94361     /*@internal*/
94362     function isBuildInfoFile(file) {
94363         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
94364     }
94365     ts.isBuildInfoFile = isBuildInfoFile;
94366     /*@internal*/
94367     /**
94368      * Iterates over the source files that are expected to have an emit output.
94369      *
94370      * @param host An EmitHost.
94371      * @param action The action to execute.
94372      * @param sourceFilesOrTargetSourceFile
94373      *   If an array, the full list of source files to emit.
94374      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
94375      */
94376     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
94377         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
94378         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
94379         var options = host.getCompilerOptions();
94380         if (options.outFile || options.out) {
94381             var prepends = host.getPrependNodes();
94382             if (sourceFiles.length || prepends.length) {
94383                 var bundle = ts.createBundle(sourceFiles, prepends);
94384                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
94385                 if (result) {
94386                     return result;
94387                 }
94388             }
94389         }
94390         else {
94391             if (!onlyBuildInfo) {
94392                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
94393                     var sourceFile = sourceFiles_1[_a];
94394                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
94395                     if (result) {
94396                         return result;
94397                     }
94398                 }
94399             }
94400             if (includeBuildInfo) {
94401                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
94402                 if (buildInfoPath)
94403                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
94404             }
94405         }
94406     }
94407     ts.forEachEmittedFile = forEachEmittedFile;
94408     function getTsBuildInfoEmitOutputFilePath(options) {
94409         var configFile = options.configFilePath;
94410         if (!ts.isIncrementalCompilation(options))
94411             return undefined;
94412         if (options.tsBuildInfoFile)
94413             return options.tsBuildInfoFile;
94414         var outPath = options.outFile || options.out;
94415         var buildInfoExtensionLess;
94416         if (outPath) {
94417             buildInfoExtensionLess = ts.removeFileExtension(outPath);
94418         }
94419         else {
94420             if (!configFile)
94421                 return undefined;
94422             var configFileExtensionLess = ts.removeFileExtension(configFile);
94423             buildInfoExtensionLess = options.outDir ?
94424                 options.rootDir ?
94425                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
94426                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
94427                 configFileExtensionLess;
94428         }
94429         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
94430     }
94431     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
94432     /*@internal*/
94433     function getOutputPathsForBundle(options, forceDtsPaths) {
94434         var outPath = options.outFile || options.out;
94435         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
94436         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
94437         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
94438         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94439         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
94440         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
94441     }
94442     ts.getOutputPathsForBundle = getOutputPathsForBundle;
94443     /*@internal*/
94444     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
94445         var options = host.getCompilerOptions();
94446         if (sourceFile.kind === 291 /* Bundle */) {
94447             return getOutputPathsForBundle(options, forceDtsPaths);
94448         }
94449         else {
94450             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
94451             var isJsonFile = ts.isJsonSourceFile(sourceFile);
94452             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
94453             var isJsonEmittedToSameLocation = isJsonFile &&
94454                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
94455             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
94456             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
94457             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
94458             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94459             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
94460         }
94461     }
94462     ts.getOutputPathsFor = getOutputPathsFor;
94463     function getSourceMapFilePath(jsFilePath, options) {
94464         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
94465     }
94466     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
94467     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
94468     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
94469     /* @internal */
94470     function getOutputExtension(sourceFile, options) {
94471         if (ts.isJsonSourceFile(sourceFile)) {
94472             return ".json" /* Json */;
94473         }
94474         if (options.jsx === 1 /* Preserve */) {
94475             if (ts.isSourceFileJS(sourceFile)) {
94476                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
94477                     return ".jsx" /* Jsx */;
94478                 }
94479             }
94480             else if (sourceFile.languageVariant === 1 /* JSX */) {
94481                 // TypeScript source file preserving JSX syntax
94482                 return ".jsx" /* Jsx */;
94483             }
94484         }
94485         return ".js" /* Js */;
94486     }
94487     ts.getOutputExtension = getOutputExtension;
94488     function rootDirOfOptions(configFile) {
94489         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
94490     }
94491     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
94492         return outputDir ?
94493             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
94494             inputFileName;
94495     }
94496     /* @internal */
94497     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
94498         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
94499         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
94500     }
94501     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
94502     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
94503         if (configFile.options.emitDeclarationOnly)
94504             return undefined;
94505         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
94506         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
94507             ".json" /* Json */ :
94508             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
94509                 ".jsx" /* Jsx */ :
94510                 ".js" /* Js */);
94511         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
94512             outputFileName :
94513             undefined;
94514     }
94515     function createAddOutput() {
94516         var outputs;
94517         return { addOutput: addOutput, getOutputs: getOutputs };
94518         function addOutput(path) {
94519             if (path) {
94520                 (outputs || (outputs = [])).push(path);
94521             }
94522         }
94523         function getOutputs() {
94524             return outputs || ts.emptyArray;
94525         }
94526     }
94527     function getSingleOutputFileNames(configFile, addOutput) {
94528         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94529         addOutput(jsFilePath);
94530         addOutput(sourceMapFilePath);
94531         addOutput(declarationFilePath);
94532         addOutput(declarationMapPath);
94533         addOutput(buildInfoPath);
94534     }
94535     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
94536         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94537             return;
94538         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94539         addOutput(js);
94540         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94541             return;
94542         if (js && configFile.options.sourceMap) {
94543             addOutput(js + ".map");
94544         }
94545         if (ts.getEmitDeclarations(configFile.options)) {
94546             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94547             addOutput(dts);
94548             if (configFile.options.declarationMap) {
94549                 addOutput(dts + ".map");
94550             }
94551         }
94552     }
94553     /*@internal*/
94554     function getAllProjectOutputs(configFile, ignoreCase) {
94555         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94556         if (configFile.options.outFile || configFile.options.out) {
94557             getSingleOutputFileNames(configFile, addOutput);
94558         }
94559         else {
94560             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
94561                 var inputFileName = _c[_b];
94562                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
94563             }
94564             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
94565         }
94566         return getOutputs();
94567     }
94568     ts.getAllProjectOutputs = getAllProjectOutputs;
94569     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
94570         inputFileName = ts.normalizePath(inputFileName);
94571         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
94572         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94573         if (commandLine.options.outFile || commandLine.options.out) {
94574             getSingleOutputFileNames(commandLine, addOutput);
94575         }
94576         else {
94577             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
94578         }
94579         return getOutputs();
94580     }
94581     ts.getOutputFileNames = getOutputFileNames;
94582     /*@internal*/
94583     function getFirstProjectOutput(configFile, ignoreCase) {
94584         if (configFile.options.outFile || configFile.options.out) {
94585             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
94586             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
94587         }
94588         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
94589             var inputFileName = _b[_a];
94590             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94591                 continue;
94592             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94593             if (jsFilePath)
94594                 return jsFilePath;
94595             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94596                 continue;
94597             if (ts.getEmitDeclarations(configFile.options)) {
94598                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94599             }
94600         }
94601         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
94602         if (buildInfoPath)
94603             return buildInfoPath;
94604         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
94605     }
94606     ts.getFirstProjectOutput = getFirstProjectOutput;
94607     /*@internal*/
94608     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
94609     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
94610         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
94611         var compilerOptions = host.getCompilerOptions();
94612         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
94613         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
94614         var emitterDiagnostics = ts.createDiagnosticCollection();
94615         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
94616         var writer = ts.createTextWriter(newLine);
94617         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
94618         var bundleBuildInfo;
94619         var emitSkipped = false;
94620         var exportedModulesFromDeclarationEmit;
94621         // Emit each output file
94622         enter();
94623         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
94624         exit();
94625         return {
94626             emitSkipped: emitSkipped,
94627             diagnostics: emitterDiagnostics.getDiagnostics(),
94628             emittedFiles: emittedFilesList,
94629             sourceMaps: sourceMapDataList,
94630             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
94631         };
94632         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
94633             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94634             var buildInfoDirectory;
94635             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
94636                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94637                 bundleBuildInfo = {
94638                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
94639                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
94640                 };
94641             }
94642             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
94643             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
94644             emitBuildInfo(bundleBuildInfo, buildInfoPath);
94645             if (!emitSkipped && emittedFilesList) {
94646                 if (!emitOnlyDtsFiles) {
94647                     if (jsFilePath) {
94648                         emittedFilesList.push(jsFilePath);
94649                     }
94650                     if (sourceMapFilePath) {
94651                         emittedFilesList.push(sourceMapFilePath);
94652                     }
94653                     if (buildInfoPath) {
94654                         emittedFilesList.push(buildInfoPath);
94655                     }
94656                 }
94657                 if (declarationFilePath) {
94658                     emittedFilesList.push(declarationFilePath);
94659                 }
94660                 if (declarationMapPath) {
94661                     emittedFilesList.push(declarationMapPath);
94662                 }
94663             }
94664             function relativeToBuildInfo(path) {
94665                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
94666             }
94667         }
94668         function emitBuildInfo(bundle, buildInfoPath) {
94669             // Write build information if applicable
94670             if (!buildInfoPath || targetSourceFile || emitSkipped)
94671                 return;
94672             var program = host.getProgramBuildInfo();
94673             if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
94674                 emitSkipped = true;
94675                 return;
94676             }
94677             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
94678             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
94679         }
94680         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
94681             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
94682                 return;
94683             }
94684             // Make sure not to write js file and source map file if any of them cannot be written
94685             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
94686                 emitSkipped = true;
94687                 return;
94688             }
94689             // Transform the source files
94690             var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
94691             var printerOptions = {
94692                 removeComments: compilerOptions.removeComments,
94693                 newLine: compilerOptions.newLine,
94694                 noEmitHelpers: compilerOptions.noEmitHelpers,
94695                 module: compilerOptions.module,
94696                 target: compilerOptions.target,
94697                 sourceMap: compilerOptions.sourceMap,
94698                 inlineSourceMap: compilerOptions.inlineSourceMap,
94699                 inlineSources: compilerOptions.inlineSources,
94700                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94701                 writeBundleFileInfo: !!bundleBuildInfo,
94702                 relativeToBuildInfo: relativeToBuildInfo
94703             };
94704             // Create a printer to print the nodes
94705             var printer = createPrinter(printerOptions, {
94706                 // resolver hooks
94707                 hasGlobalName: resolver.hasGlobalName,
94708                 // transform hooks
94709                 onEmitNode: transform.emitNodeWithNotification,
94710                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
94711                 substituteNode: transform.substituteNode,
94712             });
94713             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
94714             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
94715             // Clean up emit nodes on parse tree
94716             transform.dispose();
94717             if (bundleBuildInfo)
94718                 bundleBuildInfo.js = printer.bundleFileInfo;
94719         }
94720         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
94721             if (!sourceFileOrBundle)
94722                 return;
94723             if (!declarationFilePath) {
94724                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
94725                     emitSkipped = true;
94726                 return;
94727             }
94728             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
94729             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
94730             // Setup and perform the transformation to retrieve declarations from the input files
94731             var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
94732             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
94733                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
94734                 // Do that here when emitting only dts files
94735                 filesForEmit.forEach(collectLinkedAliases);
94736             }
94737             var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
94738             if (ts.length(declarationTransform.diagnostics)) {
94739                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
94740                     var diagnostic = _b[_a];
94741                     emitterDiagnostics.add(diagnostic);
94742                 }
94743             }
94744             var printerOptions = {
94745                 removeComments: compilerOptions.removeComments,
94746                 newLine: compilerOptions.newLine,
94747                 noEmitHelpers: true,
94748                 module: compilerOptions.module,
94749                 target: compilerOptions.target,
94750                 sourceMap: compilerOptions.sourceMap,
94751                 inlineSourceMap: compilerOptions.inlineSourceMap,
94752                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94753                 onlyPrintJsDocStyle: true,
94754                 writeBundleFileInfo: !!bundleBuildInfo,
94755                 recordInternalSection: !!bundleBuildInfo,
94756                 relativeToBuildInfo: relativeToBuildInfo
94757             };
94758             var declarationPrinter = createPrinter(printerOptions, {
94759                 // resolver hooks
94760                 hasGlobalName: resolver.hasGlobalName,
94761                 // transform hooks
94762                 onEmitNode: declarationTransform.emitNodeWithNotification,
94763                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
94764                 substituteNode: declarationTransform.substituteNode,
94765             });
94766             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
94767             emitSkipped = emitSkipped || declBlocked;
94768             if (!declBlocked || forceDtsEmit) {
94769                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
94770                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
94771                     sourceMap: compilerOptions.declarationMap,
94772                     sourceRoot: compilerOptions.sourceRoot,
94773                     mapRoot: compilerOptions.mapRoot,
94774                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
94775                 });
94776                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
94777                     var sourceFile = declarationTransform.transformed[0];
94778                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
94779                 }
94780             }
94781             declarationTransform.dispose();
94782             if (bundleBuildInfo)
94783                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
94784         }
94785         function collectLinkedAliases(node) {
94786             if (ts.isExportAssignment(node)) {
94787                 if (node.expression.kind === 75 /* Identifier */) {
94788                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
94789                 }
94790                 return;
94791             }
94792             else if (ts.isExportSpecifier(node)) {
94793                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
94794                 return;
94795             }
94796             ts.forEachChild(node, collectLinkedAliases);
94797         }
94798         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
94799             var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
94800             var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
94801             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
94802             var sourceMapGenerator;
94803             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
94804                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
94805             }
94806             if (bundle) {
94807                 printer.writeBundle(bundle, writer, sourceMapGenerator);
94808             }
94809             else {
94810                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
94811             }
94812             if (sourceMapGenerator) {
94813                 if (sourceMapDataList) {
94814                     sourceMapDataList.push({
94815                         inputSourceFileNames: sourceMapGenerator.getSources(),
94816                         sourceMap: sourceMapGenerator.toJSON()
94817                     });
94818                 }
94819                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
94820                 if (sourceMappingURL) {
94821                     if (!writer.isAtStartOfLine())
94822                         writer.rawWrite(newLine);
94823                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
94824                 }
94825                 // Write the source map
94826                 if (sourceMapFilePath) {
94827                     var sourceMap = sourceMapGenerator.toString();
94828                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
94829                 }
94830             }
94831             else {
94832                 writer.writeLine();
94833             }
94834             // Write the output file
94835             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
94836             // Reset state
94837             writer.clear();
94838         }
94839         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
94840             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
94841                 && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
94842         }
94843         function getSourceRoot(mapOptions) {
94844             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
94845             // relative paths of the sources list in the sourcemap
94846             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
94847             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
94848         }
94849         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
94850             if (mapOptions.sourceRoot)
94851                 return host.getCommonSourceDirectory();
94852             if (mapOptions.mapRoot) {
94853                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94854                 if (sourceFile) {
94855                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94856                     // 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
94857                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94858                 }
94859                 if (ts.getRootLength(sourceMapDir) === 0) {
94860                     // The relative paths are relative to the common directory
94861                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94862                 }
94863                 return sourceMapDir;
94864             }
94865             return ts.getDirectoryPath(ts.normalizePath(filePath));
94866         }
94867         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
94868             if (mapOptions.inlineSourceMap) {
94869                 // Encode the sourceMap into the sourceMap url
94870                 var sourceMapText = sourceMapGenerator.toString();
94871                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
94872                 return "data:application/json;base64," + base64SourceMapText;
94873             }
94874             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
94875             if (mapOptions.mapRoot) {
94876                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94877                 if (sourceFile) {
94878                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94879                     // 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
94880                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94881                 }
94882                 if (ts.getRootLength(sourceMapDir) === 0) {
94883                     // The relative paths are relative to the common directory
94884                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94885                     return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
94886                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
94887                     host.getCurrentDirectory(), host.getCanonicalFileName, 
94888                     /*isAbsolutePathAnUrl*/ true);
94889                 }
94890                 else {
94891                     return ts.combinePaths(sourceMapDir, sourceMapFile);
94892                 }
94893             }
94894             return sourceMapFile;
94895         }
94896     }
94897     ts.emitFiles = emitFiles;
94898     /*@internal*/
94899     function getBuildInfoText(buildInfo) {
94900         return JSON.stringify(buildInfo, undefined, 2);
94901     }
94902     ts.getBuildInfoText = getBuildInfoText;
94903     /*@internal*/
94904     function getBuildInfo(buildInfoText) {
94905         return JSON.parse(buildInfoText);
94906     }
94907     ts.getBuildInfo = getBuildInfo;
94908     /*@internal*/
94909     ts.notImplementedResolver = {
94910         hasGlobalName: ts.notImplemented,
94911         getReferencedExportContainer: ts.notImplemented,
94912         getReferencedImportDeclaration: ts.notImplemented,
94913         getReferencedDeclarationWithCollidingName: ts.notImplemented,
94914         isDeclarationWithCollidingName: ts.notImplemented,
94915         isValueAliasDeclaration: ts.notImplemented,
94916         isReferencedAliasDeclaration: ts.notImplemented,
94917         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
94918         getNodeCheckFlags: ts.notImplemented,
94919         isDeclarationVisible: ts.notImplemented,
94920         isLateBound: function (_node) { return false; },
94921         collectLinkedAliases: ts.notImplemented,
94922         isImplementationOfOverload: ts.notImplemented,
94923         isRequiredInitializedParameter: ts.notImplemented,
94924         isOptionalUninitializedParameterProperty: ts.notImplemented,
94925         isExpandoFunctionDeclaration: ts.notImplemented,
94926         getPropertiesOfContainerFunction: ts.notImplemented,
94927         createTypeOfDeclaration: ts.notImplemented,
94928         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
94929         createTypeOfExpression: ts.notImplemented,
94930         createLiteralConstValue: ts.notImplemented,
94931         isSymbolAccessible: ts.notImplemented,
94932         isEntityNameVisible: ts.notImplemented,
94933         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
94934         getConstantValue: ts.notImplemented,
94935         getReferencedValueDeclaration: ts.notImplemented,
94936         getTypeReferenceSerializationKind: ts.notImplemented,
94937         isOptionalParameter: ts.notImplemented,
94938         moduleExportsSomeValue: ts.notImplemented,
94939         isArgumentsLocalBinding: ts.notImplemented,
94940         getExternalModuleFileFromDeclaration: ts.notImplemented,
94941         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
94942         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
94943         isLiteralConstDeclaration: ts.notImplemented,
94944         getJsxFactoryEntity: ts.notImplemented,
94945         getAllAccessorDeclarations: ts.notImplemented,
94946         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
94947         isBindingCapturedByNode: ts.notImplemented,
94948         getDeclarationStatementsForSourceFile: ts.notImplemented,
94949         isImportRequiredByAugmentation: ts.notImplemented,
94950     };
94951     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
94952         var sourceFiles = bundle.sourceFiles.map(function (fileName) {
94953             var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
94954             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
94955             sourceFile.text = "";
94956             sourceFile.statements = ts.createNodeArray();
94957             return sourceFile;
94958         });
94959         var jsBundle = ts.Debug.checkDefined(bundle.js);
94960         ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
94961             var sourceFile = sourceFiles[prologueInfo.file];
94962             sourceFile.text = prologueInfo.text;
94963             sourceFile.end = prologueInfo.text.length;
94964             sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
94965                 var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
94966                 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
94967                 statement.expression.text = directive.expression.text;
94968                 return statement;
94969             }));
94970         });
94971         return sourceFiles;
94972     }
94973     /*@internal*/
94974     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
94975         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
94976         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
94977         if (!buildInfoText)
94978             return buildInfoPath;
94979         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
94980         if (!jsFileText)
94981             return jsFilePath;
94982         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
94983         // error if no source map or for now if inline sourcemap
94984         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
94985             return sourceMapFilePath || "inline sourcemap decoding";
94986         // read declaration text
94987         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
94988         if (declarationFilePath && !declarationText)
94989             return declarationFilePath;
94990         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
94991         // error if no source map or for now if inline sourcemap
94992         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
94993             return declarationMapPath || "inline sourcemap decoding";
94994         var buildInfo = getBuildInfo(buildInfoText);
94995         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
94996             return buildInfoPath;
94997         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94998         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
94999         /*onlyOwnText*/ true);
95000         var outputFiles = [];
95001         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
95002         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
95003         var emitHost = {
95004             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
95005             getCanonicalFileName: host.getCanonicalFileName,
95006             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
95007             getCompilerOptions: function () { return config.options; },
95008             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
95009             getNewLine: function () { return host.getNewLine(); },
95010             getSourceFile: ts.returnUndefined,
95011             getSourceFileByPath: ts.returnUndefined,
95012             getSourceFiles: function () { return sourceFilesForJsEmit; },
95013             getLibFileFromReference: ts.notImplemented,
95014             isSourceFileFromExternalLibrary: ts.returnFalse,
95015             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
95016             getProjectReferenceRedirect: ts.returnUndefined,
95017             isSourceOfProjectReferenceRedirect: ts.returnFalse,
95018             writeFile: function (name, text, writeByteOrderMark) {
95019                 switch (name) {
95020                     case jsFilePath:
95021                         if (jsFileText === text)
95022                             return;
95023                         break;
95024                     case sourceMapFilePath:
95025                         if (sourceMapText === text)
95026                             return;
95027                         break;
95028                     case buildInfoPath:
95029                         var newBuildInfo = getBuildInfo(text);
95030                         newBuildInfo.program = buildInfo.program;
95031                         // Update sourceFileInfo
95032                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
95033                         newBuildInfo.bundle.js.sources = js.sources;
95034                         if (dts) {
95035                             newBuildInfo.bundle.dts.sources = dts.sources;
95036                         }
95037                         newBuildInfo.bundle.sourceFiles = sourceFiles;
95038                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
95039                         return;
95040                     case declarationFilePath:
95041                         if (declarationText === text)
95042                             return;
95043                         break;
95044                     case declarationMapPath:
95045                         if (declarationMapText === text)
95046                             return;
95047                         break;
95048                     default:
95049                         ts.Debug.fail("Unexpected path: " + name);
95050                 }
95051                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
95052             },
95053             isEmitBlocked: ts.returnFalse,
95054             readFile: function (f) { return host.readFile(f); },
95055             fileExists: function (f) { return host.fileExists(f); },
95056             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
95057             getProgramBuildInfo: ts.returnUndefined,
95058             getSourceFileFromReference: ts.returnUndefined,
95059             redirectTargetsMap: ts.createMultiMap()
95060         };
95061         emitFiles(ts.notImplementedResolver, emitHost, 
95062         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
95063         return outputFiles;
95064     }
95065     ts.emitUsingBuildInfo = emitUsingBuildInfo;
95066     var PipelinePhase;
95067     (function (PipelinePhase) {
95068         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
95069         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
95070         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
95071         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
95072         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
95073     })(PipelinePhase || (PipelinePhase = {}));
95074     function createPrinter(printerOptions, handlers) {
95075         if (printerOptions === void 0) { printerOptions = {}; }
95076         if (handlers === void 0) { handlers = {}; }
95077         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;
95078         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
95079         var newLine = ts.getNewLineCharacter(printerOptions);
95080         var moduleKind = ts.getEmitModuleKind(printerOptions);
95081         var bundledHelpers = ts.createMap();
95082         var currentSourceFile;
95083         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
95084         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
95085         var generatedNames; // Set of names generated by the NameGenerator.
95086         var tempFlagsStack; // Stack of enclosing name generation scopes.
95087         var tempFlags; // TempFlags for the current name generation scope.
95088         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
95089         var reservedNames; // TempFlags to reserve in nested name generation scopes.
95090         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
95091         var writer;
95092         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
95093         var write = writeBase;
95094         var isOwnFileEmit;
95095         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
95096         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
95097         var recordInternalSection = printerOptions.recordInternalSection;
95098         var sourceFileTextPos = 0;
95099         var sourceFileTextKind = "text" /* Text */;
95100         // Source Maps
95101         var sourceMapsDisabled = true;
95102         var sourceMapGenerator;
95103         var sourceMapSource;
95104         var sourceMapSourceIndex = -1;
95105         // Comments
95106         var containerPos = -1;
95107         var containerEnd = -1;
95108         var declarationListContainerEnd = -1;
95109         var currentLineMap;
95110         var detachedCommentsInfo;
95111         var hasWrittenComment = false;
95112         var commentsDisabled = !!printerOptions.removeComments;
95113         var lastNode;
95114         var lastSubstitution;
95115         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
95116         reset();
95117         return {
95118             // public API
95119             printNode: printNode,
95120             printList: printList,
95121             printFile: printFile,
95122             printBundle: printBundle,
95123             // internal API
95124             writeNode: writeNode,
95125             writeList: writeList,
95126             writeFile: writeFile,
95127             writeBundle: writeBundle,
95128             bundleFileInfo: bundleFileInfo
95129         };
95130         function printNode(hint, node, sourceFile) {
95131             switch (hint) {
95132                 case 0 /* SourceFile */:
95133                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
95134                     break;
95135                 case 2 /* IdentifierName */:
95136                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
95137                     break;
95138                 case 1 /* Expression */:
95139                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
95140                     break;
95141             }
95142             switch (node.kind) {
95143                 case 290 /* SourceFile */: return printFile(node);
95144                 case 291 /* Bundle */: return printBundle(node);
95145                 case 292 /* UnparsedSource */: return printUnparsedSource(node);
95146             }
95147             writeNode(hint, node, sourceFile, beginPrint());
95148             return endPrint();
95149         }
95150         function printList(format, nodes, sourceFile) {
95151             writeList(format, nodes, sourceFile, beginPrint());
95152             return endPrint();
95153         }
95154         function printBundle(bundle) {
95155             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
95156             return endPrint();
95157         }
95158         function printFile(sourceFile) {
95159             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
95160             return endPrint();
95161         }
95162         function printUnparsedSource(unparsed) {
95163             writeUnparsedSource(unparsed, beginPrint());
95164             return endPrint();
95165         }
95166         function writeNode(hint, node, sourceFile, output) {
95167             var previousWriter = writer;
95168             setWriter(output, /*_sourceMapGenerator*/ undefined);
95169             print(hint, node, sourceFile);
95170             reset();
95171             writer = previousWriter;
95172         }
95173         function writeList(format, nodes, sourceFile, output) {
95174             var previousWriter = writer;
95175             setWriter(output, /*_sourceMapGenerator*/ undefined);
95176             if (sourceFile) {
95177                 setSourceFile(sourceFile);
95178             }
95179             emitList(syntheticParent, nodes, format);
95180             reset();
95181             writer = previousWriter;
95182         }
95183         function getTextPosWithWriteLine() {
95184             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
95185         }
95186         function updateOrPushBundleFileTextLike(pos, end, kind) {
95187             var last = ts.lastOrUndefined(bundleFileInfo.sections);
95188             if (last && last.kind === kind) {
95189                 last.end = end;
95190             }
95191             else {
95192                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
95193             }
95194         }
95195         function recordBundleFileInternalSectionStart(node) {
95196             if (recordInternalSection &&
95197                 bundleFileInfo &&
95198                 currentSourceFile &&
95199                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
95200                 ts.isInternalDeclaration(node, currentSourceFile) &&
95201                 sourceFileTextKind !== "internal" /* Internal */) {
95202                 var prevSourceFileTextKind = sourceFileTextKind;
95203                 recordBundleFileTextLikeSection(writer.getTextPos());
95204                 sourceFileTextPos = getTextPosWithWriteLine();
95205                 sourceFileTextKind = "internal" /* Internal */;
95206                 return prevSourceFileTextKind;
95207             }
95208             return undefined;
95209         }
95210         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
95211             if (prevSourceFileTextKind) {
95212                 recordBundleFileTextLikeSection(writer.getTextPos());
95213                 sourceFileTextPos = getTextPosWithWriteLine();
95214                 sourceFileTextKind = prevSourceFileTextKind;
95215             }
95216         }
95217         function recordBundleFileTextLikeSection(end) {
95218             if (sourceFileTextPos < end) {
95219                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
95220                 return true;
95221             }
95222             return false;
95223         }
95224         function writeBundle(bundle, output, sourceMapGenerator) {
95225             var _a;
95226             isOwnFileEmit = false;
95227             var previousWriter = writer;
95228             setWriter(output, sourceMapGenerator);
95229             emitShebangIfNeeded(bundle);
95230             emitPrologueDirectivesIfNeeded(bundle);
95231             emitHelpers(bundle);
95232             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
95233             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
95234                 var prepend = _c[_b];
95235                 writeLine();
95236                 var pos = writer.getTextPos();
95237                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
95238                 if (savedSections)
95239                     bundleFileInfo.sections = [];
95240                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
95241                 if (bundleFileInfo) {
95242                     var newSections = bundleFileInfo.sections;
95243                     bundleFileInfo.sections = savedSections;
95244                     if (prepend.oldFileOfCurrentEmit)
95245                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
95246                     else {
95247                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
95248                         bundleFileInfo.sections.push({
95249                             pos: pos,
95250                             end: writer.getTextPos(),
95251                             kind: "prepend" /* Prepend */,
95252                             data: relativeToBuildInfo(prepend.fileName),
95253                             texts: newSections
95254                         });
95255                     }
95256                 }
95257             }
95258             sourceFileTextPos = getTextPosWithWriteLine();
95259             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
95260                 var sourceFile = _e[_d];
95261                 print(0 /* SourceFile */, sourceFile, sourceFile);
95262             }
95263             if (bundleFileInfo && bundle.sourceFiles.length) {
95264                 var end = writer.getTextPos();
95265                 if (recordBundleFileTextLikeSection(end)) {
95266                     // Store prologues
95267                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
95268                     if (prologues) {
95269                         if (!bundleFileInfo.sources)
95270                             bundleFileInfo.sources = {};
95271                         bundleFileInfo.sources.prologues = prologues;
95272                     }
95273                     // Store helpes
95274                     var helpers = getHelpersFromBundledSourceFiles(bundle);
95275                     if (helpers) {
95276                         if (!bundleFileInfo.sources)
95277                             bundleFileInfo.sources = {};
95278                         bundleFileInfo.sources.helpers = helpers;
95279                     }
95280                 }
95281             }
95282             reset();
95283             writer = previousWriter;
95284         }
95285         function writeUnparsedSource(unparsed, output) {
95286             var previousWriter = writer;
95287             setWriter(output, /*_sourceMapGenerator*/ undefined);
95288             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
95289             reset();
95290             writer = previousWriter;
95291         }
95292         function writeFile(sourceFile, output, sourceMapGenerator) {
95293             isOwnFileEmit = true;
95294             var previousWriter = writer;
95295             setWriter(output, sourceMapGenerator);
95296             emitShebangIfNeeded(sourceFile);
95297             emitPrologueDirectivesIfNeeded(sourceFile);
95298             print(0 /* SourceFile */, sourceFile, sourceFile);
95299             reset();
95300             writer = previousWriter;
95301         }
95302         function beginPrint() {
95303             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
95304         }
95305         function endPrint() {
95306             var text = ownWriter.getText();
95307             ownWriter.clear();
95308             return text;
95309         }
95310         function print(hint, node, sourceFile) {
95311             if (sourceFile) {
95312                 setSourceFile(sourceFile);
95313             }
95314             pipelineEmit(hint, node);
95315         }
95316         function setSourceFile(sourceFile) {
95317             currentSourceFile = sourceFile;
95318             currentLineMap = undefined;
95319             detachedCommentsInfo = undefined;
95320             if (sourceFile) {
95321                 setSourceMapSource(sourceFile);
95322             }
95323         }
95324         function setWriter(_writer, _sourceMapGenerator) {
95325             if (_writer && printerOptions.omitTrailingSemicolon) {
95326                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
95327             }
95328             writer = _writer; // TODO: GH#18217
95329             sourceMapGenerator = _sourceMapGenerator;
95330             sourceMapsDisabled = !writer || !sourceMapGenerator;
95331         }
95332         function reset() {
95333             nodeIdToGeneratedName = [];
95334             autoGeneratedIdToGeneratedName = [];
95335             generatedNames = ts.createMap();
95336             tempFlagsStack = [];
95337             tempFlags = 0 /* Auto */;
95338             reservedNamesStack = [];
95339             currentSourceFile = undefined;
95340             currentLineMap = undefined;
95341             detachedCommentsInfo = undefined;
95342             lastNode = undefined;
95343             lastSubstitution = undefined;
95344             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
95345         }
95346         function getCurrentLineMap() {
95347             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
95348         }
95349         function emit(node) {
95350             if (node === undefined)
95351                 return;
95352             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
95353             var substitute = pipelineEmit(4 /* Unspecified */, node);
95354             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
95355             return substitute;
95356         }
95357         function emitIdentifierName(node) {
95358             if (node === undefined)
95359                 return;
95360             return pipelineEmit(2 /* IdentifierName */, node);
95361         }
95362         function emitExpression(node) {
95363             if (node === undefined)
95364                 return;
95365             return pipelineEmit(1 /* Expression */, node);
95366         }
95367         function emitJsxAttributeValue(node) {
95368             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
95369         }
95370         function pipelineEmit(emitHint, node) {
95371             var savedLastNode = lastNode;
95372             var savedLastSubstitution = lastSubstitution;
95373             var savedPreserveSourceNewlines = preserveSourceNewlines;
95374             lastNode = node;
95375             lastSubstitution = undefined;
95376             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
95377                 preserveSourceNewlines = false;
95378             }
95379             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
95380             pipelinePhase(emitHint, node);
95381             ts.Debug.assert(lastNode === node);
95382             var substitute = lastSubstitution;
95383             lastNode = savedLastNode;
95384             lastSubstitution = savedLastSubstitution;
95385             preserveSourceNewlines = savedPreserveSourceNewlines;
95386             return substitute || node;
95387         }
95388         function getPipelinePhase(phase, emitHint, node) {
95389             switch (phase) {
95390                 case 0 /* Notification */:
95391                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
95392                         return pipelineEmitWithNotification;
95393                     }
95394                 // falls through
95395                 case 1 /* Substitution */:
95396                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
95397                         return pipelineEmitWithSubstitution;
95398                     }
95399                 // falls through
95400                 case 2 /* Comments */:
95401                     if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
95402                         return pipelineEmitWithComments;
95403                     }
95404                 // falls through
95405                 case 3 /* SourceMaps */:
95406                     if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
95407                         return pipelineEmitWithSourceMap;
95408                     }
95409                 // falls through
95410                 case 4 /* Emit */:
95411                     return pipelineEmitWithHint;
95412                 default:
95413                     return ts.Debug.assertNever(phase);
95414             }
95415         }
95416         function getNextPipelinePhase(currentPhase, emitHint, node) {
95417             return getPipelinePhase(currentPhase + 1, emitHint, node);
95418         }
95419         function pipelineEmitWithNotification(hint, node) {
95420             ts.Debug.assert(lastNode === node);
95421             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
95422             onEmitNode(hint, node, pipelinePhase);
95423             ts.Debug.assert(lastNode === node);
95424         }
95425         function pipelineEmitWithHint(hint, node) {
95426             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95427             if (hint === 0 /* SourceFile */)
95428                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
95429             if (hint === 2 /* IdentifierName */)
95430                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
95431             if (hint === 6 /* JsxAttributeValue */)
95432                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
95433             if (hint === 3 /* MappedTypeParameter */)
95434                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
95435             if (hint === 5 /* EmbeddedStatement */) {
95436                 ts.Debug.assertNode(node, ts.isEmptyStatement);
95437                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
95438             }
95439             if (hint === 4 /* Unspecified */) {
95440                 if (ts.isKeyword(node.kind))
95441                     return writeTokenNode(node, writeKeyword);
95442                 switch (node.kind) {
95443                     // Pseudo-literals
95444                     case 15 /* TemplateHead */:
95445                     case 16 /* TemplateMiddle */:
95446                     case 17 /* TemplateTail */:
95447                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95448                     case 292 /* UnparsedSource */:
95449                     case 286 /* UnparsedPrepend */:
95450                         return emitUnparsedSourceOrPrepend(node);
95451                     case 285 /* UnparsedPrologue */:
95452                         return writeUnparsedNode(node);
95453                     case 287 /* UnparsedText */:
95454                     case 288 /* UnparsedInternalText */:
95455                         return emitUnparsedTextLike(node);
95456                     case 289 /* UnparsedSyntheticReference */:
95457                         return emitUnparsedSyntheticReference(node);
95458                     // Identifiers
95459                     case 75 /* Identifier */:
95460                         return emitIdentifier(node);
95461                     // PrivateIdentifiers
95462                     case 76 /* PrivateIdentifier */:
95463                         return emitPrivateIdentifier(node);
95464                     // Parse tree nodes
95465                     // Names
95466                     case 153 /* QualifiedName */:
95467                         return emitQualifiedName(node);
95468                     case 154 /* ComputedPropertyName */:
95469                         return emitComputedPropertyName(node);
95470                     // Signature elements
95471                     case 155 /* TypeParameter */:
95472                         return emitTypeParameter(node);
95473                     case 156 /* Parameter */:
95474                         return emitParameter(node);
95475                     case 157 /* Decorator */:
95476                         return emitDecorator(node);
95477                     // Type members
95478                     case 158 /* PropertySignature */:
95479                         return emitPropertySignature(node);
95480                     case 159 /* PropertyDeclaration */:
95481                         return emitPropertyDeclaration(node);
95482                     case 160 /* MethodSignature */:
95483                         return emitMethodSignature(node);
95484                     case 161 /* MethodDeclaration */:
95485                         return emitMethodDeclaration(node);
95486                     case 162 /* Constructor */:
95487                         return emitConstructor(node);
95488                     case 163 /* GetAccessor */:
95489                     case 164 /* SetAccessor */:
95490                         return emitAccessorDeclaration(node);
95491                     case 165 /* CallSignature */:
95492                         return emitCallSignature(node);
95493                     case 166 /* ConstructSignature */:
95494                         return emitConstructSignature(node);
95495                     case 167 /* IndexSignature */:
95496                         return emitIndexSignature(node);
95497                     // Types
95498                     case 168 /* TypePredicate */:
95499                         return emitTypePredicate(node);
95500                     case 169 /* TypeReference */:
95501                         return emitTypeReference(node);
95502                     case 170 /* FunctionType */:
95503                         return emitFunctionType(node);
95504                     case 300 /* JSDocFunctionType */:
95505                         return emitJSDocFunctionType(node);
95506                     case 171 /* ConstructorType */:
95507                         return emitConstructorType(node);
95508                     case 172 /* TypeQuery */:
95509                         return emitTypeQuery(node);
95510                     case 173 /* TypeLiteral */:
95511                         return emitTypeLiteral(node);
95512                     case 174 /* ArrayType */:
95513                         return emitArrayType(node);
95514                     case 175 /* TupleType */:
95515                         return emitTupleType(node);
95516                     case 176 /* OptionalType */:
95517                         return emitOptionalType(node);
95518                     case 178 /* UnionType */:
95519                         return emitUnionType(node);
95520                     case 179 /* IntersectionType */:
95521                         return emitIntersectionType(node);
95522                     case 180 /* ConditionalType */:
95523                         return emitConditionalType(node);
95524                     case 181 /* InferType */:
95525                         return emitInferType(node);
95526                     case 182 /* ParenthesizedType */:
95527                         return emitParenthesizedType(node);
95528                     case 216 /* ExpressionWithTypeArguments */:
95529                         return emitExpressionWithTypeArguments(node);
95530                     case 183 /* ThisType */:
95531                         return emitThisType();
95532                     case 184 /* TypeOperator */:
95533                         return emitTypeOperator(node);
95534                     case 185 /* IndexedAccessType */:
95535                         return emitIndexedAccessType(node);
95536                     case 186 /* MappedType */:
95537                         return emitMappedType(node);
95538                     case 187 /* LiteralType */:
95539                         return emitLiteralType(node);
95540                     case 188 /* ImportType */:
95541                         return emitImportTypeNode(node);
95542                     case 295 /* JSDocAllType */:
95543                         writePunctuation("*");
95544                         return;
95545                     case 296 /* JSDocUnknownType */:
95546                         writePunctuation("?");
95547                         return;
95548                     case 297 /* JSDocNullableType */:
95549                         return emitJSDocNullableType(node);
95550                     case 298 /* JSDocNonNullableType */:
95551                         return emitJSDocNonNullableType(node);
95552                     case 299 /* JSDocOptionalType */:
95553                         return emitJSDocOptionalType(node);
95554                     case 177 /* RestType */:
95555                     case 301 /* JSDocVariadicType */:
95556                         return emitRestOrJSDocVariadicType(node);
95557                     // Binding patterns
95558                     case 189 /* ObjectBindingPattern */:
95559                         return emitObjectBindingPattern(node);
95560                     case 190 /* ArrayBindingPattern */:
95561                         return emitArrayBindingPattern(node);
95562                     case 191 /* BindingElement */:
95563                         return emitBindingElement(node);
95564                     // Misc
95565                     case 221 /* TemplateSpan */:
95566                         return emitTemplateSpan(node);
95567                     case 222 /* SemicolonClassElement */:
95568                         return emitSemicolonClassElement();
95569                     // Statements
95570                     case 223 /* Block */:
95571                         return emitBlock(node);
95572                     case 225 /* VariableStatement */:
95573                         return emitVariableStatement(node);
95574                     case 224 /* EmptyStatement */:
95575                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
95576                     case 226 /* ExpressionStatement */:
95577                         return emitExpressionStatement(node);
95578                     case 227 /* IfStatement */:
95579                         return emitIfStatement(node);
95580                     case 228 /* DoStatement */:
95581                         return emitDoStatement(node);
95582                     case 229 /* WhileStatement */:
95583                         return emitWhileStatement(node);
95584                     case 230 /* ForStatement */:
95585                         return emitForStatement(node);
95586                     case 231 /* ForInStatement */:
95587                         return emitForInStatement(node);
95588                     case 232 /* ForOfStatement */:
95589                         return emitForOfStatement(node);
95590                     case 233 /* ContinueStatement */:
95591                         return emitContinueStatement(node);
95592                     case 234 /* BreakStatement */:
95593                         return emitBreakStatement(node);
95594                     case 235 /* ReturnStatement */:
95595                         return emitReturnStatement(node);
95596                     case 236 /* WithStatement */:
95597                         return emitWithStatement(node);
95598                     case 237 /* SwitchStatement */:
95599                         return emitSwitchStatement(node);
95600                     case 238 /* LabeledStatement */:
95601                         return emitLabeledStatement(node);
95602                     case 239 /* ThrowStatement */:
95603                         return emitThrowStatement(node);
95604                     case 240 /* TryStatement */:
95605                         return emitTryStatement(node);
95606                     case 241 /* DebuggerStatement */:
95607                         return emitDebuggerStatement(node);
95608                     // Declarations
95609                     case 242 /* VariableDeclaration */:
95610                         return emitVariableDeclaration(node);
95611                     case 243 /* VariableDeclarationList */:
95612                         return emitVariableDeclarationList(node);
95613                     case 244 /* FunctionDeclaration */:
95614                         return emitFunctionDeclaration(node);
95615                     case 245 /* ClassDeclaration */:
95616                         return emitClassDeclaration(node);
95617                     case 246 /* InterfaceDeclaration */:
95618                         return emitInterfaceDeclaration(node);
95619                     case 247 /* TypeAliasDeclaration */:
95620                         return emitTypeAliasDeclaration(node);
95621                     case 248 /* EnumDeclaration */:
95622                         return emitEnumDeclaration(node);
95623                     case 249 /* ModuleDeclaration */:
95624                         return emitModuleDeclaration(node);
95625                     case 250 /* ModuleBlock */:
95626                         return emitModuleBlock(node);
95627                     case 251 /* CaseBlock */:
95628                         return emitCaseBlock(node);
95629                     case 252 /* NamespaceExportDeclaration */:
95630                         return emitNamespaceExportDeclaration(node);
95631                     case 253 /* ImportEqualsDeclaration */:
95632                         return emitImportEqualsDeclaration(node);
95633                     case 254 /* ImportDeclaration */:
95634                         return emitImportDeclaration(node);
95635                     case 255 /* ImportClause */:
95636                         return emitImportClause(node);
95637                     case 256 /* NamespaceImport */:
95638                         return emitNamespaceImport(node);
95639                     case 262 /* NamespaceExport */:
95640                         return emitNamespaceExport(node);
95641                     case 257 /* NamedImports */:
95642                         return emitNamedImports(node);
95643                     case 258 /* ImportSpecifier */:
95644                         return emitImportSpecifier(node);
95645                     case 259 /* ExportAssignment */:
95646                         return emitExportAssignment(node);
95647                     case 260 /* ExportDeclaration */:
95648                         return emitExportDeclaration(node);
95649                     case 261 /* NamedExports */:
95650                         return emitNamedExports(node);
95651                     case 263 /* ExportSpecifier */:
95652                         return emitExportSpecifier(node);
95653                     case 264 /* MissingDeclaration */:
95654                         return;
95655                     // Module references
95656                     case 265 /* ExternalModuleReference */:
95657                         return emitExternalModuleReference(node);
95658                     // JSX (non-expression)
95659                     case 11 /* JsxText */:
95660                         return emitJsxText(node);
95661                     case 268 /* JsxOpeningElement */:
95662                     case 271 /* JsxOpeningFragment */:
95663                         return emitJsxOpeningElementOrFragment(node);
95664                     case 269 /* JsxClosingElement */:
95665                     case 272 /* JsxClosingFragment */:
95666                         return emitJsxClosingElementOrFragment(node);
95667                     case 273 /* JsxAttribute */:
95668                         return emitJsxAttribute(node);
95669                     case 274 /* JsxAttributes */:
95670                         return emitJsxAttributes(node);
95671                     case 275 /* JsxSpreadAttribute */:
95672                         return emitJsxSpreadAttribute(node);
95673                     case 276 /* JsxExpression */:
95674                         return emitJsxExpression(node);
95675                     // Clauses
95676                     case 277 /* CaseClause */:
95677                         return emitCaseClause(node);
95678                     case 278 /* DefaultClause */:
95679                         return emitDefaultClause(node);
95680                     case 279 /* HeritageClause */:
95681                         return emitHeritageClause(node);
95682                     case 280 /* CatchClause */:
95683                         return emitCatchClause(node);
95684                     // Property assignments
95685                     case 281 /* PropertyAssignment */:
95686                         return emitPropertyAssignment(node);
95687                     case 282 /* ShorthandPropertyAssignment */:
95688                         return emitShorthandPropertyAssignment(node);
95689                     case 283 /* SpreadAssignment */:
95690                         return emitSpreadAssignment(node);
95691                     // Enum
95692                     case 284 /* EnumMember */:
95693                         return emitEnumMember(node);
95694                     // JSDoc nodes (only used in codefixes currently)
95695                     case 317 /* JSDocParameterTag */:
95696                     case 323 /* JSDocPropertyTag */:
95697                         return emitJSDocPropertyLikeTag(node);
95698                     case 318 /* JSDocReturnTag */:
95699                     case 320 /* JSDocTypeTag */:
95700                     case 319 /* JSDocThisTag */:
95701                     case 316 /* JSDocEnumTag */:
95702                         return emitJSDocSimpleTypedTag(node);
95703                     case 308 /* JSDocImplementsTag */:
95704                     case 307 /* JSDocAugmentsTag */:
95705                         return emitJSDocHeritageTag(node);
95706                     case 321 /* JSDocTemplateTag */:
95707                         return emitJSDocTemplateTag(node);
95708                     case 322 /* JSDocTypedefTag */:
95709                         return emitJSDocTypedefTag(node);
95710                     case 315 /* JSDocCallbackTag */:
95711                         return emitJSDocCallbackTag(node);
95712                     case 305 /* JSDocSignature */:
95713                         return emitJSDocSignature(node);
95714                     case 304 /* JSDocTypeLiteral */:
95715                         return emitJSDocTypeLiteral(node);
95716                     case 310 /* JSDocClassTag */:
95717                     case 306 /* JSDocTag */:
95718                         return emitJSDocSimpleTag(node);
95719                     case 303 /* JSDocComment */:
95720                         return emitJSDoc(node);
95721                     // Transformation nodes (ignored)
95722                 }
95723                 if (ts.isExpression(node)) {
95724                     hint = 1 /* Expression */;
95725                     if (substituteNode !== ts.noEmitSubstitution) {
95726                         lastSubstitution = node = substituteNode(hint, node);
95727                     }
95728                 }
95729                 else if (ts.isToken(node)) {
95730                     return writeTokenNode(node, writePunctuation);
95731                 }
95732             }
95733             if (hint === 1 /* Expression */) {
95734                 switch (node.kind) {
95735                     // Literals
95736                     case 8 /* NumericLiteral */:
95737                     case 9 /* BigIntLiteral */:
95738                         return emitNumericOrBigIntLiteral(node);
95739                     case 10 /* StringLiteral */:
95740                     case 13 /* RegularExpressionLiteral */:
95741                     case 14 /* NoSubstitutionTemplateLiteral */:
95742                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95743                     // Identifiers
95744                     case 75 /* Identifier */:
95745                         return emitIdentifier(node);
95746                     // Reserved words
95747                     case 91 /* FalseKeyword */:
95748                     case 100 /* NullKeyword */:
95749                     case 102 /* SuperKeyword */:
95750                     case 106 /* TrueKeyword */:
95751                     case 104 /* ThisKeyword */:
95752                     case 96 /* ImportKeyword */:
95753                         writeTokenNode(node, writeKeyword);
95754                         return;
95755                     // Expressions
95756                     case 192 /* ArrayLiteralExpression */:
95757                         return emitArrayLiteralExpression(node);
95758                     case 193 /* ObjectLiteralExpression */:
95759                         return emitObjectLiteralExpression(node);
95760                     case 194 /* PropertyAccessExpression */:
95761                         return emitPropertyAccessExpression(node);
95762                     case 195 /* ElementAccessExpression */:
95763                         return emitElementAccessExpression(node);
95764                     case 196 /* CallExpression */:
95765                         return emitCallExpression(node);
95766                     case 197 /* NewExpression */:
95767                         return emitNewExpression(node);
95768                     case 198 /* TaggedTemplateExpression */:
95769                         return emitTaggedTemplateExpression(node);
95770                     case 199 /* TypeAssertionExpression */:
95771                         return emitTypeAssertionExpression(node);
95772                     case 200 /* ParenthesizedExpression */:
95773                         return emitParenthesizedExpression(node);
95774                     case 201 /* FunctionExpression */:
95775                         return emitFunctionExpression(node);
95776                     case 202 /* ArrowFunction */:
95777                         return emitArrowFunction(node);
95778                     case 203 /* DeleteExpression */:
95779                         return emitDeleteExpression(node);
95780                     case 204 /* TypeOfExpression */:
95781                         return emitTypeOfExpression(node);
95782                     case 205 /* VoidExpression */:
95783                         return emitVoidExpression(node);
95784                     case 206 /* AwaitExpression */:
95785                         return emitAwaitExpression(node);
95786                     case 207 /* PrefixUnaryExpression */:
95787                         return emitPrefixUnaryExpression(node);
95788                     case 208 /* PostfixUnaryExpression */:
95789                         return emitPostfixUnaryExpression(node);
95790                     case 209 /* BinaryExpression */:
95791                         return emitBinaryExpression(node);
95792                     case 210 /* ConditionalExpression */:
95793                         return emitConditionalExpression(node);
95794                     case 211 /* TemplateExpression */:
95795                         return emitTemplateExpression(node);
95796                     case 212 /* YieldExpression */:
95797                         return emitYieldExpression(node);
95798                     case 213 /* SpreadElement */:
95799                         return emitSpreadExpression(node);
95800                     case 214 /* ClassExpression */:
95801                         return emitClassExpression(node);
95802                     case 215 /* OmittedExpression */:
95803                         return;
95804                     case 217 /* AsExpression */:
95805                         return emitAsExpression(node);
95806                     case 218 /* NonNullExpression */:
95807                         return emitNonNullExpression(node);
95808                     case 219 /* MetaProperty */:
95809                         return emitMetaProperty(node);
95810                     // JSX
95811                     case 266 /* JsxElement */:
95812                         return emitJsxElement(node);
95813                     case 267 /* JsxSelfClosingElement */:
95814                         return emitJsxSelfClosingElement(node);
95815                     case 270 /* JsxFragment */:
95816                         return emitJsxFragment(node);
95817                     // Transformation nodes
95818                     case 326 /* PartiallyEmittedExpression */:
95819                         return emitPartiallyEmittedExpression(node);
95820                     case 327 /* CommaListExpression */:
95821                         return emitCommaList(node);
95822                 }
95823             }
95824         }
95825         function emitMappedTypeParameter(node) {
95826             emit(node.name);
95827             writeSpace();
95828             writeKeyword("in");
95829             writeSpace();
95830             emit(node.constraint);
95831         }
95832         function pipelineEmitWithSubstitution(hint, node) {
95833             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95834             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
95835             pipelinePhase(hint, lastSubstitution);
95836             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95837         }
95838         function getHelpersFromBundledSourceFiles(bundle) {
95839             var result;
95840             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
95841                 return undefined;
95842             }
95843             var bundledHelpers = ts.createMap();
95844             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
95845                 var sourceFile = _b[_a];
95846                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
95847                 var helpers = getSortedEmitHelpers(sourceFile);
95848                 if (!helpers)
95849                     continue;
95850                 for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
95851                     var helper = helpers_4[_c];
95852                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
95853                         bundledHelpers.set(helper.name, true);
95854                         (result || (result = [])).push(helper.name);
95855                     }
95856                 }
95857             }
95858             return result;
95859         }
95860         function emitHelpers(node) {
95861             var helpersEmitted = false;
95862             var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
95863             if (bundle && moduleKind === ts.ModuleKind.None) {
95864                 return;
95865             }
95866             var numPrepends = bundle ? bundle.prepends.length : 0;
95867             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
95868             for (var i = 0; i < numNodes; i++) {
95869                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
95870                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
95871                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
95872                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
95873                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
95874                 if (helpers) {
95875                     for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
95876                         var helper = helpers_5[_a];
95877                         if (!helper.scoped) {
95878                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
95879                             // option is set, or if it can be imported and the importHelpers compiler
95880                             // option is set.
95881                             if (shouldSkip)
95882                                 continue;
95883                             // Skip the helper if it can be bundled but hasn't already been emitted and we
95884                             // are emitting a bundled module.
95885                             if (shouldBundle) {
95886                                 if (bundledHelpers.get(helper.name)) {
95887                                     continue;
95888                                 }
95889                                 bundledHelpers.set(helper.name, true);
95890                             }
95891                         }
95892                         else if (bundle) {
95893                             // Skip the helper if it is scoped and we are emitting bundled helpers
95894                             continue;
95895                         }
95896                         var pos = getTextPosWithWriteLine();
95897                         if (typeof helper.text === "string") {
95898                             writeLines(helper.text);
95899                         }
95900                         else {
95901                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
95902                         }
95903                         if (bundleFileInfo)
95904                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
95905                         helpersEmitted = true;
95906                     }
95907                 }
95908             }
95909             return helpersEmitted;
95910         }
95911         function getSortedEmitHelpers(node) {
95912             var helpers = ts.getEmitHelpers(node);
95913             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
95914         }
95915         //
95916         // Literals/Pseudo-literals
95917         //
95918         // SyntaxKind.NumericLiteral
95919         // SyntaxKind.BigIntLiteral
95920         function emitNumericOrBigIntLiteral(node) {
95921             emitLiteral(node, /*jsxAttributeEscape*/ false);
95922         }
95923         // SyntaxKind.StringLiteral
95924         // SyntaxKind.RegularExpressionLiteral
95925         // SyntaxKind.NoSubstitutionTemplateLiteral
95926         // SyntaxKind.TemplateHead
95927         // SyntaxKind.TemplateMiddle
95928         // SyntaxKind.TemplateTail
95929         function emitLiteral(node, jsxAttributeEscape) {
95930             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
95931             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
95932                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
95933                 writeLiteral(text);
95934             }
95935             else {
95936                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
95937                 writeStringLiteral(text);
95938             }
95939         }
95940         // SyntaxKind.UnparsedSource
95941         // SyntaxKind.UnparsedPrepend
95942         function emitUnparsedSourceOrPrepend(unparsed) {
95943             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
95944                 var text = _b[_a];
95945                 writeLine();
95946                 emit(text);
95947             }
95948         }
95949         // SyntaxKind.UnparsedPrologue
95950         // SyntaxKind.UnparsedText
95951         // SyntaxKind.UnparsedInternal
95952         // SyntaxKind.UnparsedSyntheticReference
95953         function writeUnparsedNode(unparsed) {
95954             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
95955         }
95956         // SyntaxKind.UnparsedText
95957         // SyntaxKind.UnparsedInternal
95958         function emitUnparsedTextLike(unparsed) {
95959             var pos = getTextPosWithWriteLine();
95960             writeUnparsedNode(unparsed);
95961             if (bundleFileInfo) {
95962                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
95963                     "text" /* Text */ :
95964                     "internal" /* Internal */);
95965             }
95966         }
95967         // SyntaxKind.UnparsedSyntheticReference
95968         function emitUnparsedSyntheticReference(unparsed) {
95969             var pos = getTextPosWithWriteLine();
95970             writeUnparsedNode(unparsed);
95971             if (bundleFileInfo) {
95972                 var section = ts.clone(unparsed.section);
95973                 section.pos = pos;
95974                 section.end = writer.getTextPos();
95975                 bundleFileInfo.sections.push(section);
95976             }
95977         }
95978         //
95979         // Identifiers
95980         //
95981         function emitIdentifier(node) {
95982             var writeText = node.symbol ? writeSymbol : write;
95983             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95984             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
95985         }
95986         //
95987         // Names
95988         //
95989         function emitPrivateIdentifier(node) {
95990             var writeText = node.symbol ? writeSymbol : write;
95991             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95992         }
95993         function emitQualifiedName(node) {
95994             emitEntityName(node.left);
95995             writePunctuation(".");
95996             emit(node.right);
95997         }
95998         function emitEntityName(node) {
95999             if (node.kind === 75 /* Identifier */) {
96000                 emitExpression(node);
96001             }
96002             else {
96003                 emit(node);
96004             }
96005         }
96006         function emitComputedPropertyName(node) {
96007             writePunctuation("[");
96008             emitExpression(node.expression);
96009             writePunctuation("]");
96010         }
96011         //
96012         // Signature elements
96013         //
96014         function emitTypeParameter(node) {
96015             emit(node.name);
96016             if (node.constraint) {
96017                 writeSpace();
96018                 writeKeyword("extends");
96019                 writeSpace();
96020                 emit(node.constraint);
96021             }
96022             if (node.default) {
96023                 writeSpace();
96024                 writeOperator("=");
96025                 writeSpace();
96026                 emit(node.default);
96027             }
96028         }
96029         function emitParameter(node) {
96030             emitDecorators(node, node.decorators);
96031             emitModifiers(node, node.modifiers);
96032             emit(node.dotDotDotToken);
96033             emitNodeWithWriter(node.name, writeParameter);
96034             emit(node.questionToken);
96035             if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
96036                 emit(node.type);
96037             }
96038             else {
96039                 emitTypeAnnotation(node.type);
96040             }
96041             // 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.
96042             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);
96043         }
96044         function emitDecorator(decorator) {
96045             writePunctuation("@");
96046             emitExpression(decorator.expression);
96047         }
96048         //
96049         // Type members
96050         //
96051         function emitPropertySignature(node) {
96052             emitDecorators(node, node.decorators);
96053             emitModifiers(node, node.modifiers);
96054             emitNodeWithWriter(node.name, writeProperty);
96055             emit(node.questionToken);
96056             emitTypeAnnotation(node.type);
96057             writeTrailingSemicolon();
96058         }
96059         function emitPropertyDeclaration(node) {
96060             emitDecorators(node, node.decorators);
96061             emitModifiers(node, node.modifiers);
96062             emit(node.name);
96063             emit(node.questionToken);
96064             emit(node.exclamationToken);
96065             emitTypeAnnotation(node.type);
96066             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
96067             writeTrailingSemicolon();
96068         }
96069         function emitMethodSignature(node) {
96070             pushNameGenerationScope(node);
96071             emitDecorators(node, node.decorators);
96072             emitModifiers(node, node.modifiers);
96073             emit(node.name);
96074             emit(node.questionToken);
96075             emitTypeParameters(node, node.typeParameters);
96076             emitParameters(node, node.parameters);
96077             emitTypeAnnotation(node.type);
96078             writeTrailingSemicolon();
96079             popNameGenerationScope(node);
96080         }
96081         function emitMethodDeclaration(node) {
96082             emitDecorators(node, node.decorators);
96083             emitModifiers(node, node.modifiers);
96084             emit(node.asteriskToken);
96085             emit(node.name);
96086             emit(node.questionToken);
96087             emitSignatureAndBody(node, emitSignatureHead);
96088         }
96089         function emitConstructor(node) {
96090             emitModifiers(node, node.modifiers);
96091             writeKeyword("constructor");
96092             emitSignatureAndBody(node, emitSignatureHead);
96093         }
96094         function emitAccessorDeclaration(node) {
96095             emitDecorators(node, node.decorators);
96096             emitModifiers(node, node.modifiers);
96097             writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
96098             writeSpace();
96099             emit(node.name);
96100             emitSignatureAndBody(node, emitSignatureHead);
96101         }
96102         function emitCallSignature(node) {
96103             pushNameGenerationScope(node);
96104             emitDecorators(node, node.decorators);
96105             emitModifiers(node, node.modifiers);
96106             emitTypeParameters(node, node.typeParameters);
96107             emitParameters(node, node.parameters);
96108             emitTypeAnnotation(node.type);
96109             writeTrailingSemicolon();
96110             popNameGenerationScope(node);
96111         }
96112         function emitConstructSignature(node) {
96113             pushNameGenerationScope(node);
96114             emitDecorators(node, node.decorators);
96115             emitModifiers(node, node.modifiers);
96116             writeKeyword("new");
96117             writeSpace();
96118             emitTypeParameters(node, node.typeParameters);
96119             emitParameters(node, node.parameters);
96120             emitTypeAnnotation(node.type);
96121             writeTrailingSemicolon();
96122             popNameGenerationScope(node);
96123         }
96124         function emitIndexSignature(node) {
96125             emitDecorators(node, node.decorators);
96126             emitModifiers(node, node.modifiers);
96127             emitParametersForIndexSignature(node, node.parameters);
96128             emitTypeAnnotation(node.type);
96129             writeTrailingSemicolon();
96130         }
96131         function emitSemicolonClassElement() {
96132             writeTrailingSemicolon();
96133         }
96134         //
96135         // Types
96136         //
96137         function emitTypePredicate(node) {
96138             if (node.assertsModifier) {
96139                 emit(node.assertsModifier);
96140                 writeSpace();
96141             }
96142             emit(node.parameterName);
96143             if (node.type) {
96144                 writeSpace();
96145                 writeKeyword("is");
96146                 writeSpace();
96147                 emit(node.type);
96148             }
96149         }
96150         function emitTypeReference(node) {
96151             emit(node.typeName);
96152             emitTypeArguments(node, node.typeArguments);
96153         }
96154         function emitFunctionType(node) {
96155             pushNameGenerationScope(node);
96156             emitTypeParameters(node, node.typeParameters);
96157             emitParametersForArrow(node, node.parameters);
96158             writeSpace();
96159             writePunctuation("=>");
96160             writeSpace();
96161             emit(node.type);
96162             popNameGenerationScope(node);
96163         }
96164         function emitJSDocFunctionType(node) {
96165             writeKeyword("function");
96166             emitParameters(node, node.parameters);
96167             writePunctuation(":");
96168             emit(node.type);
96169         }
96170         function emitJSDocNullableType(node) {
96171             writePunctuation("?");
96172             emit(node.type);
96173         }
96174         function emitJSDocNonNullableType(node) {
96175             writePunctuation("!");
96176             emit(node.type);
96177         }
96178         function emitJSDocOptionalType(node) {
96179             emit(node.type);
96180             writePunctuation("=");
96181         }
96182         function emitConstructorType(node) {
96183             pushNameGenerationScope(node);
96184             writeKeyword("new");
96185             writeSpace();
96186             emitTypeParameters(node, node.typeParameters);
96187             emitParameters(node, node.parameters);
96188             writeSpace();
96189             writePunctuation("=>");
96190             writeSpace();
96191             emit(node.type);
96192             popNameGenerationScope(node);
96193         }
96194         function emitTypeQuery(node) {
96195             writeKeyword("typeof");
96196             writeSpace();
96197             emit(node.exprName);
96198         }
96199         function emitTypeLiteral(node) {
96200             writePunctuation("{");
96201             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
96202             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
96203             writePunctuation("}");
96204         }
96205         function emitArrayType(node) {
96206             emit(node.elementType);
96207             writePunctuation("[");
96208             writePunctuation("]");
96209         }
96210         function emitRestOrJSDocVariadicType(node) {
96211             writePunctuation("...");
96212             emit(node.type);
96213         }
96214         function emitTupleType(node) {
96215             writePunctuation("[");
96216             emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
96217             writePunctuation("]");
96218         }
96219         function emitOptionalType(node) {
96220             emit(node.type);
96221             writePunctuation("?");
96222         }
96223         function emitUnionType(node) {
96224             emitList(node, node.types, 516 /* UnionTypeConstituents */);
96225         }
96226         function emitIntersectionType(node) {
96227             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
96228         }
96229         function emitConditionalType(node) {
96230             emit(node.checkType);
96231             writeSpace();
96232             writeKeyword("extends");
96233             writeSpace();
96234             emit(node.extendsType);
96235             writeSpace();
96236             writePunctuation("?");
96237             writeSpace();
96238             emit(node.trueType);
96239             writeSpace();
96240             writePunctuation(":");
96241             writeSpace();
96242             emit(node.falseType);
96243         }
96244         function emitInferType(node) {
96245             writeKeyword("infer");
96246             writeSpace();
96247             emit(node.typeParameter);
96248         }
96249         function emitParenthesizedType(node) {
96250             writePunctuation("(");
96251             emit(node.type);
96252             writePunctuation(")");
96253         }
96254         function emitThisType() {
96255             writeKeyword("this");
96256         }
96257         function emitTypeOperator(node) {
96258             writeTokenText(node.operator, writeKeyword);
96259             writeSpace();
96260             emit(node.type);
96261         }
96262         function emitIndexedAccessType(node) {
96263             emit(node.objectType);
96264             writePunctuation("[");
96265             emit(node.indexType);
96266             writePunctuation("]");
96267         }
96268         function emitMappedType(node) {
96269             var emitFlags = ts.getEmitFlags(node);
96270             writePunctuation("{");
96271             if (emitFlags & 1 /* SingleLine */) {
96272                 writeSpace();
96273             }
96274             else {
96275                 writeLine();
96276                 increaseIndent();
96277             }
96278             if (node.readonlyToken) {
96279                 emit(node.readonlyToken);
96280                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
96281                     writeKeyword("readonly");
96282                 }
96283                 writeSpace();
96284             }
96285             writePunctuation("[");
96286             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
96287             writePunctuation("]");
96288             if (node.questionToken) {
96289                 emit(node.questionToken);
96290                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
96291                     writePunctuation("?");
96292                 }
96293             }
96294             writePunctuation(":");
96295             writeSpace();
96296             emit(node.type);
96297             writeTrailingSemicolon();
96298             if (emitFlags & 1 /* SingleLine */) {
96299                 writeSpace();
96300             }
96301             else {
96302                 writeLine();
96303                 decreaseIndent();
96304             }
96305             writePunctuation("}");
96306         }
96307         function emitLiteralType(node) {
96308             emitExpression(node.literal);
96309         }
96310         function emitImportTypeNode(node) {
96311             if (node.isTypeOf) {
96312                 writeKeyword("typeof");
96313                 writeSpace();
96314             }
96315             writeKeyword("import");
96316             writePunctuation("(");
96317             emit(node.argument);
96318             writePunctuation(")");
96319             if (node.qualifier) {
96320                 writePunctuation(".");
96321                 emit(node.qualifier);
96322             }
96323             emitTypeArguments(node, node.typeArguments);
96324         }
96325         //
96326         // Binding patterns
96327         //
96328         function emitObjectBindingPattern(node) {
96329             writePunctuation("{");
96330             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
96331             writePunctuation("}");
96332         }
96333         function emitArrayBindingPattern(node) {
96334             writePunctuation("[");
96335             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
96336             writePunctuation("]");
96337         }
96338         function emitBindingElement(node) {
96339             emit(node.dotDotDotToken);
96340             if (node.propertyName) {
96341                 emit(node.propertyName);
96342                 writePunctuation(":");
96343                 writeSpace();
96344             }
96345             emit(node.name);
96346             emitInitializer(node.initializer, node.name.end, node);
96347         }
96348         //
96349         // Expressions
96350         //
96351         function emitArrayLiteralExpression(node) {
96352             var elements = node.elements;
96353             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96354             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
96355         }
96356         function emitObjectLiteralExpression(node) {
96357             ts.forEach(node.properties, generateMemberNames);
96358             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96359             if (indentedFlag) {
96360                 increaseIndent();
96361             }
96362             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96363             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
96364             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
96365             if (indentedFlag) {
96366                 decreaseIndent();
96367             }
96368         }
96369         function emitPropertyAccessExpression(node) {
96370             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
96371             var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
96372             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
96373             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
96374             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
96375             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
96376                 mayNeedDotDotForPropertyAccess(expression) &&
96377                 !writer.hasTrailingComment() &&
96378                 !writer.hasTrailingWhitespace();
96379             if (shouldEmitDotDot) {
96380                 writePunctuation(".");
96381             }
96382             if (node.questionDotToken) {
96383                 emit(token);
96384             }
96385             else {
96386                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
96387             }
96388             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
96389             emit(node.name);
96390             decreaseIndentIf(linesBeforeDot, linesAfterDot);
96391         }
96392         // 1..toString is a valid property access, emit a dot after the literal
96393         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
96394         function mayNeedDotDotForPropertyAccess(expression) {
96395             expression = ts.skipPartiallyEmittedExpressions(expression);
96396             if (ts.isNumericLiteral(expression)) {
96397                 // check if numeric literal is a decimal literal that was originally written with a dot
96398                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
96399                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
96400                 // if the expression doesn't have any comments that will be emitted.
96401                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
96402             }
96403             else if (ts.isAccessExpression(expression)) {
96404                 // check if constant enum value is integer
96405                 var constantValue = ts.getConstantValue(expression);
96406                 // isFinite handles cases when constantValue is undefined
96407                 return typeof constantValue === "number" && isFinite(constantValue)
96408                     && Math.floor(constantValue) === constantValue;
96409             }
96410         }
96411         function emitElementAccessExpression(node) {
96412             emitExpression(node.expression);
96413             emit(node.questionDotToken);
96414             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
96415             emitExpression(node.argumentExpression);
96416             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
96417         }
96418         function emitCallExpression(node) {
96419             emitExpression(node.expression);
96420             emit(node.questionDotToken);
96421             emitTypeArguments(node, node.typeArguments);
96422             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
96423         }
96424         function emitNewExpression(node) {
96425             emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
96426             writeSpace();
96427             emitExpression(node.expression);
96428             emitTypeArguments(node, node.typeArguments);
96429             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
96430         }
96431         function emitTaggedTemplateExpression(node) {
96432             emitExpression(node.tag);
96433             emitTypeArguments(node, node.typeArguments);
96434             writeSpace();
96435             emitExpression(node.template);
96436         }
96437         function emitTypeAssertionExpression(node) {
96438             writePunctuation("<");
96439             emit(node.type);
96440             writePunctuation(">");
96441             emitExpression(node.expression);
96442         }
96443         function emitParenthesizedExpression(node) {
96444             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
96445             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
96446             emitExpression(node.expression);
96447             writeLineSeparatorsAfter(node.expression, node);
96448             decreaseIndentIf(indented);
96449             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
96450         }
96451         function emitFunctionExpression(node) {
96452             generateNameIfNeeded(node.name);
96453             emitFunctionDeclarationOrExpression(node);
96454         }
96455         function emitArrowFunction(node) {
96456             emitDecorators(node, node.decorators);
96457             emitModifiers(node, node.modifiers);
96458             emitSignatureAndBody(node, emitArrowFunctionHead);
96459         }
96460         function emitArrowFunctionHead(node) {
96461             emitTypeParameters(node, node.typeParameters);
96462             emitParametersForArrow(node, node.parameters);
96463             emitTypeAnnotation(node.type);
96464             writeSpace();
96465             emit(node.equalsGreaterThanToken);
96466         }
96467         function emitDeleteExpression(node) {
96468             emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
96469             writeSpace();
96470             emitExpression(node.expression);
96471         }
96472         function emitTypeOfExpression(node) {
96473             emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
96474             writeSpace();
96475             emitExpression(node.expression);
96476         }
96477         function emitVoidExpression(node) {
96478             emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
96479             writeSpace();
96480             emitExpression(node.expression);
96481         }
96482         function emitAwaitExpression(node) {
96483             emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
96484             writeSpace();
96485             emitExpression(node.expression);
96486         }
96487         function emitPrefixUnaryExpression(node) {
96488             writeTokenText(node.operator, writeOperator);
96489             if (shouldEmitWhitespaceBeforeOperand(node)) {
96490                 writeSpace();
96491             }
96492             emitExpression(node.operand);
96493         }
96494         function shouldEmitWhitespaceBeforeOperand(node) {
96495             // In some cases, we need to emit a space between the operator and the operand. One obvious case
96496             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
96497             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
96498             // are just for clarity of exposition, and not part of the source code):
96499             //
96500             //  (+(+1))
96501             //  (+(++1))
96502             //
96503             // We need to emit a space in both cases. In the first case, the absence of a space will make
96504             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
96505             // expression a prefix increment whose operand is a plus expression - (++(+x))
96506             // The same is true of minus of course.
96507             var operand = node.operand;
96508             return operand.kind === 207 /* PrefixUnaryExpression */
96509                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
96510                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
96511         }
96512         function emitPostfixUnaryExpression(node) {
96513             emitExpression(node.operand);
96514             writeTokenText(node.operator, writeOperator);
96515         }
96516         var EmitBinaryExpressionState;
96517         (function (EmitBinaryExpressionState) {
96518             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
96519             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
96520             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
96521         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
96522         /**
96523          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
96524          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
96525          * not require notification/substitution/comment/sourcemap decorations.
96526          */
96527         function emitBinaryExpression(node) {
96528             var nodeStack = [node];
96529             var stateStack = [0 /* EmitLeft */];
96530             var stackIndex = 0;
96531             while (stackIndex >= 0) {
96532                 node = nodeStack[stackIndex];
96533                 switch (stateStack[stackIndex]) {
96534                     case 0 /* EmitLeft */: {
96535                         maybePipelineEmitExpression(node.left);
96536                         break;
96537                     }
96538                     case 1 /* EmitRight */: {
96539                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
96540                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96541                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96542                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
96543                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
96544                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
96545                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
96546                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
96547                         maybePipelineEmitExpression(node.right);
96548                         break;
96549                     }
96550                     case 2 /* FinishEmit */: {
96551                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96552                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96553                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
96554                         stackIndex--;
96555                         break;
96556                     }
96557                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
96558                 }
96559             }
96560             function maybePipelineEmitExpression(next) {
96561                 // Advance the state of this unit of work,
96562                 stateStack[stackIndex]++;
96563                 // Then actually do the work of emitting the node `next` returned by the prior state
96564                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
96565                 // binary expression handling, where possible, to the contained work queue
96566                 // #region trampolinePipelineEmit
96567                 var savedLastNode = lastNode;
96568                 var savedLastSubstitution = lastSubstitution;
96569                 lastNode = next;
96570                 lastSubstitution = undefined;
96571                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
96572                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
96573                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
96574                     // skip all the intermediate indirection and push the expression directly onto the work stack
96575                     stackIndex++;
96576                     stateStack[stackIndex] = 0 /* EmitLeft */;
96577                     nodeStack[stackIndex] = next;
96578                 }
96579                 else {
96580                     pipelinePhase(1 /* Expression */, next);
96581                 }
96582                 ts.Debug.assert(lastNode === next);
96583                 lastNode = savedLastNode;
96584                 lastSubstitution = savedLastSubstitution;
96585                 // #endregion trampolinePipelineEmit
96586             }
96587         }
96588         function emitConditionalExpression(node) {
96589             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
96590             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
96591             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
96592             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
96593             emitExpression(node.condition);
96594             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
96595             emit(node.questionToken);
96596             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
96597             emitExpression(node.whenTrue);
96598             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
96599             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
96600             emit(node.colonToken);
96601             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
96602             emitExpression(node.whenFalse);
96603             decreaseIndentIf(linesBeforeColon, linesAfterColon);
96604         }
96605         function emitTemplateExpression(node) {
96606             emit(node.head);
96607             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
96608         }
96609         function emitYieldExpression(node) {
96610             emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
96611             emit(node.asteriskToken);
96612             emitExpressionWithLeadingSpace(node.expression);
96613         }
96614         function emitSpreadExpression(node) {
96615             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
96616             emitExpression(node.expression);
96617         }
96618         function emitClassExpression(node) {
96619             generateNameIfNeeded(node.name);
96620             emitClassDeclarationOrExpression(node);
96621         }
96622         function emitExpressionWithTypeArguments(node) {
96623             emitExpression(node.expression);
96624             emitTypeArguments(node, node.typeArguments);
96625         }
96626         function emitAsExpression(node) {
96627             emitExpression(node.expression);
96628             if (node.type) {
96629                 writeSpace();
96630                 writeKeyword("as");
96631                 writeSpace();
96632                 emit(node.type);
96633             }
96634         }
96635         function emitNonNullExpression(node) {
96636             emitExpression(node.expression);
96637             writeOperator("!");
96638         }
96639         function emitMetaProperty(node) {
96640             writeToken(node.keywordToken, node.pos, writePunctuation);
96641             writePunctuation(".");
96642             emit(node.name);
96643         }
96644         //
96645         // Misc
96646         //
96647         function emitTemplateSpan(node) {
96648             emitExpression(node.expression);
96649             emit(node.literal);
96650         }
96651         //
96652         // Statements
96653         //
96654         function emitBlock(node) {
96655             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
96656         }
96657         function emitBlockStatements(node, forceSingleLine) {
96658             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
96659             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
96660             emitList(node, node.statements, format);
96661             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
96662         }
96663         function emitVariableStatement(node) {
96664             emitModifiers(node, node.modifiers);
96665             emit(node.declarationList);
96666             writeTrailingSemicolon();
96667         }
96668         function emitEmptyStatement(isEmbeddedStatement) {
96669             // While most trailing semicolons are possibly insignificant, an embedded "empty"
96670             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
96671             if (isEmbeddedStatement) {
96672                 writePunctuation(";");
96673             }
96674             else {
96675                 writeTrailingSemicolon();
96676             }
96677         }
96678         function emitExpressionStatement(node) {
96679             emitExpression(node.expression);
96680             // Emit semicolon in non json files
96681             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
96682             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
96683                 writeTrailingSemicolon();
96684             }
96685         }
96686         function emitIfStatement(node) {
96687             var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
96688             writeSpace();
96689             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96690             emitExpression(node.expression);
96691             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96692             emitEmbeddedStatement(node, node.thenStatement);
96693             if (node.elseStatement) {
96694                 writeLineOrSpace(node);
96695                 emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
96696                 if (node.elseStatement.kind === 227 /* IfStatement */) {
96697                     writeSpace();
96698                     emit(node.elseStatement);
96699                 }
96700                 else {
96701                     emitEmbeddedStatement(node, node.elseStatement);
96702                 }
96703             }
96704         }
96705         function emitWhileClause(node, startPos) {
96706             var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
96707             writeSpace();
96708             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96709             emitExpression(node.expression);
96710             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96711         }
96712         function emitDoStatement(node) {
96713             emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
96714             emitEmbeddedStatement(node, node.statement);
96715             if (ts.isBlock(node.statement)) {
96716                 writeSpace();
96717             }
96718             else {
96719                 writeLineOrSpace(node);
96720             }
96721             emitWhileClause(node, node.statement.end);
96722             writeTrailingSemicolon();
96723         }
96724         function emitWhileStatement(node) {
96725             emitWhileClause(node, node.pos);
96726             emitEmbeddedStatement(node, node.statement);
96727         }
96728         function emitForStatement(node) {
96729             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96730             writeSpace();
96731             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
96732             emitForBinding(node.initializer);
96733             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
96734             emitExpressionWithLeadingSpace(node.condition);
96735             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
96736             emitExpressionWithLeadingSpace(node.incrementor);
96737             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
96738             emitEmbeddedStatement(node, node.statement);
96739         }
96740         function emitForInStatement(node) {
96741             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96742             writeSpace();
96743             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96744             emitForBinding(node.initializer);
96745             writeSpace();
96746             emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
96747             writeSpace();
96748             emitExpression(node.expression);
96749             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96750             emitEmbeddedStatement(node, node.statement);
96751         }
96752         function emitForOfStatement(node) {
96753             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96754             writeSpace();
96755             emitWithTrailingSpace(node.awaitModifier);
96756             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96757             emitForBinding(node.initializer);
96758             writeSpace();
96759             emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
96760             writeSpace();
96761             emitExpression(node.expression);
96762             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96763             emitEmbeddedStatement(node, node.statement);
96764         }
96765         function emitForBinding(node) {
96766             if (node !== undefined) {
96767                 if (node.kind === 243 /* VariableDeclarationList */) {
96768                     emit(node);
96769                 }
96770                 else {
96771                     emitExpression(node);
96772                 }
96773             }
96774         }
96775         function emitContinueStatement(node) {
96776             emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
96777             emitWithLeadingSpace(node.label);
96778             writeTrailingSemicolon();
96779         }
96780         function emitBreakStatement(node) {
96781             emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
96782             emitWithLeadingSpace(node.label);
96783             writeTrailingSemicolon();
96784         }
96785         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
96786             var node = ts.getParseTreeNode(contextNode);
96787             var isSimilarNode = node && node.kind === contextNode.kind;
96788             var startPos = pos;
96789             if (isSimilarNode && currentSourceFile) {
96790                 pos = ts.skipTrivia(currentSourceFile.text, pos);
96791             }
96792             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
96793                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
96794                 if (needsIndent) {
96795                     increaseIndent();
96796                 }
96797                 emitLeadingCommentsOfPosition(startPos);
96798                 if (needsIndent) {
96799                     decreaseIndent();
96800                 }
96801             }
96802             pos = writeTokenText(token, writer, pos);
96803             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
96804                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
96805             }
96806             return pos;
96807         }
96808         function emitReturnStatement(node) {
96809             emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
96810             emitExpressionWithLeadingSpace(node.expression);
96811             writeTrailingSemicolon();
96812         }
96813         function emitWithStatement(node) {
96814             var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
96815             writeSpace();
96816             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96817             emitExpression(node.expression);
96818             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96819             emitEmbeddedStatement(node, node.statement);
96820         }
96821         function emitSwitchStatement(node) {
96822             var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
96823             writeSpace();
96824             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96825             emitExpression(node.expression);
96826             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96827             writeSpace();
96828             emit(node.caseBlock);
96829         }
96830         function emitLabeledStatement(node) {
96831             emit(node.label);
96832             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
96833             writeSpace();
96834             emit(node.statement);
96835         }
96836         function emitThrowStatement(node) {
96837             emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
96838             emitExpressionWithLeadingSpace(node.expression);
96839             writeTrailingSemicolon();
96840         }
96841         function emitTryStatement(node) {
96842             emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
96843             writeSpace();
96844             emit(node.tryBlock);
96845             if (node.catchClause) {
96846                 writeLineOrSpace(node);
96847                 emit(node.catchClause);
96848             }
96849             if (node.finallyBlock) {
96850                 writeLineOrSpace(node);
96851                 emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
96852                 writeSpace();
96853                 emit(node.finallyBlock);
96854             }
96855         }
96856         function emitDebuggerStatement(node) {
96857             writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
96858             writeTrailingSemicolon();
96859         }
96860         //
96861         // Declarations
96862         //
96863         function emitVariableDeclaration(node) {
96864             emit(node.name);
96865             emit(node.exclamationToken);
96866             emitTypeAnnotation(node.type);
96867             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
96868         }
96869         function emitVariableDeclarationList(node) {
96870             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
96871             writeSpace();
96872             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
96873         }
96874         function emitFunctionDeclaration(node) {
96875             emitFunctionDeclarationOrExpression(node);
96876         }
96877         function emitFunctionDeclarationOrExpression(node) {
96878             emitDecorators(node, node.decorators);
96879             emitModifiers(node, node.modifiers);
96880             writeKeyword("function");
96881             emit(node.asteriskToken);
96882             writeSpace();
96883             emitIdentifierName(node.name);
96884             emitSignatureAndBody(node, emitSignatureHead);
96885         }
96886         function emitBlockCallback(_hint, body) {
96887             emitBlockFunctionBody(body);
96888         }
96889         function emitSignatureAndBody(node, emitSignatureHead) {
96890             var body = node.body;
96891             if (body) {
96892                 if (ts.isBlock(body)) {
96893                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96894                     if (indentedFlag) {
96895                         increaseIndent();
96896                     }
96897                     pushNameGenerationScope(node);
96898                     ts.forEach(node.parameters, generateNames);
96899                     generateNames(node.body);
96900                     emitSignatureHead(node);
96901                     if (onEmitNode) {
96902                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
96903                     }
96904                     else {
96905                         emitBlockFunctionBody(body);
96906                     }
96907                     popNameGenerationScope(node);
96908                     if (indentedFlag) {
96909                         decreaseIndent();
96910                     }
96911                 }
96912                 else {
96913                     emitSignatureHead(node);
96914                     writeSpace();
96915                     emitExpression(body);
96916                 }
96917             }
96918             else {
96919                 emitSignatureHead(node);
96920                 writeTrailingSemicolon();
96921             }
96922         }
96923         function emitSignatureHead(node) {
96924             emitTypeParameters(node, node.typeParameters);
96925             emitParameters(node, node.parameters);
96926             emitTypeAnnotation(node.type);
96927         }
96928         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
96929             // We must emit a function body as a single-line body in the following case:
96930             // * The body has NodeEmitFlags.SingleLine specified.
96931             // We must emit a function body as a multi-line body in the following cases:
96932             // * The body is explicitly marked as multi-line.
96933             // * A non-synthesized body's start and end position are on different lines.
96934             // * Any statement in the body starts on a new line.
96935             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
96936                 return true;
96937             }
96938             if (body.multiLine) {
96939                 return false;
96940             }
96941             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
96942                 return false;
96943             }
96944             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
96945                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
96946                 return false;
96947             }
96948             var previousStatement;
96949             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
96950                 var statement = _b[_a];
96951                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
96952                     return false;
96953                 }
96954                 previousStatement = statement;
96955             }
96956             return true;
96957         }
96958         function emitBlockFunctionBody(body) {
96959             writeSpace();
96960             writePunctuation("{");
96961             increaseIndent();
96962             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
96963                 ? emitBlockFunctionBodyOnSingleLine
96964                 : emitBlockFunctionBodyWorker;
96965             if (emitBodyWithDetachedComments) {
96966                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
96967             }
96968             else {
96969                 emitBlockFunctionBody(body);
96970             }
96971             decreaseIndent();
96972             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
96973         }
96974         function emitBlockFunctionBodyOnSingleLine(body) {
96975             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
96976         }
96977         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
96978             // Emit all the prologue directives (like "use strict").
96979             var statementOffset = emitPrologueDirectives(body.statements);
96980             var pos = writer.getTextPos();
96981             emitHelpers(body);
96982             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
96983                 decreaseIndent();
96984                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
96985                 increaseIndent();
96986             }
96987             else {
96988                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
96989             }
96990         }
96991         function emitClassDeclaration(node) {
96992             emitClassDeclarationOrExpression(node);
96993         }
96994         function emitClassDeclarationOrExpression(node) {
96995             ts.forEach(node.members, generateMemberNames);
96996             emitDecorators(node, node.decorators);
96997             emitModifiers(node, node.modifiers);
96998             writeKeyword("class");
96999             if (node.name) {
97000                 writeSpace();
97001                 emitIdentifierName(node.name);
97002             }
97003             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
97004             if (indentedFlag) {
97005                 increaseIndent();
97006             }
97007             emitTypeParameters(node, node.typeParameters);
97008             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
97009             writeSpace();
97010             writePunctuation("{");
97011             emitList(node, node.members, 129 /* ClassMembers */);
97012             writePunctuation("}");
97013             if (indentedFlag) {
97014                 decreaseIndent();
97015             }
97016         }
97017         function emitInterfaceDeclaration(node) {
97018             emitDecorators(node, node.decorators);
97019             emitModifiers(node, node.modifiers);
97020             writeKeyword("interface");
97021             writeSpace();
97022             emit(node.name);
97023             emitTypeParameters(node, node.typeParameters);
97024             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
97025             writeSpace();
97026             writePunctuation("{");
97027             emitList(node, node.members, 129 /* InterfaceMembers */);
97028             writePunctuation("}");
97029         }
97030         function emitTypeAliasDeclaration(node) {
97031             emitDecorators(node, node.decorators);
97032             emitModifiers(node, node.modifiers);
97033             writeKeyword("type");
97034             writeSpace();
97035             emit(node.name);
97036             emitTypeParameters(node, node.typeParameters);
97037             writeSpace();
97038             writePunctuation("=");
97039             writeSpace();
97040             emit(node.type);
97041             writeTrailingSemicolon();
97042         }
97043         function emitEnumDeclaration(node) {
97044             emitModifiers(node, node.modifiers);
97045             writeKeyword("enum");
97046             writeSpace();
97047             emit(node.name);
97048             writeSpace();
97049             writePunctuation("{");
97050             emitList(node, node.members, 145 /* EnumMembers */);
97051             writePunctuation("}");
97052         }
97053         function emitModuleDeclaration(node) {
97054             emitModifiers(node, node.modifiers);
97055             if (~node.flags & 1024 /* GlobalAugmentation */) {
97056                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
97057                 writeSpace();
97058             }
97059             emit(node.name);
97060             var body = node.body;
97061             if (!body)
97062                 return writeTrailingSemicolon();
97063             while (body.kind === 249 /* ModuleDeclaration */) {
97064                 writePunctuation(".");
97065                 emit(body.name);
97066                 body = body.body;
97067             }
97068             writeSpace();
97069             emit(body);
97070         }
97071         function emitModuleBlock(node) {
97072             pushNameGenerationScope(node);
97073             ts.forEach(node.statements, generateNames);
97074             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
97075             popNameGenerationScope(node);
97076         }
97077         function emitCaseBlock(node) {
97078             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
97079             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
97080             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
97081         }
97082         function emitImportEqualsDeclaration(node) {
97083             emitModifiers(node, node.modifiers);
97084             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
97085             writeSpace();
97086             emit(node.name);
97087             writeSpace();
97088             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
97089             writeSpace();
97090             emitModuleReference(node.moduleReference);
97091             writeTrailingSemicolon();
97092         }
97093         function emitModuleReference(node) {
97094             if (node.kind === 75 /* Identifier */) {
97095                 emitExpression(node);
97096             }
97097             else {
97098                 emit(node);
97099             }
97100         }
97101         function emitImportDeclaration(node) {
97102             emitModifiers(node, node.modifiers);
97103             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
97104             writeSpace();
97105             if (node.importClause) {
97106                 emit(node.importClause);
97107                 writeSpace();
97108                 emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
97109                 writeSpace();
97110             }
97111             emitExpression(node.moduleSpecifier);
97112             writeTrailingSemicolon();
97113         }
97114         function emitImportClause(node) {
97115             if (node.isTypeOnly) {
97116                 emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
97117                 writeSpace();
97118             }
97119             emit(node.name);
97120             if (node.name && node.namedBindings) {
97121                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
97122                 writeSpace();
97123             }
97124             emit(node.namedBindings);
97125         }
97126         function emitNamespaceImport(node) {
97127             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
97128             writeSpace();
97129             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97130             writeSpace();
97131             emit(node.name);
97132         }
97133         function emitNamedImports(node) {
97134             emitNamedImportsOrExports(node);
97135         }
97136         function emitImportSpecifier(node) {
97137             emitImportOrExportSpecifier(node);
97138         }
97139         function emitExportAssignment(node) {
97140             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97141             writeSpace();
97142             if (node.isExportEquals) {
97143                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
97144             }
97145             else {
97146                 emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
97147             }
97148             writeSpace();
97149             emitExpression(node.expression);
97150             writeTrailingSemicolon();
97151         }
97152         function emitExportDeclaration(node) {
97153             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97154             writeSpace();
97155             if (node.isTypeOnly) {
97156                 nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
97157                 writeSpace();
97158             }
97159             if (node.exportClause) {
97160                 emit(node.exportClause);
97161             }
97162             else {
97163                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
97164             }
97165             if (node.moduleSpecifier) {
97166                 writeSpace();
97167                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
97168                 emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
97169                 writeSpace();
97170                 emitExpression(node.moduleSpecifier);
97171             }
97172             writeTrailingSemicolon();
97173         }
97174         function emitNamespaceExportDeclaration(node) {
97175             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97176             writeSpace();
97177             nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
97178             writeSpace();
97179             nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
97180             writeSpace();
97181             emit(node.name);
97182             writeTrailingSemicolon();
97183         }
97184         function emitNamespaceExport(node) {
97185             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
97186             writeSpace();
97187             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97188             writeSpace();
97189             emit(node.name);
97190         }
97191         function emitNamedExports(node) {
97192             emitNamedImportsOrExports(node);
97193         }
97194         function emitExportSpecifier(node) {
97195             emitImportOrExportSpecifier(node);
97196         }
97197         function emitNamedImportsOrExports(node) {
97198             writePunctuation("{");
97199             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
97200             writePunctuation("}");
97201         }
97202         function emitImportOrExportSpecifier(node) {
97203             if (node.propertyName) {
97204                 emit(node.propertyName);
97205                 writeSpace();
97206                 emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
97207                 writeSpace();
97208             }
97209             emit(node.name);
97210         }
97211         //
97212         // Module references
97213         //
97214         function emitExternalModuleReference(node) {
97215             writeKeyword("require");
97216             writePunctuation("(");
97217             emitExpression(node.expression);
97218             writePunctuation(")");
97219         }
97220         //
97221         // JSX
97222         //
97223         function emitJsxElement(node) {
97224             emit(node.openingElement);
97225             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97226             emit(node.closingElement);
97227         }
97228         function emitJsxSelfClosingElement(node) {
97229             writePunctuation("<");
97230             emitJsxTagName(node.tagName);
97231             emitTypeArguments(node, node.typeArguments);
97232             writeSpace();
97233             emit(node.attributes);
97234             writePunctuation("/>");
97235         }
97236         function emitJsxFragment(node) {
97237             emit(node.openingFragment);
97238             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97239             emit(node.closingFragment);
97240         }
97241         function emitJsxOpeningElementOrFragment(node) {
97242             writePunctuation("<");
97243             if (ts.isJsxOpeningElement(node)) {
97244                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
97245                 emitJsxTagName(node.tagName);
97246                 emitTypeArguments(node, node.typeArguments);
97247                 if (node.attributes.properties && node.attributes.properties.length > 0) {
97248                     writeSpace();
97249                 }
97250                 emit(node.attributes);
97251                 writeLineSeparatorsAfter(node.attributes, node);
97252                 decreaseIndentIf(indented);
97253             }
97254             writePunctuation(">");
97255         }
97256         function emitJsxText(node) {
97257             writer.writeLiteral(node.text);
97258         }
97259         function emitJsxClosingElementOrFragment(node) {
97260             writePunctuation("</");
97261             if (ts.isJsxClosingElement(node)) {
97262                 emitJsxTagName(node.tagName);
97263             }
97264             writePunctuation(">");
97265         }
97266         function emitJsxAttributes(node) {
97267             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
97268         }
97269         function emitJsxAttribute(node) {
97270             emit(node.name);
97271             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
97272         }
97273         function emitJsxSpreadAttribute(node) {
97274             writePunctuation("{...");
97275             emitExpression(node.expression);
97276             writePunctuation("}");
97277         }
97278         function emitJsxExpression(node) {
97279             if (node.expression) {
97280                 writePunctuation("{");
97281                 emit(node.dotDotDotToken);
97282                 emitExpression(node.expression);
97283                 writePunctuation("}");
97284             }
97285         }
97286         function emitJsxTagName(node) {
97287             if (node.kind === 75 /* Identifier */) {
97288                 emitExpression(node);
97289             }
97290             else {
97291                 emit(node);
97292             }
97293         }
97294         //
97295         // Clauses
97296         //
97297         function emitCaseClause(node) {
97298             emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
97299             writeSpace();
97300             emitExpression(node.expression);
97301             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
97302         }
97303         function emitDefaultClause(node) {
97304             var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
97305             emitCaseOrDefaultClauseRest(node, node.statements, pos);
97306         }
97307         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
97308             var emitAsSingleStatement = statements.length === 1 &&
97309                 (
97310                 // treat synthesized nodes as located on the same line for emit purposes
97311                 ts.nodeIsSynthesized(parentNode) ||
97312                     ts.nodeIsSynthesized(statements[0]) ||
97313                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
97314             var format = 163969 /* CaseOrDefaultClauseStatements */;
97315             if (emitAsSingleStatement) {
97316                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97317                 writeSpace();
97318                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
97319             }
97320             else {
97321                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97322             }
97323             emitList(parentNode, statements, format);
97324         }
97325         function emitHeritageClause(node) {
97326             writeSpace();
97327             writeTokenText(node.token, writeKeyword);
97328             writeSpace();
97329             emitList(node, node.types, 528 /* HeritageClauseTypes */);
97330         }
97331         function emitCatchClause(node) {
97332             var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
97333             writeSpace();
97334             if (node.variableDeclaration) {
97335                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
97336                 emit(node.variableDeclaration);
97337                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
97338                 writeSpace();
97339             }
97340             emit(node.block);
97341         }
97342         //
97343         // Property assignments
97344         //
97345         function emitPropertyAssignment(node) {
97346             emit(node.name);
97347             writePunctuation(":");
97348             writeSpace();
97349             // This is to ensure that we emit comment in the following case:
97350             //      For example:
97351             //          obj = {
97352             //              id: /*comment1*/ ()=>void
97353             //          }
97354             // "comment1" is not considered to be leading comment for node.initializer
97355             // but rather a trailing comment on the previous node.
97356             var initializer = node.initializer;
97357             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
97358                 var commentRange = ts.getCommentRange(initializer);
97359                 emitTrailingCommentsOfPosition(commentRange.pos);
97360             }
97361             emitExpression(initializer);
97362         }
97363         function emitShorthandPropertyAssignment(node) {
97364             emit(node.name);
97365             if (node.objectAssignmentInitializer) {
97366                 writeSpace();
97367                 writePunctuation("=");
97368                 writeSpace();
97369                 emitExpression(node.objectAssignmentInitializer);
97370             }
97371         }
97372         function emitSpreadAssignment(node) {
97373             if (node.expression) {
97374                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
97375                 emitExpression(node.expression);
97376             }
97377         }
97378         //
97379         // Enum
97380         //
97381         function emitEnumMember(node) {
97382             emit(node.name);
97383             emitInitializer(node.initializer, node.name.end, node);
97384         }
97385         //
97386         // JSDoc
97387         //
97388         function emitJSDoc(node) {
97389             write("/**");
97390             if (node.comment) {
97391                 var lines = node.comment.split(/\r\n?|\n/g);
97392                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
97393                     var line = lines_2[_a];
97394                     writeLine();
97395                     writeSpace();
97396                     writePunctuation("*");
97397                     writeSpace();
97398                     write(line);
97399                 }
97400             }
97401             if (node.tags) {
97402                 if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) {
97403                     writeSpace();
97404                     emit(node.tags[0]);
97405                 }
97406                 else {
97407                     emitList(node, node.tags, 33 /* JSDocComment */);
97408                 }
97409             }
97410             writeSpace();
97411             write("*/");
97412         }
97413         function emitJSDocSimpleTypedTag(tag) {
97414             emitJSDocTagName(tag.tagName);
97415             emitJSDocTypeExpression(tag.typeExpression);
97416             emitJSDocComment(tag.comment);
97417         }
97418         function emitJSDocHeritageTag(tag) {
97419             emitJSDocTagName(tag.tagName);
97420             writeSpace();
97421             writePunctuation("{");
97422             emit(tag.class);
97423             writePunctuation("}");
97424             emitJSDocComment(tag.comment);
97425         }
97426         function emitJSDocTemplateTag(tag) {
97427             emitJSDocTagName(tag.tagName);
97428             emitJSDocTypeExpression(tag.constraint);
97429             writeSpace();
97430             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
97431             emitJSDocComment(tag.comment);
97432         }
97433         function emitJSDocTypedefTag(tag) {
97434             emitJSDocTagName(tag.tagName);
97435             if (tag.typeExpression) {
97436                 if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
97437                     emitJSDocTypeExpression(tag.typeExpression);
97438                 }
97439                 else {
97440                     writeSpace();
97441                     writePunctuation("{");
97442                     write("Object");
97443                     if (tag.typeExpression.isArrayType) {
97444                         writePunctuation("[");
97445                         writePunctuation("]");
97446                     }
97447                     writePunctuation("}");
97448                 }
97449             }
97450             if (tag.fullName) {
97451                 writeSpace();
97452                 emit(tag.fullName);
97453             }
97454             emitJSDocComment(tag.comment);
97455             if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
97456                 emitJSDocTypeLiteral(tag.typeExpression);
97457             }
97458         }
97459         function emitJSDocCallbackTag(tag) {
97460             emitJSDocTagName(tag.tagName);
97461             if (tag.name) {
97462                 writeSpace();
97463                 emit(tag.name);
97464             }
97465             emitJSDocComment(tag.comment);
97466             emitJSDocSignature(tag.typeExpression);
97467         }
97468         function emitJSDocSimpleTag(tag) {
97469             emitJSDocTagName(tag.tagName);
97470             emitJSDocComment(tag.comment);
97471         }
97472         function emitJSDocTypeLiteral(lit) {
97473             emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
97474         }
97475         function emitJSDocSignature(sig) {
97476             if (sig.typeParameters) {
97477                 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
97478             }
97479             if (sig.parameters) {
97480                 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
97481             }
97482             if (sig.type) {
97483                 writeLine();
97484                 writeSpace();
97485                 writePunctuation("*");
97486                 writeSpace();
97487                 emit(sig.type);
97488             }
97489         }
97490         function emitJSDocPropertyLikeTag(param) {
97491             emitJSDocTagName(param.tagName);
97492             emitJSDocTypeExpression(param.typeExpression);
97493             writeSpace();
97494             if (param.isBracketed) {
97495                 writePunctuation("[");
97496             }
97497             emit(param.name);
97498             if (param.isBracketed) {
97499                 writePunctuation("]");
97500             }
97501             emitJSDocComment(param.comment);
97502         }
97503         function emitJSDocTagName(tagName) {
97504             writePunctuation("@");
97505             emit(tagName);
97506         }
97507         function emitJSDocComment(comment) {
97508             if (comment) {
97509                 writeSpace();
97510                 write(comment);
97511             }
97512         }
97513         function emitJSDocTypeExpression(typeExpression) {
97514             if (typeExpression) {
97515                 writeSpace();
97516                 writePunctuation("{");
97517                 emit(typeExpression.type);
97518                 writePunctuation("}");
97519             }
97520         }
97521         //
97522         // Top-level nodes
97523         //
97524         function emitSourceFile(node) {
97525             writeLine();
97526             var statements = node.statements;
97527             if (emitBodyWithDetachedComments) {
97528                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
97529                 // The synthesized node will have no leading comment so some comments may be missed.
97530                 var shouldEmitDetachedComment = statements.length === 0 ||
97531                     !ts.isPrologueDirective(statements[0]) ||
97532                     ts.nodeIsSynthesized(statements[0]);
97533                 if (shouldEmitDetachedComment) {
97534                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
97535                     return;
97536                 }
97537             }
97538             emitSourceFileWorker(node);
97539         }
97540         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
97541             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
97542             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
97543                 var prepend = _b[_a];
97544                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
97545                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
97546                         var ref = _d[_c];
97547                         emit(ref);
97548                         writeLine();
97549                     }
97550                 }
97551             }
97552         }
97553         function emitTripleSlashDirectivesIfNeeded(node) {
97554             if (node.isDeclarationFile)
97555                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
97556         }
97557         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
97558             if (hasNoDefaultLib) {
97559                 var pos = writer.getTextPos();
97560                 writeComment("/// <reference no-default-lib=\"true\"/>");
97561                 if (bundleFileInfo)
97562                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
97563                 writeLine();
97564             }
97565             if (currentSourceFile && currentSourceFile.moduleName) {
97566                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
97567                 writeLine();
97568             }
97569             if (currentSourceFile && currentSourceFile.amdDependencies) {
97570                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
97571                     var dep = _b[_a];
97572                     if (dep.name) {
97573                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
97574                     }
97575                     else {
97576                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
97577                     }
97578                     writeLine();
97579                 }
97580             }
97581             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
97582                 var directive = files_1[_c];
97583                 var pos = writer.getTextPos();
97584                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
97585                 if (bundleFileInfo)
97586                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
97587                 writeLine();
97588             }
97589             for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
97590                 var directive = types_22[_d];
97591                 var pos = writer.getTextPos();
97592                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
97593                 if (bundleFileInfo)
97594                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
97595                 writeLine();
97596             }
97597             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
97598                 var directive = libs_1[_e];
97599                 var pos = writer.getTextPos();
97600                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
97601                 if (bundleFileInfo)
97602                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
97603                 writeLine();
97604             }
97605         }
97606         function emitSourceFileWorker(node) {
97607             var statements = node.statements;
97608             pushNameGenerationScope(node);
97609             ts.forEach(node.statements, generateNames);
97610             emitHelpers(node);
97611             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
97612             emitTripleSlashDirectivesIfNeeded(node);
97613             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
97614             popNameGenerationScope(node);
97615         }
97616         // Transformation nodes
97617         function emitPartiallyEmittedExpression(node) {
97618             emitExpression(node.expression);
97619         }
97620         function emitCommaList(node) {
97621             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
97622         }
97623         /**
97624          * Emits any prologue directives at the start of a Statement list, returning the
97625          * number of prologue directives written to the output.
97626          */
97627         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
97628             var needsToSetSourceFile = !!sourceFile;
97629             for (var i = 0; i < statements.length; i++) {
97630                 var statement = statements[i];
97631                 if (ts.isPrologueDirective(statement)) {
97632                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
97633                     if (shouldEmitPrologueDirective) {
97634                         if (needsToSetSourceFile) {
97635                             needsToSetSourceFile = false;
97636                             setSourceFile(sourceFile);
97637                         }
97638                         writeLine();
97639                         var pos = writer.getTextPos();
97640                         emit(statement);
97641                         if (recordBundleFileSection && bundleFileInfo)
97642                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
97643                         if (seenPrologueDirectives) {
97644                             seenPrologueDirectives.set(statement.expression.text, true);
97645                         }
97646                     }
97647                 }
97648                 else {
97649                     // return index of the first non prologue directive
97650                     return i;
97651                 }
97652             }
97653             return statements.length;
97654         }
97655         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
97656             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
97657                 var prologue = prologues_1[_a];
97658                 if (!seenPrologueDirectives.has(prologue.data)) {
97659                     writeLine();
97660                     var pos = writer.getTextPos();
97661                     emit(prologue);
97662                     if (bundleFileInfo)
97663                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
97664                     if (seenPrologueDirectives) {
97665                         seenPrologueDirectives.set(prologue.data, true);
97666                     }
97667                 }
97668             }
97669         }
97670         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
97671             if (ts.isSourceFile(sourceFileOrBundle)) {
97672                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
97673             }
97674             else {
97675                 var seenPrologueDirectives = ts.createMap();
97676                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97677                     var prepend = _b[_a];
97678                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
97679                 }
97680                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97681                     var sourceFile = _d[_c];
97682                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
97683                 }
97684                 setSourceFile(undefined);
97685             }
97686         }
97687         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
97688             var seenPrologueDirectives = ts.createMap();
97689             var prologues;
97690             for (var index = 0; index < bundle.sourceFiles.length; index++) {
97691                 var sourceFile = bundle.sourceFiles[index];
97692                 var directives = void 0;
97693                 var end = 0;
97694                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
97695                     var statement = _b[_a];
97696                     if (!ts.isPrologueDirective(statement))
97697                         break;
97698                     if (seenPrologueDirectives.has(statement.expression.text))
97699                         continue;
97700                     seenPrologueDirectives.set(statement.expression.text, true);
97701                     (directives || (directives = [])).push({
97702                         pos: statement.pos,
97703                         end: statement.end,
97704                         expression: {
97705                             pos: statement.expression.pos,
97706                             end: statement.expression.end,
97707                             text: statement.expression.text
97708                         }
97709                     });
97710                     end = end < statement.end ? statement.end : end;
97711                 }
97712                 if (directives)
97713                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
97714             }
97715             return prologues;
97716         }
97717         function emitShebangIfNeeded(sourceFileOrBundle) {
97718             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
97719                 var shebang = ts.getShebang(sourceFileOrBundle.text);
97720                 if (shebang) {
97721                     writeComment(shebang);
97722                     writeLine();
97723                     return true;
97724                 }
97725             }
97726             else {
97727                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97728                     var prepend = _b[_a];
97729                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
97730                     if (emitShebangIfNeeded(prepend)) {
97731                         return true;
97732                     }
97733                 }
97734                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97735                     var sourceFile = _d[_c];
97736                     // Emit only the first encountered shebang
97737                     if (emitShebangIfNeeded(sourceFile)) {
97738                         return true;
97739                     }
97740                 }
97741             }
97742         }
97743         //
97744         // Helpers
97745         //
97746         function emitNodeWithWriter(node, writer) {
97747             if (!node)
97748                 return;
97749             var savedWrite = write;
97750             write = writer;
97751             emit(node);
97752             write = savedWrite;
97753         }
97754         function emitModifiers(node, modifiers) {
97755             if (modifiers && modifiers.length) {
97756                 emitList(node, modifiers, 262656 /* Modifiers */);
97757                 writeSpace();
97758             }
97759         }
97760         function emitTypeAnnotation(node) {
97761             if (node) {
97762                 writePunctuation(":");
97763                 writeSpace();
97764                 emit(node);
97765             }
97766         }
97767         function emitInitializer(node, equalCommentStartPos, container) {
97768             if (node) {
97769                 writeSpace();
97770                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
97771                 writeSpace();
97772                 emitExpression(node);
97773             }
97774         }
97775         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
97776             if (node) {
97777                 prefixWriter(prefix);
97778                 emit(node);
97779             }
97780         }
97781         function emitWithLeadingSpace(node) {
97782             if (node) {
97783                 writeSpace();
97784                 emit(node);
97785             }
97786         }
97787         function emitExpressionWithLeadingSpace(node) {
97788             if (node) {
97789                 writeSpace();
97790                 emitExpression(node);
97791             }
97792         }
97793         function emitWithTrailingSpace(node) {
97794             if (node) {
97795                 emit(node);
97796                 writeSpace();
97797             }
97798         }
97799         function emitEmbeddedStatement(parent, node) {
97800             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
97801                 writeSpace();
97802                 emit(node);
97803             }
97804             else {
97805                 writeLine();
97806                 increaseIndent();
97807                 if (ts.isEmptyStatement(node)) {
97808                     pipelineEmit(5 /* EmbeddedStatement */, node);
97809                 }
97810                 else {
97811                     emit(node);
97812                 }
97813                 decreaseIndent();
97814             }
97815         }
97816         function emitDecorators(parentNode, decorators) {
97817             emitList(parentNode, decorators, 2146305 /* Decorators */);
97818         }
97819         function emitTypeArguments(parentNode, typeArguments) {
97820             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
97821         }
97822         function emitTypeParameters(parentNode, typeParameters) {
97823             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
97824                 return emitTypeArguments(parentNode, parentNode.typeArguments);
97825             }
97826             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
97827         }
97828         function emitParameters(parentNode, parameters) {
97829             emitList(parentNode, parameters, 2576 /* Parameters */);
97830         }
97831         function canEmitSimpleArrowHead(parentNode, parameters) {
97832             var parameter = ts.singleOrUndefined(parameters);
97833             return parameter
97834                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
97835                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
97836                 && !parentNode.type // arrow function may not have return type annotation
97837                 && !ts.some(parentNode.decorators) // parent may not have decorators
97838                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
97839                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
97840                 && !ts.some(parameter.decorators) // parameter may not have decorators
97841                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
97842                 && !parameter.dotDotDotToken // parameter may not be rest
97843                 && !parameter.questionToken // parameter may not be optional
97844                 && !parameter.type // parameter may not have a type annotation
97845                 && !parameter.initializer // parameter may not have an initializer
97846                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
97847         }
97848         function emitParametersForArrow(parentNode, parameters) {
97849             if (canEmitSimpleArrowHead(parentNode, parameters)) {
97850                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
97851             }
97852             else {
97853                 emitParameters(parentNode, parameters);
97854             }
97855         }
97856         function emitParametersForIndexSignature(parentNode, parameters) {
97857             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
97858         }
97859         function emitList(parentNode, children, format, start, count) {
97860             emitNodeList(emit, parentNode, children, format, start, count);
97861         }
97862         function emitExpressionList(parentNode, children, format, start, count) {
97863             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
97864         }
97865         function writeDelimiter(format) {
97866             switch (format & 60 /* DelimitersMask */) {
97867                 case 0 /* None */:
97868                     break;
97869                 case 16 /* CommaDelimited */:
97870                     writePunctuation(",");
97871                     break;
97872                 case 4 /* BarDelimited */:
97873                     writeSpace();
97874                     writePunctuation("|");
97875                     break;
97876                 case 32 /* AsteriskDelimited */:
97877                     writeSpace();
97878                     writePunctuation("*");
97879                     writeSpace();
97880                     break;
97881                 case 8 /* AmpersandDelimited */:
97882                     writeSpace();
97883                     writePunctuation("&");
97884                     break;
97885             }
97886         }
97887         function emitNodeList(emit, parentNode, children, format, start, count) {
97888             if (start === void 0) { start = 0; }
97889             if (count === void 0) { count = children ? children.length - start : 0; }
97890             var isUndefined = children === undefined;
97891             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
97892                 return;
97893             }
97894             var isEmpty = children === undefined || start >= children.length || count === 0;
97895             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
97896                 if (onBeforeEmitNodeArray) {
97897                     onBeforeEmitNodeArray(children);
97898                 }
97899                 if (onAfterEmitNodeArray) {
97900                     onAfterEmitNodeArray(children);
97901                 }
97902                 return;
97903             }
97904             if (format & 15360 /* BracketsMask */) {
97905                 writePunctuation(getOpeningBracket(format));
97906                 if (isEmpty && !isUndefined) {
97907                     // TODO: GH#18217
97908                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
97909                 }
97910             }
97911             if (onBeforeEmitNodeArray) {
97912                 onBeforeEmitNodeArray(children);
97913             }
97914             if (isEmpty) {
97915                 // Write a line terminator if the parent node was multi-line
97916                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
97917                     writeLine();
97918                 }
97919                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
97920                     writeSpace();
97921                 }
97922             }
97923             else {
97924                 // Write the opening line terminator or leading whitespace.
97925                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
97926                 var shouldEmitInterveningComments = mayEmitInterveningComments;
97927                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
97928                 if (leadingLineTerminatorCount) {
97929                     writeLine(leadingLineTerminatorCount);
97930                     shouldEmitInterveningComments = false;
97931                 }
97932                 else if (format & 256 /* SpaceBetweenBraces */) {
97933                     writeSpace();
97934                 }
97935                 // Increase the indent, if requested.
97936                 if (format & 128 /* Indented */) {
97937                     increaseIndent();
97938                 }
97939                 // Emit each child.
97940                 var previousSibling = void 0;
97941                 var previousSourceFileTextKind = void 0;
97942                 var shouldDecreaseIndentAfterEmit = false;
97943                 for (var i = 0; i < count; i++) {
97944                     var child = children[start + i];
97945                     // Write the delimiter if this is not the first node.
97946                     if (format & 32 /* AsteriskDelimited */) {
97947                         // always write JSDoc in the format "\n *"
97948                         writeLine();
97949                         writeDelimiter(format);
97950                     }
97951                     else if (previousSibling) {
97952                         // i.e
97953                         //      function commentedParameters(
97954                         //          /* Parameter a */
97955                         //          a
97956                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
97957                         //          ,
97958                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
97959                             emitLeadingCommentsOfPosition(previousSibling.end);
97960                         }
97961                         writeDelimiter(format);
97962                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97963                         // Write either a line terminator or whitespace to separate the elements.
97964                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
97965                         if (separatingLineTerminatorCount > 0) {
97966                             // If a synthesized node in a single-line list starts on a new
97967                             // line, we should increase the indent.
97968                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
97969                                 increaseIndent();
97970                                 shouldDecreaseIndentAfterEmit = true;
97971                             }
97972                             writeLine(separatingLineTerminatorCount);
97973                             shouldEmitInterveningComments = false;
97974                         }
97975                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
97976                             writeSpace();
97977                         }
97978                     }
97979                     // Emit this child.
97980                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
97981                     if (shouldEmitInterveningComments) {
97982                         if (emitTrailingCommentsOfPosition) {
97983                             var commentRange = ts.getCommentRange(child);
97984                             emitTrailingCommentsOfPosition(commentRange.pos);
97985                         }
97986                     }
97987                     else {
97988                         shouldEmitInterveningComments = mayEmitInterveningComments;
97989                     }
97990                     emit(child);
97991                     if (shouldDecreaseIndentAfterEmit) {
97992                         decreaseIndent();
97993                         shouldDecreaseIndentAfterEmit = false;
97994                     }
97995                     previousSibling = child;
97996                 }
97997                 // Write a trailing comma, if requested.
97998                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
97999                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
98000                     writePunctuation(",");
98001                 }
98002                 // Emit any trailing comment of the last element in the list
98003                 // i.e
98004                 //       var array = [...
98005                 //          2
98006                 //          /* end of element 2 */
98007                 //       ];
98008                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
98009                     emitLeadingCommentsOfPosition(previousSibling.end);
98010                 }
98011                 // Decrease the indent, if requested.
98012                 if (format & 128 /* Indented */) {
98013                     decreaseIndent();
98014                 }
98015                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
98016                 // Write the closing line terminator or closing whitespace.
98017                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
98018                 if (closingLineTerminatorCount) {
98019                     writeLine(closingLineTerminatorCount);
98020                 }
98021                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
98022                     writeSpace();
98023                 }
98024             }
98025             if (onAfterEmitNodeArray) {
98026                 onAfterEmitNodeArray(children);
98027             }
98028             if (format & 15360 /* BracketsMask */) {
98029                 if (isEmpty && !isUndefined) {
98030                     // TODO: GH#18217
98031                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
98032                 }
98033                 writePunctuation(getClosingBracket(format));
98034             }
98035         }
98036         // Writers
98037         function writeLiteral(s) {
98038             writer.writeLiteral(s);
98039         }
98040         function writeStringLiteral(s) {
98041             writer.writeStringLiteral(s);
98042         }
98043         function writeBase(s) {
98044             writer.write(s);
98045         }
98046         function writeSymbol(s, sym) {
98047             writer.writeSymbol(s, sym);
98048         }
98049         function writePunctuation(s) {
98050             writer.writePunctuation(s);
98051         }
98052         function writeTrailingSemicolon() {
98053             writer.writeTrailingSemicolon(";");
98054         }
98055         function writeKeyword(s) {
98056             writer.writeKeyword(s);
98057         }
98058         function writeOperator(s) {
98059             writer.writeOperator(s);
98060         }
98061         function writeParameter(s) {
98062             writer.writeParameter(s);
98063         }
98064         function writeComment(s) {
98065             writer.writeComment(s);
98066         }
98067         function writeSpace() {
98068             writer.writeSpace(" ");
98069         }
98070         function writeProperty(s) {
98071             writer.writeProperty(s);
98072         }
98073         function writeLine(count) {
98074             if (count === void 0) { count = 1; }
98075             for (var i = 0; i < count; i++) {
98076                 writer.writeLine(i > 0);
98077             }
98078         }
98079         function increaseIndent() {
98080             writer.increaseIndent();
98081         }
98082         function decreaseIndent() {
98083             writer.decreaseIndent();
98084         }
98085         function writeToken(token, pos, writer, contextNode) {
98086             return !sourceMapsDisabled
98087                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
98088                 : writeTokenText(token, writer, pos);
98089         }
98090         function writeTokenNode(node, writer) {
98091             if (onBeforeEmitToken) {
98092                 onBeforeEmitToken(node);
98093             }
98094             writer(ts.tokenToString(node.kind));
98095             if (onAfterEmitToken) {
98096                 onAfterEmitToken(node);
98097             }
98098         }
98099         function writeTokenText(token, writer, pos) {
98100             var tokenString = ts.tokenToString(token);
98101             writer(tokenString);
98102             return pos < 0 ? pos : pos + tokenString.length;
98103         }
98104         function writeLineOrSpace(node) {
98105             if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
98106                 writeSpace();
98107             }
98108             else {
98109                 writeLine();
98110             }
98111         }
98112         function writeLines(text) {
98113             var lines = text.split(/\r\n?|\n/g);
98114             var indentation = ts.guessIndentation(lines);
98115             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
98116                 var lineText = lines_3[_a];
98117                 var line = indentation ? lineText.slice(indentation) : lineText;
98118                 if (line.length) {
98119                     writeLine();
98120                     write(line);
98121                 }
98122             }
98123         }
98124         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
98125             if (lineCount) {
98126                 increaseIndent();
98127                 writeLine(lineCount);
98128             }
98129             else if (writeSpaceIfNotIndenting) {
98130                 writeSpace();
98131             }
98132         }
98133         // Helper function to decrease the indent if we previously indented.  Allows multiple
98134         // previous indent values to be considered at a time.  This also allows caller to just
98135         // call this once, passing in all their appropriate indent values, instead of needing
98136         // to call this helper function multiple times.
98137         function decreaseIndentIf(value1, value2) {
98138             if (value1) {
98139                 decreaseIndent();
98140             }
98141             if (value2) {
98142                 decreaseIndent();
98143             }
98144         }
98145         function getLeadingLineTerminatorCount(parentNode, children, format) {
98146             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98147                 if (format & 65536 /* PreferNewLine */) {
98148                     return 1;
98149                 }
98150                 var firstChild_1 = children[0];
98151                 if (firstChild_1 === undefined) {
98152                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98153                 }
98154                 if (firstChild_1.kind === 11 /* JsxText */) {
98155                     // JsxText will be written with its leading whitespace, so don't add more manually.
98156                     return 0;
98157                 }
98158                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) {
98159                     if (preserveSourceNewlines) {
98160                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
98161                     }
98162                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
98163                 }
98164                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
98165                     return 1;
98166                 }
98167             }
98168             return format & 1 /* MultiLine */ ? 1 : 0;
98169         }
98170         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
98171             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98172                 if (previousNode === undefined || nextNode === undefined) {
98173                     return 0;
98174                 }
98175                 if (nextNode.kind === 11 /* JsxText */) {
98176                     // JsxText will be written with its leading whitespace, so don't add more manually.
98177                     return 0;
98178                 }
98179                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
98180                     if (preserveSourceNewlines) {
98181                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
98182                     }
98183                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
98184                 }
98185                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
98186                     return 1;
98187                 }
98188             }
98189             else if (ts.getStartsOnNewLine(nextNode)) {
98190                 return 1;
98191             }
98192             return format & 1 /* MultiLine */ ? 1 : 0;
98193         }
98194         function getClosingLineTerminatorCount(parentNode, children, format) {
98195             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98196                 if (format & 65536 /* PreferNewLine */) {
98197                     return 1;
98198                 }
98199                 var lastChild_1 = ts.lastOrUndefined(children);
98200                 if (lastChild_1 === undefined) {
98201                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98202                 }
98203                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) {
98204                     if (preserveSourceNewlines) {
98205                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); });
98206                     }
98207                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1;
98208                 }
98209                 if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) {
98210                     return 1;
98211                 }
98212             }
98213             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
98214                 return 1;
98215             }
98216             return 0;
98217         }
98218         function getEffectiveLines(getLineDifference) {
98219             // If 'preserveSourceNewlines' is disabled, we should never call this function
98220             // because it could be more expensive than alternative approximations.
98221             ts.Debug.assert(!!preserveSourceNewlines);
98222             // We start by measuring the line difference from a position to its adjacent comments,
98223             // so that this is counted as a one-line difference, not two:
98224             //
98225             //   node1;
98226             //   // NODE2 COMMENT
98227             //   node2;
98228             var lines = getLineDifference(/*includeComments*/ true);
98229             if (lines === 0) {
98230                 // However, if the line difference considering comments was 0, we might have this:
98231                 //
98232                 //   node1; // NODE2 COMMENT
98233                 //   node2;
98234                 //
98235                 // in which case we should be ignoring node2's comment, so this too is counted as
98236                 // a one-line difference, not zero.
98237                 return getLineDifference(/*includeComments*/ false);
98238             }
98239             return lines;
98240         }
98241         function writeLineSeparatorsAndIndentBefore(node, parent) {
98242             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
98243             if (leadingNewlines) {
98244                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
98245             }
98246             return !!leadingNewlines;
98247         }
98248         function writeLineSeparatorsAfter(node, parent) {
98249             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
98250             if (trailingNewlines) {
98251                 writeLine(trailingNewlines);
98252             }
98253         }
98254         function synthesizedNodeStartsOnNewLine(node, format) {
98255             if (ts.nodeIsSynthesized(node)) {
98256                 var startsOnNewLine = ts.getStartsOnNewLine(node);
98257                 if (startsOnNewLine === undefined) {
98258                     return (format & 65536 /* PreferNewLine */) !== 0;
98259                 }
98260                 return startsOnNewLine;
98261             }
98262             return (format & 65536 /* PreferNewLine */) !== 0;
98263         }
98264         function getLinesBetweenNodes(parent, node1, node2) {
98265             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
98266                 return 0;
98267             }
98268             parent = skipSynthesizedParentheses(parent);
98269             node1 = skipSynthesizedParentheses(node1);
98270             node2 = skipSynthesizedParentheses(node2);
98271             // Always use a newline for synthesized code if the synthesizer desires it.
98272             if (ts.getStartsOnNewLine(node2)) {
98273                 return 1;
98274             }
98275             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
98276                 if (preserveSourceNewlines) {
98277                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
98278                 }
98279                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
98280             }
98281             return 0;
98282         }
98283         function isEmptyBlock(block) {
98284             return block.statements.length === 0
98285                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
98286         }
98287         function skipSynthesizedParentheses(node) {
98288             while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
98289                 node = node.expression;
98290             }
98291             return node;
98292         }
98293         function getTextOfNode(node, includeTrivia) {
98294             if (ts.isGeneratedIdentifier(node)) {
98295                 return generateName(node);
98296             }
98297             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
98298                 return ts.idText(node);
98299             }
98300             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98301                 return getTextOfNode(node.textSourceNode, includeTrivia);
98302             }
98303             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
98304                 return node.text;
98305             }
98306             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
98307         }
98308         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
98309             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98310                 var textSourceNode = node.textSourceNode;
98311                 if (ts.isIdentifier(textSourceNode)) {
98312                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
98313                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
98314                             "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
98315                 }
98316                 else {
98317                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
98318                 }
98319             }
98320             return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
98321         }
98322         /**
98323          * Push a new name generation scope.
98324          */
98325         function pushNameGenerationScope(node) {
98326             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98327                 return;
98328             }
98329             tempFlagsStack.push(tempFlags);
98330             tempFlags = 0;
98331             reservedNamesStack.push(reservedNames);
98332         }
98333         /**
98334          * Pop the current name generation scope.
98335          */
98336         function popNameGenerationScope(node) {
98337             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98338                 return;
98339             }
98340             tempFlags = tempFlagsStack.pop();
98341             reservedNames = reservedNamesStack.pop();
98342         }
98343         function reserveNameInNestedScopes(name) {
98344             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
98345                 reservedNames = ts.createMap();
98346             }
98347             reservedNames.set(name, true);
98348         }
98349         function generateNames(node) {
98350             if (!node)
98351                 return;
98352             switch (node.kind) {
98353                 case 223 /* Block */:
98354                     ts.forEach(node.statements, generateNames);
98355                     break;
98356                 case 238 /* LabeledStatement */:
98357                 case 236 /* WithStatement */:
98358                 case 228 /* DoStatement */:
98359                 case 229 /* WhileStatement */:
98360                     generateNames(node.statement);
98361                     break;
98362                 case 227 /* IfStatement */:
98363                     generateNames(node.thenStatement);
98364                     generateNames(node.elseStatement);
98365                     break;
98366                 case 230 /* ForStatement */:
98367                 case 232 /* ForOfStatement */:
98368                 case 231 /* ForInStatement */:
98369                     generateNames(node.initializer);
98370                     generateNames(node.statement);
98371                     break;
98372                 case 237 /* SwitchStatement */:
98373                     generateNames(node.caseBlock);
98374                     break;
98375                 case 251 /* CaseBlock */:
98376                     ts.forEach(node.clauses, generateNames);
98377                     break;
98378                 case 277 /* CaseClause */:
98379                 case 278 /* DefaultClause */:
98380                     ts.forEach(node.statements, generateNames);
98381                     break;
98382                 case 240 /* TryStatement */:
98383                     generateNames(node.tryBlock);
98384                     generateNames(node.catchClause);
98385                     generateNames(node.finallyBlock);
98386                     break;
98387                 case 280 /* CatchClause */:
98388                     generateNames(node.variableDeclaration);
98389                     generateNames(node.block);
98390                     break;
98391                 case 225 /* VariableStatement */:
98392                     generateNames(node.declarationList);
98393                     break;
98394                 case 243 /* VariableDeclarationList */:
98395                     ts.forEach(node.declarations, generateNames);
98396                     break;
98397                 case 242 /* VariableDeclaration */:
98398                 case 156 /* Parameter */:
98399                 case 191 /* BindingElement */:
98400                 case 245 /* ClassDeclaration */:
98401                     generateNameIfNeeded(node.name);
98402                     break;
98403                 case 244 /* FunctionDeclaration */:
98404                     generateNameIfNeeded(node.name);
98405                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98406                         ts.forEach(node.parameters, generateNames);
98407                         generateNames(node.body);
98408                     }
98409                     break;
98410                 case 189 /* ObjectBindingPattern */:
98411                 case 190 /* ArrayBindingPattern */:
98412                     ts.forEach(node.elements, generateNames);
98413                     break;
98414                 case 254 /* ImportDeclaration */:
98415                     generateNames(node.importClause);
98416                     break;
98417                 case 255 /* ImportClause */:
98418                     generateNameIfNeeded(node.name);
98419                     generateNames(node.namedBindings);
98420                     break;
98421                 case 256 /* NamespaceImport */:
98422                     generateNameIfNeeded(node.name);
98423                     break;
98424                 case 262 /* NamespaceExport */:
98425                     generateNameIfNeeded(node.name);
98426                     break;
98427                 case 257 /* NamedImports */:
98428                     ts.forEach(node.elements, generateNames);
98429                     break;
98430                 case 258 /* ImportSpecifier */:
98431                     generateNameIfNeeded(node.propertyName || node.name);
98432                     break;
98433             }
98434         }
98435         function generateMemberNames(node) {
98436             if (!node)
98437                 return;
98438             switch (node.kind) {
98439                 case 281 /* PropertyAssignment */:
98440                 case 282 /* ShorthandPropertyAssignment */:
98441                 case 159 /* PropertyDeclaration */:
98442                 case 161 /* MethodDeclaration */:
98443                 case 163 /* GetAccessor */:
98444                 case 164 /* SetAccessor */:
98445                     generateNameIfNeeded(node.name);
98446                     break;
98447             }
98448         }
98449         function generateNameIfNeeded(name) {
98450             if (name) {
98451                 if (ts.isGeneratedIdentifier(name)) {
98452                     generateName(name);
98453                 }
98454                 else if (ts.isBindingPattern(name)) {
98455                     generateNames(name);
98456                 }
98457             }
98458         }
98459         /**
98460          * Generate the text for a generated identifier.
98461          */
98462         function generateName(name) {
98463             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
98464                 // Node names generate unique names based on their original node
98465                 // and are cached based on that node's id.
98466                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
98467             }
98468             else {
98469                 // Auto, Loop, and Unique names are cached based on their unique
98470                 // autoGenerateId.
98471                 var autoGenerateId = name.autoGenerateId;
98472                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
98473             }
98474         }
98475         function generateNameCached(node, flags) {
98476             var nodeId = ts.getNodeId(node);
98477             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
98478         }
98479         /**
98480          * Returns a value indicating whether a name is unique globally, within the current file,
98481          * or within the NameGenerator.
98482          */
98483         function isUniqueName(name) {
98484             return isFileLevelUniqueName(name)
98485                 && !generatedNames.has(name)
98486                 && !(reservedNames && reservedNames.has(name));
98487         }
98488         /**
98489          * Returns a value indicating whether a name is unique globally or within the current file.
98490          */
98491         function isFileLevelUniqueName(name) {
98492             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
98493         }
98494         /**
98495          * Returns a value indicating whether a name is unique within a container.
98496          */
98497         function isUniqueLocalName(name, container) {
98498             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
98499                 if (node.locals) {
98500                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
98501                     // We conservatively include alias symbols to cover cases where they're emitted as locals
98502                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
98503                         return false;
98504                     }
98505                 }
98506             }
98507             return true;
98508         }
98509         /**
98510          * Return the next available name in the pattern _a ... _z, _0, _1, ...
98511          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
98512          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
98513          */
98514         function makeTempVariableName(flags, reservedInNestedScopes) {
98515             if (flags && !(tempFlags & flags)) {
98516                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
98517                 if (isUniqueName(name)) {
98518                     tempFlags |= flags;
98519                     if (reservedInNestedScopes) {
98520                         reserveNameInNestedScopes(name);
98521                     }
98522                     return name;
98523                 }
98524             }
98525             while (true) {
98526                 var count = tempFlags & 268435455 /* CountMask */;
98527                 tempFlags++;
98528                 // Skip over 'i' and 'n'
98529                 if (count !== 8 && count !== 13) {
98530                     var name = count < 26
98531                         ? "_" + String.fromCharCode(97 /* a */ + count)
98532                         : "_" + (count - 26);
98533                     if (isUniqueName(name)) {
98534                         if (reservedInNestedScopes) {
98535                             reserveNameInNestedScopes(name);
98536                         }
98537                         return name;
98538                     }
98539                 }
98540             }
98541         }
98542         /**
98543          * Generate a name that is unique within the current file and doesn't conflict with any names
98544          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
98545          * where n is a positive integer. Note that names generated by makeTempVariableName and
98546          * makeUniqueName are guaranteed to never conflict.
98547          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
98548          */
98549         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
98550             if (checkFn === void 0) { checkFn = isUniqueName; }
98551             if (optimistic) {
98552                 if (checkFn(baseName)) {
98553                     if (scoped) {
98554                         reserveNameInNestedScopes(baseName);
98555                     }
98556                     else {
98557                         generatedNames.set(baseName, true);
98558                     }
98559                     return baseName;
98560                 }
98561             }
98562             // Find the first unique 'name_n', where n is a positive number
98563             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
98564                 baseName += "_";
98565             }
98566             var i = 1;
98567             while (true) {
98568                 var generatedName = baseName + i;
98569                 if (checkFn(generatedName)) {
98570                     if (scoped) {
98571                         reserveNameInNestedScopes(generatedName);
98572                     }
98573                     else {
98574                         generatedNames.set(generatedName, true);
98575                     }
98576                     return generatedName;
98577                 }
98578                 i++;
98579             }
98580         }
98581         function makeFileLevelOptimisticUniqueName(name) {
98582             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
98583         }
98584         /**
98585          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
98586          */
98587         function generateNameForModuleOrEnum(node) {
98588             var name = getTextOfNode(node.name);
98589             // Use module/enum name itself if it is unique, otherwise make a unique variation
98590             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
98591         }
98592         /**
98593          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
98594          */
98595         function generateNameForImportOrExportDeclaration(node) {
98596             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
98597             var baseName = ts.isStringLiteral(expr) ?
98598                 ts.makeIdentifierFromModuleName(expr.text) : "module";
98599             return makeUniqueName(baseName);
98600         }
98601         /**
98602          * Generates a unique name for a default export.
98603          */
98604         function generateNameForExportDefault() {
98605             return makeUniqueName("default");
98606         }
98607         /**
98608          * Generates a unique name for a class expression.
98609          */
98610         function generateNameForClassExpression() {
98611             return makeUniqueName("class");
98612         }
98613         function generateNameForMethodOrAccessor(node) {
98614             if (ts.isIdentifier(node.name)) {
98615                 return generateNameCached(node.name);
98616             }
98617             return makeTempVariableName(0 /* Auto */);
98618         }
98619         /**
98620          * Generates a unique name from a node.
98621          */
98622         function generateNameForNode(node, flags) {
98623             switch (node.kind) {
98624                 case 75 /* Identifier */:
98625                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
98626                 case 249 /* ModuleDeclaration */:
98627                 case 248 /* EnumDeclaration */:
98628                     return generateNameForModuleOrEnum(node);
98629                 case 254 /* ImportDeclaration */:
98630                 case 260 /* ExportDeclaration */:
98631                     return generateNameForImportOrExportDeclaration(node);
98632                 case 244 /* FunctionDeclaration */:
98633                 case 245 /* ClassDeclaration */:
98634                 case 259 /* ExportAssignment */:
98635                     return generateNameForExportDefault();
98636                 case 214 /* ClassExpression */:
98637                     return generateNameForClassExpression();
98638                 case 161 /* MethodDeclaration */:
98639                 case 163 /* GetAccessor */:
98640                 case 164 /* SetAccessor */:
98641                     return generateNameForMethodOrAccessor(node);
98642                 case 154 /* ComputedPropertyName */:
98643                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
98644                 default:
98645                     return makeTempVariableName(0 /* Auto */);
98646             }
98647         }
98648         /**
98649          * Generates a unique identifier for a node.
98650          */
98651         function makeName(name) {
98652             switch (name.autoGenerateFlags & 7 /* KindMask */) {
98653                 case 1 /* Auto */:
98654                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98655                 case 2 /* Loop */:
98656                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98657                 case 3 /* Unique */:
98658                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98659             }
98660             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
98661         }
98662         /**
98663          * Gets the node from which a name should be generated.
98664          */
98665         function getNodeForGeneratedName(name) {
98666             var autoGenerateId = name.autoGenerateId;
98667             var node = name;
98668             var original = node.original;
98669             while (original) {
98670                 node = original;
98671                 // if "node" is a different generated name (having a different
98672                 // "autoGenerateId"), use it and stop traversing.
98673                 if (ts.isIdentifier(node)
98674                     && !!(node.autoGenerateFlags & 4 /* Node */)
98675                     && node.autoGenerateId !== autoGenerateId) {
98676                     break;
98677                 }
98678                 original = node.original;
98679             }
98680             // otherwise, return the original node for the source;
98681             return node;
98682         }
98683         // Comments
98684         function pipelineEmitWithComments(hint, node) {
98685             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98686             enterComment();
98687             hasWrittenComment = false;
98688             var emitFlags = ts.getEmitFlags(node);
98689             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
98690             var isEmittedNode = node.kind !== 325 /* NotEmittedStatement */;
98691             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
98692             // It is expensive to walk entire tree just to set one kind of node to have no comments.
98693             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
98694             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
98695             // Save current container state on the stack.
98696             var savedContainerPos = containerPos;
98697             var savedContainerEnd = containerEnd;
98698             var savedDeclarationListContainerEnd = declarationListContainerEnd;
98699             if ((pos > 0 || end > 0) && pos !== end) {
98700                 // Emit leading comments if the position is not synthesized and the node
98701                 // has not opted out from emitting leading comments.
98702                 if (!skipLeadingComments) {
98703                     emitLeadingComments(pos, isEmittedNode);
98704                 }
98705                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
98706                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
98707                     containerPos = pos;
98708                 }
98709                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
98710                     // As above.
98711                     containerEnd = end;
98712                     // To avoid invalid comment emit in a down-level binding pattern, we
98713                     // keep track of the last declaration list container's end
98714                     if (node.kind === 243 /* VariableDeclarationList */) {
98715                         declarationListContainerEnd = end;
98716                     }
98717                 }
98718             }
98719             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
98720             exitComment();
98721             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
98722             if (emitFlags & 2048 /* NoNestedComments */) {
98723                 commentsDisabled = true;
98724                 pipelinePhase(hint, node);
98725                 commentsDisabled = false;
98726             }
98727             else {
98728                 pipelinePhase(hint, node);
98729             }
98730             enterComment();
98731             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
98732             if ((pos > 0 || end > 0) && pos !== end) {
98733                 // Restore previous container state.
98734                 containerPos = savedContainerPos;
98735                 containerEnd = savedContainerEnd;
98736                 declarationListContainerEnd = savedDeclarationListContainerEnd;
98737                 // Emit trailing comments if the position is not synthesized and the node
98738                 // has not opted out from emitting leading comments and is an emitted node.
98739                 if (!skipTrailingComments && isEmittedNode) {
98740                     emitTrailingComments(end);
98741                 }
98742             }
98743             exitComment();
98744             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98745         }
98746         function emitLeadingSynthesizedComment(comment) {
98747             if (comment.kind === 2 /* SingleLineCommentTrivia */) {
98748                 writer.writeLine();
98749             }
98750             writeSynthesizedComment(comment);
98751             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
98752                 writer.writeLine();
98753             }
98754             else {
98755                 writer.writeSpace(" ");
98756             }
98757         }
98758         function emitTrailingSynthesizedComment(comment) {
98759             if (!writer.isAtStartOfLine()) {
98760                 writer.writeSpace(" ");
98761             }
98762             writeSynthesizedComment(comment);
98763             if (comment.hasTrailingNewLine) {
98764                 writer.writeLine();
98765             }
98766         }
98767         function writeSynthesizedComment(comment) {
98768             var text = formatSynthesizedComment(comment);
98769             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
98770             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
98771         }
98772         function formatSynthesizedComment(comment) {
98773             return comment.kind === 3 /* MultiLineCommentTrivia */
98774                 ? "/*" + comment.text + "*/"
98775                 : "//" + comment.text;
98776         }
98777         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
98778             enterComment();
98779             var pos = detachedRange.pos, end = detachedRange.end;
98780             var emitFlags = ts.getEmitFlags(node);
98781             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
98782             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
98783             if (!skipLeadingComments) {
98784                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
98785             }
98786             exitComment();
98787             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
98788                 commentsDisabled = true;
98789                 emitCallback(node);
98790                 commentsDisabled = false;
98791             }
98792             else {
98793                 emitCallback(node);
98794             }
98795             enterComment();
98796             if (!skipTrailingComments) {
98797                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
98798                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
98799                     writer.writeLine();
98800                 }
98801             }
98802             exitComment();
98803         }
98804         function emitLeadingComments(pos, isEmittedNode) {
98805             hasWrittenComment = false;
98806             if (isEmittedNode) {
98807                 forEachLeadingCommentToEmit(pos, emitLeadingComment);
98808             }
98809             else if (pos === 0) {
98810                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
98811                 // unless it is a triple slash comment at the top of the file.
98812                 // For Example:
98813                 //      /// <reference-path ...>
98814                 //      declare var x;
98815                 //      /// <reference-path ...>
98816                 //      interface F {}
98817                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
98818                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
98819             }
98820         }
98821         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98822             if (isTripleSlashComment(commentPos, commentEnd)) {
98823                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
98824             }
98825         }
98826         function shouldWriteComment(text, pos) {
98827             if (printerOptions.onlyPrintJsDocStyle) {
98828                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
98829             }
98830             return true;
98831         }
98832         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98833             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98834                 return;
98835             if (!hasWrittenComment) {
98836                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
98837                 hasWrittenComment = true;
98838             }
98839             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
98840             emitPos(commentPos);
98841             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98842             emitPos(commentEnd);
98843             if (hasTrailingNewLine) {
98844                 writer.writeLine();
98845             }
98846             else if (kind === 3 /* MultiLineCommentTrivia */) {
98847                 writer.writeSpace(" ");
98848             }
98849         }
98850         function emitLeadingCommentsOfPosition(pos) {
98851             if (commentsDisabled || pos === -1) {
98852                 return;
98853             }
98854             emitLeadingComments(pos, /*isEmittedNode*/ true);
98855         }
98856         function emitTrailingComments(pos) {
98857             forEachTrailingCommentToEmit(pos, emitTrailingComment);
98858         }
98859         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98860             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98861                 return;
98862             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
98863             if (!writer.isAtStartOfLine()) {
98864                 writer.writeSpace(" ");
98865             }
98866             emitPos(commentPos);
98867             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98868             emitPos(commentEnd);
98869             if (hasTrailingNewLine) {
98870                 writer.writeLine();
98871             }
98872         }
98873         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
98874             if (commentsDisabled) {
98875                 return;
98876             }
98877             enterComment();
98878             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
98879             exitComment();
98880         }
98881         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98882             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
98883             emitPos(commentPos);
98884             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98885             emitPos(commentEnd);
98886             if (hasTrailingNewLine) {
98887                 writer.writeLine();
98888             }
98889             else {
98890                 writer.writeSpace(" ");
98891             }
98892         }
98893         function forEachLeadingCommentToEmit(pos, cb) {
98894             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
98895             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
98896                 if (hasDetachedComments(pos)) {
98897                     forEachLeadingCommentWithoutDetachedComments(cb);
98898                 }
98899                 else {
98900                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98901                 }
98902             }
98903         }
98904         function forEachTrailingCommentToEmit(end, cb) {
98905             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
98906             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
98907                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
98908             }
98909         }
98910         function hasDetachedComments(pos) {
98911             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
98912         }
98913         function forEachLeadingCommentWithoutDetachedComments(cb) {
98914             // get the leading comments from detachedPos
98915             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
98916             if (detachedCommentsInfo.length - 1) {
98917                 detachedCommentsInfo.pop();
98918             }
98919             else {
98920                 detachedCommentsInfo = undefined;
98921             }
98922             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98923         }
98924         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
98925             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
98926             if (currentDetachedCommentInfo) {
98927                 if (detachedCommentsInfo) {
98928                     detachedCommentsInfo.push(currentDetachedCommentInfo);
98929                 }
98930                 else {
98931                     detachedCommentsInfo = [currentDetachedCommentInfo];
98932                 }
98933             }
98934         }
98935         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
98936             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98937                 return;
98938             emitPos(commentPos);
98939             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
98940             emitPos(commentEnd);
98941         }
98942         /**
98943          * Determine if the given comment is a triple-slash
98944          *
98945          * @return true if the comment is a triple-slash comment else false
98946          */
98947         function isTripleSlashComment(commentPos, commentEnd) {
98948             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
98949         }
98950         // Source Maps
98951         function getParsedSourceMap(node) {
98952             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
98953                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
98954             }
98955             return node.parsedSourceMap || undefined;
98956         }
98957         function pipelineEmitWithSourceMap(hint, node) {
98958             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98959             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
98960             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
98961                 pipelinePhase(hint, node);
98962             }
98963             else if (ts.isUnparsedNode(node)) {
98964                 var parsed = getParsedSourceMap(node.parent);
98965                 if (parsed && sourceMapGenerator) {
98966                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
98967                 }
98968                 pipelinePhase(hint, node);
98969             }
98970             else {
98971                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
98972                 var emitFlags = ts.getEmitFlags(node);
98973                 if (node.kind !== 325 /* NotEmittedStatement */
98974                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
98975                     && pos >= 0) {
98976                     emitSourcePos(source, skipSourceTrivia(source, pos));
98977                 }
98978                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
98979                     sourceMapsDisabled = true;
98980                     pipelinePhase(hint, node);
98981                     sourceMapsDisabled = false;
98982                 }
98983                 else {
98984                     pipelinePhase(hint, node);
98985                 }
98986                 if (node.kind !== 325 /* NotEmittedStatement */
98987                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
98988                     && end >= 0) {
98989                     emitSourcePos(source, end);
98990                 }
98991             }
98992             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98993         }
98994         /**
98995          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
98996          */
98997         function skipSourceTrivia(source, pos) {
98998             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
98999         }
99000         /**
99001          * Emits a mapping.
99002          *
99003          * If the position is synthetic (undefined or a negative value), no mapping will be
99004          * created.
99005          *
99006          * @param pos The position.
99007          */
99008         function emitPos(pos) {
99009             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
99010                 return;
99011             }
99012             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
99013             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
99014             /*nameIndex*/ undefined);
99015         }
99016         function emitSourcePos(source, pos) {
99017             if (source !== sourceMapSource) {
99018                 var savedSourceMapSource = sourceMapSource;
99019                 setSourceMapSource(source);
99020                 emitPos(pos);
99021                 setSourceMapSource(savedSourceMapSource);
99022             }
99023             else {
99024                 emitPos(pos);
99025             }
99026         }
99027         /**
99028          * Emits a token of a node with possible leading and trailing source maps.
99029          *
99030          * @param node The node containing the token.
99031          * @param token The token to emit.
99032          * @param tokenStartPos The start pos of the token.
99033          * @param emitCallback The callback used to emit the token.
99034          */
99035         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
99036             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
99037                 return emitCallback(token, writer, tokenPos);
99038             }
99039             var emitNode = node && node.emitNode;
99040             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
99041             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
99042             var source = range && range.source || sourceMapSource;
99043             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
99044             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
99045                 emitSourcePos(source, tokenPos);
99046             }
99047             tokenPos = emitCallback(token, writer, tokenPos);
99048             if (range)
99049                 tokenPos = range.end;
99050             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
99051                 emitSourcePos(source, tokenPos);
99052             }
99053             return tokenPos;
99054         }
99055         function setSourceMapSource(source) {
99056             if (sourceMapsDisabled) {
99057                 return;
99058             }
99059             sourceMapSource = source;
99060             if (isJsonSourceMapSource(source)) {
99061                 return;
99062             }
99063             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
99064             if (printerOptions.inlineSources) {
99065                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
99066             }
99067         }
99068         function isJsonSourceMapSource(sourceFile) {
99069             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
99070         }
99071     }
99072     ts.createPrinter = createPrinter;
99073     function createBracketsMap() {
99074         var brackets = [];
99075         brackets[1024 /* Braces */] = ["{", "}"];
99076         brackets[2048 /* Parenthesis */] = ["(", ")"];
99077         brackets[4096 /* AngleBrackets */] = ["<", ">"];
99078         brackets[8192 /* SquareBrackets */] = ["[", "]"];
99079         return brackets;
99080     }
99081     function getOpeningBracket(format) {
99082         return brackets[format & 15360 /* BracketsMask */][0];
99083     }
99084     function getClosingBracket(format) {
99085         return brackets[format & 15360 /* BracketsMask */][1];
99086     }
99087     // Flags enum to track count of temp variables and a few dedicated names
99088     var TempFlags;
99089     (function (TempFlags) {
99090         TempFlags[TempFlags["Auto"] = 0] = "Auto";
99091         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
99092         TempFlags[TempFlags["_i"] = 268435456] = "_i";
99093     })(TempFlags || (TempFlags = {}));
99094 })(ts || (ts = {}));
99095 /* @internal */
99096 var ts;
99097 (function (ts) {
99098     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
99099         if (!host.getDirectories || !host.readDirectory) {
99100             return undefined;
99101         }
99102         var cachedReadDirectoryResult = ts.createMap();
99103         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
99104         return {
99105             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
99106             fileExists: fileExists,
99107             readFile: function (path, encoding) { return host.readFile(path, encoding); },
99108             directoryExists: host.directoryExists && directoryExists,
99109             getDirectories: getDirectories,
99110             readDirectory: readDirectory,
99111             createDirectory: host.createDirectory && createDirectory,
99112             writeFile: host.writeFile && writeFile,
99113             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
99114             addOrDeleteFile: addOrDeleteFile,
99115             clearCache: clearCache,
99116             realpath: host.realpath && realpath
99117         };
99118         function toPath(fileName) {
99119             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
99120         }
99121         function getCachedFileSystemEntries(rootDirPath) {
99122             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
99123         }
99124         function getCachedFileSystemEntriesForBaseDir(path) {
99125             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
99126         }
99127         function getBaseNameOfFileName(fileName) {
99128             return ts.getBaseFileName(ts.normalizePath(fileName));
99129         }
99130         function createCachedFileSystemEntries(rootDir, rootDirPath) {
99131             var resultFromHost = {
99132                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
99133                 directories: host.getDirectories(rootDir) || []
99134             };
99135             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
99136             return resultFromHost;
99137         }
99138         /**
99139          * If the readDirectory result was already cached, it returns that
99140          * Otherwise gets result from host and caches it.
99141          * The host request is done under try catch block to avoid caching incorrect result
99142          */
99143         function tryReadDirectory(rootDir, rootDirPath) {
99144             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
99145             var cachedResult = getCachedFileSystemEntries(rootDirPath);
99146             if (cachedResult) {
99147                 return cachedResult;
99148             }
99149             try {
99150                 return createCachedFileSystemEntries(rootDir, rootDirPath);
99151             }
99152             catch (_e) {
99153                 // If there is exception to read directories, dont cache the result and direct the calls to host
99154                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
99155                 return undefined;
99156             }
99157         }
99158         function fileNameEqual(name1, name2) {
99159             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
99160         }
99161         function hasEntry(entries, name) {
99162             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
99163         }
99164         function updateFileSystemEntry(entries, baseName, isValid) {
99165             if (hasEntry(entries, baseName)) {
99166                 if (!isValid) {
99167                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
99168                 }
99169             }
99170             else if (isValid) {
99171                 return entries.push(baseName);
99172             }
99173         }
99174         function writeFile(fileName, data, writeByteOrderMark) {
99175             var path = toPath(fileName);
99176             var result = getCachedFileSystemEntriesForBaseDir(path);
99177             if (result) {
99178                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
99179             }
99180             return host.writeFile(fileName, data, writeByteOrderMark);
99181         }
99182         function fileExists(fileName) {
99183             var path = toPath(fileName);
99184             var result = getCachedFileSystemEntriesForBaseDir(path);
99185             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
99186                 host.fileExists(fileName);
99187         }
99188         function directoryExists(dirPath) {
99189             var path = toPath(dirPath);
99190             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
99191         }
99192         function createDirectory(dirPath) {
99193             var path = toPath(dirPath);
99194             var result = getCachedFileSystemEntriesForBaseDir(path);
99195             var baseFileName = getBaseNameOfFileName(dirPath);
99196             if (result) {
99197                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
99198             }
99199             host.createDirectory(dirPath);
99200         }
99201         function getDirectories(rootDir) {
99202             var rootDirPath = toPath(rootDir);
99203             var result = tryReadDirectory(rootDir, rootDirPath);
99204             if (result) {
99205                 return result.directories.slice();
99206             }
99207             return host.getDirectories(rootDir);
99208         }
99209         function readDirectory(rootDir, extensions, excludes, includes, depth) {
99210             var rootDirPath = toPath(rootDir);
99211             var result = tryReadDirectory(rootDir, rootDirPath);
99212             if (result) {
99213                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
99214             }
99215             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
99216             function getFileSystemEntries(dir) {
99217                 var path = toPath(dir);
99218                 if (path === rootDirPath) {
99219                     return result;
99220                 }
99221                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
99222             }
99223         }
99224         function realpath(s) {
99225             return host.realpath ? host.realpath(s) : s;
99226         }
99227         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
99228             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
99229             if (existingResult) {
99230                 // Just clear the cache for now
99231                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
99232                 clearCache();
99233                 return undefined;
99234             }
99235             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
99236             if (!parentResult) {
99237                 return undefined;
99238             }
99239             // This was earlier a file (hence not in cached directory contents)
99240             // or we never cached the directory containing it
99241             if (!host.directoryExists) {
99242                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
99243                 clearCache();
99244                 return undefined;
99245             }
99246             var baseName = getBaseNameOfFileName(fileOrDirectory);
99247             var fsQueryResult = {
99248                 fileExists: host.fileExists(fileOrDirectoryPath),
99249                 directoryExists: host.directoryExists(fileOrDirectoryPath)
99250             };
99251             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
99252                 // Folder added or removed, clear the cache instead of updating the folder and its structure
99253                 clearCache();
99254             }
99255             else {
99256                 // No need to update the directory structure, just files
99257                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
99258             }
99259             return fsQueryResult;
99260         }
99261         function addOrDeleteFile(fileName, filePath, eventKind) {
99262             if (eventKind === ts.FileWatcherEventKind.Changed) {
99263                 return;
99264             }
99265             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
99266             if (parentResult) {
99267                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
99268             }
99269         }
99270         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
99271             updateFileSystemEntry(parentResult.files, baseName, fileExists);
99272         }
99273         function clearCache() {
99274             cachedReadDirectoryResult.clear();
99275         }
99276     }
99277     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
99278     var ConfigFileProgramReloadLevel;
99279     (function (ConfigFileProgramReloadLevel) {
99280         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
99281         /** Update the file name list from the disk */
99282         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
99283         /** Reload completely by re-reading contents of config file from disk and updating program */
99284         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
99285     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
99286     /**
99287      * Updates the existing missing file watches with the new set of missing files after new program is created
99288      */
99289     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
99290         var missingFilePaths = program.getMissingFilePaths();
99291         var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
99292         // Update the missing file paths watcher
99293         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
99294             // Watch the missing files
99295             createNewValue: createMissingFileWatch,
99296             // Files that are no longer missing (e.g. because they are no longer required)
99297             // should no longer be watched.
99298             onDeleteValue: ts.closeFileWatcher
99299         });
99300     }
99301     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
99302     /**
99303      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
99304      * after new program is created because the config file was reloaded or program was created first time from the config file
99305      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
99306      * as wildcard directories wont change unless reloading config file
99307      */
99308     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
99309         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
99310             // Create new watch and recursive info
99311             createNewValue: createWildcardDirectoryWatcher,
99312             // Close existing watch thats not needed any more
99313             onDeleteValue: closeFileWatcherOf,
99314             // Close existing watch that doesnt match in the flags
99315             onExistingValue: updateWildcardDirectoryWatcher
99316         });
99317         function createWildcardDirectoryWatcher(directory, flags) {
99318             // Create new watch and recursive info
99319             return {
99320                 watcher: watchDirectory(directory, flags),
99321                 flags: flags
99322             };
99323         }
99324         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
99325             // Watcher needs to be updated if the recursive flags dont match
99326             if (existingWatcher.flags === flags) {
99327                 return;
99328             }
99329             existingWatcher.watcher.close();
99330             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
99331         }
99332     }
99333     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
99334     function isEmittedFileOfProgram(program, file) {
99335         if (!program) {
99336             return false;
99337         }
99338         return program.isEmittedFile(file);
99339     }
99340     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
99341     var WatchLogLevel;
99342     (function (WatchLogLevel) {
99343         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
99344         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
99345         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
99346     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
99347     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
99348         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
99349     }
99350     ts.getWatchFactory = getWatchFactory;
99351     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
99352         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
99353         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
99354         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
99355         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
99356             ts.setSysLog(function (s) { return log(s); });
99357         }
99358         return {
99359             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
99360                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99361             },
99362             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
99363                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99364             },
99365             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
99366                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
99367             }
99368         };
99369     }
99370     function watchFile(host, file, callback, pollingInterval, options) {
99371         return host.watchFile(file, callback, pollingInterval, options);
99372     }
99373     function watchFilePath(host, file, callback, pollingInterval, options, path) {
99374         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
99375     }
99376     function watchDirectory(host, directory, callback, flags, options) {
99377         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
99378     }
99379     function getCreateFileWatcher(watchLogLevel, addWatch) {
99380         switch (watchLogLevel) {
99381             case WatchLogLevel.None:
99382                 return addWatch;
99383             case WatchLogLevel.TriggerOnly:
99384                 return createFileWatcherWithTriggerLogging;
99385             case WatchLogLevel.Verbose:
99386                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
99387         }
99388     }
99389     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99390         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99391         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99392         return {
99393             close: function () {
99394                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99395                 watcher.close();
99396             }
99397         };
99398     }
99399     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99400         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99401         log(watchInfo);
99402         var start = ts.timestamp();
99403         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99404         var elapsed = ts.timestamp() - start;
99405         log("Elapsed:: " + elapsed + "ms " + watchInfo);
99406         return {
99407             close: function () {
99408                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99409                 log(watchInfo);
99410                 var start = ts.timestamp();
99411                 watcher.close();
99412                 var elapsed = ts.timestamp() - start;
99413                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
99414             }
99415         };
99416     }
99417     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99418         return addWatch(host, file, function (fileName, cbOptional) {
99419             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99420             log(triggerredInfo);
99421             var start = ts.timestamp();
99422             cb(fileName, cbOptional, passThrough);
99423             var elapsed = ts.timestamp() - start;
99424             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
99425         }, flags, options);
99426     }
99427     function getFallbackOptions(options) {
99428         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
99429         return {
99430             watchFile: fallbackPolling !== undefined ?
99431                 fallbackPolling :
99432                 ts.WatchFileKind.PriorityPollingInterval
99433         };
99434     }
99435     ts.getFallbackOptions = getFallbackOptions;
99436     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
99437         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
99438     }
99439     function closeFileWatcherOf(objWithWatcher) {
99440         objWithWatcher.watcher.close();
99441     }
99442     ts.closeFileWatcherOf = closeFileWatcherOf;
99443 })(ts || (ts = {}));
99444 var ts;
99445 (function (ts) {
99446     function findConfigFile(searchPath, fileExists, configName) {
99447         if (configName === void 0) { configName = "tsconfig.json"; }
99448         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
99449             var fileName = ts.combinePaths(ancestor, configName);
99450             return fileExists(fileName) ? fileName : undefined;
99451         });
99452     }
99453     ts.findConfigFile = findConfigFile;
99454     function resolveTripleslashReference(moduleName, containingFile) {
99455         var basePath = ts.getDirectoryPath(containingFile);
99456         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
99457         return ts.normalizePath(referencedFileName);
99458     }
99459     ts.resolveTripleslashReference = resolveTripleslashReference;
99460     /* @internal */
99461     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
99462         var commonPathComponents;
99463         var failed = ts.forEach(fileNames, function (sourceFile) {
99464             // Each file contributes into common source file path
99465             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
99466             sourcePathComponents.pop(); // The base file name is not part of the common directory path
99467             if (!commonPathComponents) {
99468                 // first file
99469                 commonPathComponents = sourcePathComponents;
99470                 return;
99471             }
99472             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
99473             for (var i = 0; i < n; i++) {
99474                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
99475                     if (i === 0) {
99476                         // Failed to find any common path component
99477                         return true;
99478                     }
99479                     // New common path found that is 0 -> i-1
99480                     commonPathComponents.length = i;
99481                     break;
99482                 }
99483             }
99484             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
99485             if (sourcePathComponents.length < commonPathComponents.length) {
99486                 commonPathComponents.length = sourcePathComponents.length;
99487             }
99488         });
99489         // A common path can not be found when paths span multiple drives on windows, for example
99490         if (failed) {
99491             return "";
99492         }
99493         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
99494             return currentDirectory;
99495         }
99496         return ts.getPathFromPathComponents(commonPathComponents);
99497     }
99498     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
99499     function createCompilerHost(options, setParentNodes) {
99500         return createCompilerHostWorker(options, setParentNodes);
99501     }
99502     ts.createCompilerHost = createCompilerHost;
99503     /*@internal*/
99504     // TODO(shkamat): update this after reworking ts build API
99505     function createCompilerHostWorker(options, setParentNodes, system) {
99506         if (system === void 0) { system = ts.sys; }
99507         var existingDirectories = ts.createMap();
99508         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
99509         function getSourceFile(fileName, languageVersion, onError) {
99510             var text;
99511             try {
99512                 ts.performance.mark("beforeIORead");
99513                 text = compilerHost.readFile(fileName);
99514                 ts.performance.mark("afterIORead");
99515                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
99516             }
99517             catch (e) {
99518                 if (onError) {
99519                     onError(e.message);
99520                 }
99521                 text = "";
99522             }
99523             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
99524         }
99525         function directoryExists(directoryPath) {
99526             if (existingDirectories.has(directoryPath)) {
99527                 return true;
99528             }
99529             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
99530                 existingDirectories.set(directoryPath, true);
99531                 return true;
99532             }
99533             return false;
99534         }
99535         function writeFile(fileName, data, writeByteOrderMark, onError) {
99536             try {
99537                 ts.performance.mark("beforeIOWrite");
99538                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
99539                 // the system.writeFile will do its own directory creation and
99540                 // the ensureDirectoriesExist call will always be redundant.
99541                 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); });
99542                 ts.performance.mark("afterIOWrite");
99543                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
99544             }
99545             catch (e) {
99546                 if (onError) {
99547                     onError(e.message);
99548                 }
99549             }
99550         }
99551         var outputFingerprints;
99552         function writeFileWorker(fileName, data, writeByteOrderMark) {
99553             if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
99554                 system.writeFile(fileName, data, writeByteOrderMark);
99555                 return;
99556             }
99557             if (!outputFingerprints) {
99558                 outputFingerprints = ts.createMap();
99559             }
99560             var hash = system.createHash(data);
99561             var mtimeBefore = system.getModifiedTime(fileName);
99562             if (mtimeBefore) {
99563                 var fingerprint = outputFingerprints.get(fileName);
99564                 // If output has not been changed, and the file has no external modification
99565                 if (fingerprint &&
99566                     fingerprint.byteOrderMark === writeByteOrderMark &&
99567                     fingerprint.hash === hash &&
99568                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
99569                     return;
99570                 }
99571             }
99572             system.writeFile(fileName, data, writeByteOrderMark);
99573             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
99574             outputFingerprints.set(fileName, {
99575                 hash: hash,
99576                 byteOrderMark: writeByteOrderMark,
99577                 mtime: mtimeAfter
99578             });
99579         }
99580         function getDefaultLibLocation() {
99581             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
99582         }
99583         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
99584         var realpath = system.realpath && (function (path) { return system.realpath(path); });
99585         var compilerHost = {
99586             getSourceFile: getSourceFile,
99587             getDefaultLibLocation: getDefaultLibLocation,
99588             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
99589             writeFile: writeFile,
99590             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
99591             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
99592             getCanonicalFileName: getCanonicalFileName,
99593             getNewLine: function () { return newLine; },
99594             fileExists: function (fileName) { return system.fileExists(fileName); },
99595             readFile: function (fileName) { return system.readFile(fileName); },
99596             trace: function (s) { return system.write(s + newLine); },
99597             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
99598             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
99599             getDirectories: function (path) { return system.getDirectories(path); },
99600             realpath: realpath,
99601             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
99602             createDirectory: function (d) { return system.createDirectory(d); },
99603             createHash: ts.maybeBind(system, system.createHash)
99604         };
99605         return compilerHost;
99606     }
99607     ts.createCompilerHostWorker = createCompilerHostWorker;
99608     /*@internal*/
99609     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
99610         var originalReadFile = host.readFile;
99611         var originalFileExists = host.fileExists;
99612         var originalDirectoryExists = host.directoryExists;
99613         var originalCreateDirectory = host.createDirectory;
99614         var originalWriteFile = host.writeFile;
99615         var readFileCache = ts.createMap();
99616         var fileExistsCache = ts.createMap();
99617         var directoryExistsCache = ts.createMap();
99618         var sourceFileCache = ts.createMap();
99619         var readFileWithCache = function (fileName) {
99620             var key = toPath(fileName);
99621             var value = readFileCache.get(key);
99622             if (value !== undefined)
99623                 return value !== false ? value : undefined;
99624             return setReadFileCache(key, fileName);
99625         };
99626         var setReadFileCache = function (key, fileName) {
99627             var newValue = originalReadFile.call(host, fileName);
99628             readFileCache.set(key, newValue !== undefined ? newValue : false);
99629             return newValue;
99630         };
99631         host.readFile = function (fileName) {
99632             var key = toPath(fileName);
99633             var value = readFileCache.get(key);
99634             if (value !== undefined)
99635                 return value !== false ? value : undefined; // could be .d.ts from output
99636             // Cache json or buildInfo
99637             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
99638                 return originalReadFile.call(host, fileName);
99639             }
99640             return setReadFileCache(key, fileName);
99641         };
99642         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
99643             var key = toPath(fileName);
99644             var value = sourceFileCache.get(key);
99645             if (value)
99646                 return value;
99647             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
99648             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
99649                 sourceFileCache.set(key, sourceFile);
99650             }
99651             return sourceFile;
99652         } : undefined;
99653         // fileExists for any kind of extension
99654         host.fileExists = function (fileName) {
99655             var key = toPath(fileName);
99656             var value = fileExistsCache.get(key);
99657             if (value !== undefined)
99658                 return value;
99659             var newValue = originalFileExists.call(host, fileName);
99660             fileExistsCache.set(key, !!newValue);
99661             return newValue;
99662         };
99663         if (originalWriteFile) {
99664             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
99665                 var key = toPath(fileName);
99666                 fileExistsCache.delete(key);
99667                 var value = readFileCache.get(key);
99668                 if (value !== undefined && value !== data) {
99669                     readFileCache.delete(key);
99670                     sourceFileCache.delete(key);
99671                 }
99672                 else if (getSourceFileWithCache) {
99673                     var sourceFile = sourceFileCache.get(key);
99674                     if (sourceFile && sourceFile.text !== data) {
99675                         sourceFileCache.delete(key);
99676                     }
99677                 }
99678                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
99679             };
99680         }
99681         // directoryExists
99682         if (originalDirectoryExists && originalCreateDirectory) {
99683             host.directoryExists = function (directory) {
99684                 var key = toPath(directory);
99685                 var value = directoryExistsCache.get(key);
99686                 if (value !== undefined)
99687                     return value;
99688                 var newValue = originalDirectoryExists.call(host, directory);
99689                 directoryExistsCache.set(key, !!newValue);
99690                 return newValue;
99691             };
99692             host.createDirectory = function (directory) {
99693                 var key = toPath(directory);
99694                 directoryExistsCache.delete(key);
99695                 originalCreateDirectory.call(host, directory);
99696             };
99697         }
99698         return {
99699             originalReadFile: originalReadFile,
99700             originalFileExists: originalFileExists,
99701             originalDirectoryExists: originalDirectoryExists,
99702             originalCreateDirectory: originalCreateDirectory,
99703             originalWriteFile: originalWriteFile,
99704             getSourceFileWithCache: getSourceFileWithCache,
99705             readFileWithCache: readFileWithCache
99706         };
99707     }
99708     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
99709     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
99710         var diagnostics;
99711         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
99712         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
99713         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
99714         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
99715         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
99716         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
99717             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
99718         }
99719         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
99720     }
99721     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
99722     function formatDiagnostics(diagnostics, host) {
99723         var output = "";
99724         for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
99725             var diagnostic = diagnostics_2[_i];
99726             output += formatDiagnostic(diagnostic, host);
99727         }
99728         return output;
99729     }
99730     ts.formatDiagnostics = formatDiagnostics;
99731     function formatDiagnostic(diagnostic, host) {
99732         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
99733         if (diagnostic.file) {
99734             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
99735             var fileName = diagnostic.file.fileName;
99736             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
99737             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
99738         }
99739         return errorMessage;
99740     }
99741     ts.formatDiagnostic = formatDiagnostic;
99742     /** @internal */
99743     var ForegroundColorEscapeSequences;
99744     (function (ForegroundColorEscapeSequences) {
99745         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
99746         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
99747         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
99748         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
99749         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
99750     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
99751     var gutterStyleSequence = "\u001b[7m";
99752     var gutterSeparator = " ";
99753     var resetEscapeSequence = "\u001b[0m";
99754     var ellipsis = "...";
99755     var halfIndent = "  ";
99756     var indent = "    ";
99757     function getCategoryFormat(category) {
99758         switch (category) {
99759             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
99760             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
99761             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
99762             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
99763         }
99764     }
99765     /** @internal */
99766     function formatColorAndReset(text, formatStyle) {
99767         return formatStyle + text + resetEscapeSequence;
99768     }
99769     ts.formatColorAndReset = formatColorAndReset;
99770     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
99771         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
99772         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
99773         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
99774         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
99775         var gutterWidth = (lastLine + 1 + "").length;
99776         if (hasMoreThanFiveLines) {
99777             gutterWidth = Math.max(ellipsis.length, gutterWidth);
99778         }
99779         var context = "";
99780         for (var i = firstLine; i <= lastLine; i++) {
99781             context += host.getNewLine();
99782             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
99783             // so we'll skip ahead to the second-to-last line.
99784             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
99785                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
99786                 i = lastLine - 1;
99787             }
99788             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
99789             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
99790             var lineContent = file.text.slice(lineStart, lineEnd);
99791             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
99792             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
99793             // Output the gutter and the actual contents of the line.
99794             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
99795             context += lineContent + host.getNewLine();
99796             // Output the gutter and the error span for the line using tildes.
99797             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
99798             context += squiggleColor;
99799             if (i === firstLine) {
99800                 // If we're on the last line, then limit it to the last character of the last line.
99801                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
99802                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
99803                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
99804                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
99805             }
99806             else if (i === lastLine) {
99807                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
99808             }
99809             else {
99810                 // Squiggle the entire line.
99811                 context += lineContent.replace(/./g, "~");
99812             }
99813             context += resetEscapeSequence;
99814         }
99815         return context;
99816     }
99817     /* @internal */
99818     function formatLocation(file, start, host, color) {
99819         if (color === void 0) { color = formatColorAndReset; }
99820         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
99821         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
99822         var output = "";
99823         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
99824         output += ":";
99825         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
99826         output += ":";
99827         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
99828         return output;
99829     }
99830     ts.formatLocation = formatLocation;
99831     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
99832         var output = "";
99833         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
99834             var diagnostic = diagnostics_3[_i];
99835             if (diagnostic.file) {
99836                 var file = diagnostic.file, start = diagnostic.start;
99837                 output += formatLocation(file, start, host); // TODO: GH#18217
99838                 output += " - ";
99839             }
99840             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
99841             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
99842             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
99843             if (diagnostic.file) {
99844                 output += host.getNewLine();
99845                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
99846                 if (diagnostic.relatedInformation) {
99847                     output += host.getNewLine();
99848                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
99849                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
99850                         if (file) {
99851                             output += host.getNewLine();
99852                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
99853                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
99854                         }
99855                         output += host.getNewLine();
99856                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
99857                     }
99858                 }
99859             }
99860             output += host.getNewLine();
99861         }
99862         return output;
99863     }
99864     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
99865     function flattenDiagnosticMessageText(diag, newLine, indent) {
99866         if (indent === void 0) { indent = 0; }
99867         if (ts.isString(diag)) {
99868             return diag;
99869         }
99870         else if (diag === undefined) {
99871             return "";
99872         }
99873         var result = "";
99874         if (indent) {
99875             result += newLine;
99876             for (var i = 0; i < indent; i++) {
99877                 result += "  ";
99878             }
99879         }
99880         result += diag.messageText;
99881         indent++;
99882         if (diag.next) {
99883             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
99884                 var kid = _a[_i];
99885                 result += flattenDiagnosticMessageText(kid, newLine, indent);
99886             }
99887         }
99888         return result;
99889     }
99890     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
99891     /* @internal */
99892     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
99893         if (names.length === 0) {
99894             return [];
99895         }
99896         var resolutions = [];
99897         var cache = ts.createMap();
99898         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
99899             var name = names_2[_i];
99900             var result = void 0;
99901             if (cache.has(name)) {
99902                 result = cache.get(name);
99903             }
99904             else {
99905                 cache.set(name, result = loader(name, containingFile, redirectedReference));
99906             }
99907             resolutions.push(result);
99908         }
99909         return resolutions;
99910     }
99911     ts.loadWithLocalCache = loadWithLocalCache;
99912     /* @internal */
99913     ts.inferredTypesContainingFile = "__inferred type names__.ts";
99914     /**
99915      * Determines if program structure is upto date or needs to be recreated
99916      */
99917     /* @internal */
99918     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
99919         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
99920         if (!program || hasChangedAutomaticTypeDirectiveNames) {
99921             return false;
99922         }
99923         // If root file names don't match
99924         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
99925             return false;
99926         }
99927         var seenResolvedRefs;
99928         // If project references don't match
99929         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
99930             return false;
99931         }
99932         // If any file is not up-to-date, then the whole program is not up-to-date
99933         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
99934             return false;
99935         }
99936         // If any of the missing file paths are now created
99937         if (program.getMissingFilePaths().some(fileExists)) {
99938             return false;
99939         }
99940         var currentOptions = program.getCompilerOptions();
99941         // If the compilation settings do no match, then the program is not up-to-date
99942         if (!ts.compareDataObjects(currentOptions, newOptions)) {
99943             return false;
99944         }
99945         // If everything matches but the text of config file is changed,
99946         // error locations can change for program options, so update the program
99947         if (currentOptions.configFile && newOptions.configFile) {
99948             return currentOptions.configFile.text === newOptions.configFile.text;
99949         }
99950         return true;
99951         function sourceFileNotUptoDate(sourceFile) {
99952             return !sourceFileVersionUptoDate(sourceFile) ||
99953                 hasInvalidatedResolution(sourceFile.path);
99954         }
99955         function sourceFileVersionUptoDate(sourceFile) {
99956             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
99957         }
99958         function projectReferenceUptoDate(oldRef, newRef, index) {
99959             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
99960                 return false;
99961             }
99962             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
99963         }
99964         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
99965             if (oldResolvedRef) {
99966                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
99967                     // Assume true
99968                     return true;
99969                 }
99970                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
99971                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
99972                     return false;
99973                 }
99974                 // Add to seen before checking the referenced paths of this config file
99975                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
99976                 // If child project references are upto date, this project reference is uptodate
99977                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
99978                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
99979                 });
99980             }
99981             // In old program, not able to resolve project reference path,
99982             // so if config file doesnt exist, it is uptodate.
99983             return !fileExists(resolveProjectReferencePath(oldRef));
99984         }
99985     }
99986     ts.isProgramUptoDate = isProgramUptoDate;
99987     function getConfigFileParsingDiagnostics(configFileParseResult) {
99988         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
99989             configFileParseResult.errors;
99990     }
99991     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
99992     /**
99993      * Determine if source file needs to be re-created even if its text hasn't changed
99994      */
99995     function shouldProgramCreateNewSourceFiles(program, newOptions) {
99996         if (!program)
99997             return false;
99998         // If any compiler options change, we can't reuse old source file even if version match
99999         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
100000         var oldOptions = program.getCompilerOptions();
100001         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
100002             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
100003         });
100004     }
100005     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
100006         return {
100007             rootNames: rootNames,
100008             options: options,
100009             host: host,
100010             oldProgram: oldProgram,
100011             configFileParsingDiagnostics: configFileParsingDiagnostics
100012         };
100013     }
100014     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
100015         var _a;
100016         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
100017         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
100018         var oldProgram = createProgramOptions.oldProgram;
100019         var processingDefaultLibFiles;
100020         var processingOtherFiles;
100021         var files;
100022         var symlinks;
100023         var commonSourceDirectory;
100024         var diagnosticsProducingTypeChecker;
100025         var noDiagnosticsTypeChecker;
100026         var classifiableNames;
100027         var ambientModuleNameToUnmodifiedFileName = ts.createMap();
100028         // Todo:: Use this to report why file was included in --extendedDiagnostics
100029         var refFileMap;
100030         var cachedBindAndCheckDiagnosticsForFile = {};
100031         var cachedDeclarationDiagnosticsForFile = {};
100032         var resolvedTypeReferenceDirectives = ts.createMap();
100033         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
100034         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
100035         // This works as imported modules are discovered recursively in a depth first manner, specifically:
100036         // - For each root file, findSourceFile is called.
100037         // - This calls processImportedModules for each module imported in the source file.
100038         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
100039         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
100040         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
100041         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
100042         var currentNodeModulesDepth = 0;
100043         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
100044         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
100045         var modulesWithElidedImports = ts.createMap();
100046         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
100047         var sourceFilesFoundSearchingNodeModules = ts.createMap();
100048         ts.performance.mark("beforeProgram");
100049         var host = createProgramOptions.host || createCompilerHost(options);
100050         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
100051         var skipDefaultLib = options.noLib;
100052         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
100053         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
100054         var programDiagnostics = ts.createDiagnosticCollection();
100055         var currentDirectory = host.getCurrentDirectory();
100056         var supportedExtensions = ts.getSupportedExtensions(options);
100057         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
100058         // Map storing if there is emit blocking diagnostics for given input
100059         var hasEmitBlockingDiagnostics = ts.createMap();
100060         var _compilerOptionsObjectLiteralSyntax;
100061         var moduleResolutionCache;
100062         var actualResolveModuleNamesWorker;
100063         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
100064         if (host.resolveModuleNames) {
100065             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
100066                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
100067                 if (!resolved || resolved.extension !== undefined) {
100068                     return resolved;
100069                 }
100070                 var withExtension = ts.clone(resolved);
100071                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
100072                 return withExtension;
100073             }); };
100074         }
100075         else {
100076             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
100077             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
100078             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
100079         }
100080         var actualResolveTypeReferenceDirectiveNamesWorker;
100081         if (host.resolveTypeReferenceDirectives) {
100082             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
100083         }
100084         else {
100085             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
100086             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
100087         }
100088         // Map from a stringified PackageId to the source file with that id.
100089         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
100090         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
100091         var packageIdToSourceFile = ts.createMap();
100092         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
100093         var sourceFileToPackageName = ts.createMap();
100094         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
100095         var redirectTargetsMap = ts.createMultiMap();
100096         /**
100097          * map with
100098          * - SourceFile if present
100099          * - false if sourceFile missing for source of project reference redirect
100100          * - undefined otherwise
100101          */
100102         var filesByName = ts.createMap();
100103         var missingFilePaths;
100104         // stores 'filename -> file association' ignoring case
100105         // used to track cases when two file names differ only in casing
100106         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
100107         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
100108         var resolvedProjectReferences;
100109         var projectReferenceRedirects;
100110         var mapFromFileToProjectReferenceRedirects;
100111         var mapFromToProjectReferenceRedirectSource;
100112         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
100113             !options.disableSourceOfProjectReferenceRedirect;
100114         var _b = updateHostForUseSourceOfProjectReferenceRedirect({
100115             compilerHost: host,
100116             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
100117             toPath: toPath,
100118             getResolvedProjectReferences: getResolvedProjectReferences,
100119             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
100120             forEachResolvedProjectReference: forEachResolvedProjectReference
100121         }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists;
100122         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
100123         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
100124         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
100125         var structuralIsReused;
100126         structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
100127         if (structuralIsReused !== 2 /* Completely */) {
100128             processingDefaultLibFiles = [];
100129             processingOtherFiles = [];
100130             if (projectReferences) {
100131                 if (!resolvedProjectReferences) {
100132                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100133                 }
100134                 if (rootNames.length) {
100135                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
100136                         var parsedRef = resolvedProjectReferences_1[_i];
100137                         if (!parsedRef)
100138                             continue;
100139                         var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
100140                         if (useSourceOfProjectReferenceRedirect) {
100141                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
100142                                 for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
100143                                     var fileName = _d[_c];
100144                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100145                                 }
100146                             }
100147                         }
100148                         else {
100149                             if (out) {
100150                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100151                             }
100152                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
100153                                 for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) {
100154                                     var fileName = _f[_e];
100155                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
100156                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100157                                     }
100158                                 }
100159                             }
100160                         }
100161                     }
100162                 }
100163             }
100164             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
100165             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
100166             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
100167             if (typeReferences.length) {
100168                 // This containingFilename needs to match with the one used in managed-side
100169                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
100170                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
100171                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
100172                 for (var i = 0; i < typeReferences.length; i++) {
100173                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
100174                 }
100175             }
100176             // Do not process the default library if:
100177             //  - The '--noLib' flag is used.
100178             //  - A 'no-default-lib' reference comment is encountered in
100179             //      processing the root files.
100180             if (rootNames.length && !skipDefaultLib) {
100181                 // If '--lib' is not specified, include default library file according to '--target'
100182                 // otherwise, using options specified in '--lib' instead of '--target' default library file
100183                 var defaultLibraryFileName = getDefaultLibraryFileName();
100184                 if (!options.lib && defaultLibraryFileName) {
100185                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100186                 }
100187                 else {
100188                     ts.forEach(options.lib, function (libFileName) {
100189                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100190                     });
100191                 }
100192             }
100193             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
100194                 var path = _a[0], file = _a[1];
100195                 return file === undefined ? path : undefined;
100196             }));
100197             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
100198             processingDefaultLibFiles = undefined;
100199             processingOtherFiles = undefined;
100200         }
100201         ts.Debug.assert(!!missingFilePaths);
100202         // Release any files we have acquired in the old program but are
100203         // not part of the new program.
100204         if (oldProgram && host.onReleaseOldSourceFile) {
100205             var oldSourceFiles = oldProgram.getSourceFiles();
100206             for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) {
100207                 var oldSourceFile = oldSourceFiles_1[_g];
100208                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
100209                 if (shouldCreateNewSourceFile || !newFile ||
100210                     // old file wasnt redirect but new file is
100211                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
100212                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
100213                 }
100214             }
100215             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
100216                 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
100217                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
100218                 }
100219             });
100220         }
100221         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
100222         oldProgram = undefined;
100223         var program = {
100224             getRootFileNames: function () { return rootNames; },
100225             getSourceFile: getSourceFile,
100226             getSourceFileByPath: getSourceFileByPath,
100227             getSourceFiles: function () { return files; },
100228             getMissingFilePaths: function () { return missingFilePaths; },
100229             getRefFileMap: function () { return refFileMap; },
100230             getFilesByNameMap: function () { return filesByName; },
100231             getCompilerOptions: function () { return options; },
100232             getSyntacticDiagnostics: getSyntacticDiagnostics,
100233             getOptionsDiagnostics: getOptionsDiagnostics,
100234             getGlobalDiagnostics: getGlobalDiagnostics,
100235             getSemanticDiagnostics: getSemanticDiagnostics,
100236             getSuggestionDiagnostics: getSuggestionDiagnostics,
100237             getDeclarationDiagnostics: getDeclarationDiagnostics,
100238             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
100239             getProgramDiagnostics: getProgramDiagnostics,
100240             getTypeChecker: getTypeChecker,
100241             getClassifiableNames: getClassifiableNames,
100242             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
100243             getCommonSourceDirectory: getCommonSourceDirectory,
100244             emit: emit,
100245             getCurrentDirectory: function () { return currentDirectory; },
100246             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
100247             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
100248             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
100249             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
100250             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
100251             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
100252             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
100253             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
100254             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100255             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
100256             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
100257             getSourceFileFromReference: getSourceFileFromReference,
100258             getLibFileFromReference: getLibFileFromReference,
100259             sourceFileToPackageName: sourceFileToPackageName,
100260             redirectTargetsMap: redirectTargetsMap,
100261             isEmittedFile: isEmittedFile,
100262             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
100263             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
100264             getProjectReferences: getProjectReferences,
100265             getResolvedProjectReferences: getResolvedProjectReferences,
100266             getProjectReferenceRedirect: getProjectReferenceRedirect,
100267             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100268             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
100269             forEachResolvedProjectReference: forEachResolvedProjectReference,
100270             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100271             emitBuildInfo: emitBuildInfo,
100272             fileExists: fileExists,
100273             getProbableSymlinks: getProbableSymlinks,
100274             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100275         };
100276         onProgramCreateComplete();
100277         verifyCompilerOptions();
100278         ts.performance.mark("afterProgram");
100279         ts.performance.measure("Program", "beforeProgram", "afterProgram");
100280         return program;
100281         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
100282             ts.performance.mark("beforeResolveModule");
100283             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
100284             ts.performance.mark("afterResolveModule");
100285             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
100286             return result;
100287         }
100288         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
100289             ts.performance.mark("beforeResolveTypeReference");
100290             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
100291             ts.performance.mark("afterResolveTypeReference");
100292             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
100293             return result;
100294         }
100295         function compareDefaultLibFiles(a, b) {
100296             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
100297         }
100298         function getDefaultLibFilePriority(a) {
100299             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
100300                 var basename = ts.getBaseFileName(a.fileName);
100301                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
100302                     return 0;
100303                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
100304                 var index = ts.libs.indexOf(name);
100305                 if (index !== -1)
100306                     return index + 1;
100307             }
100308             return ts.libs.length + 2;
100309         }
100310         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
100311             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
100312         }
100313         function toPath(fileName) {
100314             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
100315         }
100316         function getCommonSourceDirectory() {
100317             if (commonSourceDirectory === undefined) {
100318                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
100319                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
100320                     // If a rootDir is specified use it as the commonSourceDirectory
100321                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100322                 }
100323                 else if (options.composite && options.configFilePath) {
100324                     // Project compilations never infer their root from the input source paths
100325                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100326                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
100327                 }
100328                 else {
100329                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
100330                 }
100331                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100332                     // Make sure directory path ends with directory separator so this string can directly
100333                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
100334                     // start with / making it rooted path
100335                     commonSourceDirectory += ts.directorySeparator;
100336                 }
100337             }
100338             return commonSourceDirectory;
100339         }
100340         function getClassifiableNames() {
100341             if (!classifiableNames) {
100342                 // Initialize a checker so that all our files are bound.
100343                 getTypeChecker();
100344                 classifiableNames = ts.createUnderscoreEscapedMap();
100345                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
100346                     var sourceFile = files_2[_i];
100347                     ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
100348                 }
100349             }
100350             return classifiableNames;
100351         }
100352         function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
100353             if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
100354                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
100355                 // the best we can do is fallback to the default logic.
100356                 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
100357             }
100358             var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
100359             if (oldSourceFile !== file && file.resolvedModules) {
100360                 // `file` was created for the new program.
100361                 //
100362                 // We only set `file.resolvedModules` via work from the current function,
100363                 // so it is defined iff we already called the current function on `file`.
100364                 // That call happened no later than the creation of the `file` object,
100365                 // which per above occurred during the current program creation.
100366                 // Since we assume the filesystem does not change during program creation,
100367                 // it is safe to reuse resolutions from the earlier call.
100368                 var result_11 = [];
100369                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
100370                     var moduleName = moduleNames_1[_i];
100371                     var resolvedModule = file.resolvedModules.get(moduleName);
100372                     result_11.push(resolvedModule);
100373                 }
100374                 return result_11;
100375             }
100376             // At this point, we know at least one of the following hold:
100377             // - file has local declarations for ambient modules
100378             // - old program state is available
100379             // With this information, we can infer some module resolutions without performing resolution.
100380             /** An ordered list of module names for which we cannot recover the resolution. */
100381             var unknownModuleNames;
100382             /**
100383              * The indexing of elements in this list matches that of `moduleNames`.
100384              *
100385              * Before combining results, result[i] is in one of the following states:
100386              * * undefined: needs to be recomputed,
100387              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
100388              * Needs to be reset to undefined before returning,
100389              * * ResolvedModuleFull instance: can be reused.
100390              */
100391             var result;
100392             var reusedNames;
100393             /** A transient placeholder used to mark predicted resolution in the result list. */
100394             var predictedToResolveToAmbientModuleMarker = {};
100395             for (var i = 0; i < moduleNames.length; i++) {
100396                 var moduleName = moduleNames[i];
100397                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
100398                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
100399                     var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
100400                     if (oldResolvedModule) {
100401                         if (ts.isTraceEnabled(options, host)) {
100402                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
100403                         }
100404                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
100405                         (reusedNames || (reusedNames = [])).push(moduleName);
100406                         continue;
100407                     }
100408                 }
100409                 // We know moduleName resolves to an ambient module provided that moduleName:
100410                 // - is in the list of ambient modules locally declared in the current source file.
100411                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
100412                 //   (so the same module declaration will land in the new program)
100413                 var resolvesToAmbientModuleInNonModifiedFile = false;
100414                 if (ts.contains(file.ambientModuleNames, moduleName)) {
100415                     resolvesToAmbientModuleInNonModifiedFile = true;
100416                     if (ts.isTraceEnabled(options, host)) {
100417                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
100418                     }
100419                 }
100420                 else {
100421                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
100422                 }
100423                 if (resolvesToAmbientModuleInNonModifiedFile) {
100424                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
100425                 }
100426                 else {
100427                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
100428                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
100429                 }
100430             }
100431             var resolutions = unknownModuleNames && unknownModuleNames.length
100432                 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
100433                 : ts.emptyArray;
100434             // Combine results of resolutions and predicted results
100435             if (!result) {
100436                 // There were no unresolved/ambient resolutions.
100437                 ts.Debug.assert(resolutions.length === moduleNames.length);
100438                 return resolutions;
100439             }
100440             var j = 0;
100441             for (var i = 0; i < result.length; i++) {
100442                 if (result[i]) {
100443                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
100444                     // If it is the former, we can leave it as is.
100445                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
100446                         result[i] = undefined; // TODO: GH#18217
100447                     }
100448                 }
100449                 else {
100450                     result[i] = resolutions[j];
100451                     j++;
100452                 }
100453             }
100454             ts.Debug.assert(j === resolutions.length);
100455             return result;
100456             // If we change our policy of rechecking failed lookups on each program create,
100457             // we should adjust the value returned here.
100458             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
100459                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
100460                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
100461                 if (resolutionToFile && resolvedFile) {
100462                     // In the old program, we resolved to an ambient module that was in the same
100463                     //   place as we expected to find an actual module file.
100464                     // We actually need to return 'false' here even though this seems like a 'true' case
100465                     //   because the normal module resolution algorithm will find this anyway.
100466                     return false;
100467                 }
100468                 // at least one of declarations should come from non-modified source file
100469                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
100470                 if (!unmodifiedFile) {
100471                     return false;
100472                 }
100473                 if (ts.isTraceEnabled(options, host)) {
100474                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
100475                 }
100476                 return true;
100477             }
100478         }
100479         function canReuseProjectReferences() {
100480             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
100481                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
100482                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
100483                 if (oldResolvedRef) {
100484                     // Resolved project reference has gone missing or changed
100485                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
100486                 }
100487                 else {
100488                     // A previously-unresolved reference may be resolved now
100489                     return newResolvedRef !== undefined;
100490                 }
100491             }, function (oldProjectReferences, parent) {
100492                 // If array of references is changed, we cant resue old program
100493                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
100494                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
100495             });
100496         }
100497         function tryReuseStructureFromOldProgram() {
100498             if (!oldProgram) {
100499                 return 0 /* Not */;
100500             }
100501             // check properties that can affect structure of the program or module resolution strategy
100502             // if any of these properties has changed - structure cannot be reused
100503             var oldOptions = oldProgram.getCompilerOptions();
100504             if (ts.changesAffectModuleResolution(oldOptions, options)) {
100505                 return oldProgram.structureIsReused = 0 /* Not */;
100506             }
100507             ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
100508             // there is an old program, check if we can reuse its structure
100509             var oldRootNames = oldProgram.getRootFileNames();
100510             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
100511                 return oldProgram.structureIsReused = 0 /* Not */;
100512             }
100513             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
100514                 return oldProgram.structureIsReused = 0 /* Not */;
100515             }
100516             // Check if any referenced project tsconfig files are different
100517             if (!canReuseProjectReferences()) {
100518                 return oldProgram.structureIsReused = 0 /* Not */;
100519             }
100520             if (projectReferences) {
100521                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100522             }
100523             // check if program source files has changed in the way that can affect structure of the program
100524             var newSourceFiles = [];
100525             var modifiedSourceFiles = [];
100526             oldProgram.structureIsReused = 2 /* Completely */;
100527             // If the missing file paths are now present, it can change the progam structure,
100528             // and hence cant reuse the structure.
100529             // This is same as how we dont reuse the structure if one of the file from old program is now missing
100530             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
100531                 return oldProgram.structureIsReused = 0 /* Not */;
100532             }
100533             var oldSourceFiles = oldProgram.getSourceFiles();
100534             var SeenPackageName;
100535             (function (SeenPackageName) {
100536                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
100537                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
100538             })(SeenPackageName || (SeenPackageName = {}));
100539             var seenPackageNames = ts.createMap();
100540             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
100541                 var oldSourceFile = oldSourceFiles_2[_i];
100542                 var newSourceFile = host.getSourceFileByPath
100543                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
100544                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
100545                 if (!newSourceFile) {
100546                     return oldProgram.structureIsReused = 0 /* Not */;
100547                 }
100548                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
100549                 var fileChanged = void 0;
100550                 if (oldSourceFile.redirectInfo) {
100551                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
100552                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
100553                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
100554                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
100555                         return oldProgram.structureIsReused = 0 /* Not */;
100556                     }
100557                     fileChanged = false;
100558                     newSourceFile = oldSourceFile; // Use the redirect.
100559                 }
100560                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
100561                     // If a redirected-to source file changes, the redirect may be broken.
100562                     if (newSourceFile !== oldSourceFile) {
100563                         return oldProgram.structureIsReused = 0 /* Not */;
100564                     }
100565                     fileChanged = false;
100566                 }
100567                 else {
100568                     fileChanged = newSourceFile !== oldSourceFile;
100569                 }
100570                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
100571                 newSourceFile.path = oldSourceFile.path;
100572                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
100573                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
100574                 newSourceFile.fileName = oldSourceFile.fileName;
100575                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
100576                 if (packageName !== undefined) {
100577                     // If there are 2 different source files for the same package name and at least one of them changes,
100578                     // they might become redirects. So we must rebuild the program.
100579                     var prevKind = seenPackageNames.get(packageName);
100580                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
100581                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
100582                         return oldProgram.structureIsReused = 0 /* Not */;
100583                     }
100584                     seenPackageNames.set(packageName, newKind);
100585                 }
100586                 if (fileChanged) {
100587                     // The `newSourceFile` object was created for the new program.
100588                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
100589                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
100590                         return oldProgram.structureIsReused = 0 /* Not */;
100591                     }
100592                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
100593                         // value of no-default-lib has changed
100594                         // this will affect if default library is injected into the list of files
100595                         oldProgram.structureIsReused = 1 /* SafeModules */;
100596                     }
100597                     // check tripleslash references
100598                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
100599                         // tripleslash references has changed
100600                         oldProgram.structureIsReused = 1 /* SafeModules */;
100601                     }
100602                     // check imports and module augmentations
100603                     collectExternalModuleReferences(newSourceFile);
100604                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
100605                         // imports has changed
100606                         oldProgram.structureIsReused = 1 /* SafeModules */;
100607                     }
100608                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
100609                         // moduleAugmentations has changed
100610                         oldProgram.structureIsReused = 1 /* SafeModules */;
100611                     }
100612                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
100613                         // dynamicImport has changed
100614                         oldProgram.structureIsReused = 1 /* SafeModules */;
100615                     }
100616                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
100617                         // 'types' references has changed
100618                         oldProgram.structureIsReused = 1 /* SafeModules */;
100619                     }
100620                     // tentatively approve the file
100621                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100622                 }
100623                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
100624                     // 'module/types' references could have changed
100625                     oldProgram.structureIsReused = 1 /* SafeModules */;
100626                     // add file to the modified list so that we will resolve it later
100627                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100628                 }
100629                 // if file has passed all checks it should be safe to reuse it
100630                 newSourceFiles.push(newSourceFile);
100631             }
100632             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100633                 return oldProgram.structureIsReused;
100634             }
100635             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
100636             for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
100637                 var oldFile = oldSourceFiles_3[_a];
100638                 if (!ts.contains(modifiedFiles, oldFile)) {
100639                     for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
100640                         var moduleName = _c[_b];
100641                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
100642                     }
100643                 }
100644             }
100645             // try to verify results of module resolution
100646             for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
100647                 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
100648                 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
100649                 var moduleNames = getModuleNames(newSourceFile);
100650                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
100651                 // ensure that module resolution results are still correct
100652                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
100653                 if (resolutionsChanged) {
100654                     oldProgram.structureIsReused = 1 /* SafeModules */;
100655                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
100656                 }
100657                 else {
100658                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
100659                 }
100660                 if (resolveTypeReferenceDirectiveNamesWorker) {
100661                     // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
100662                     var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
100663                     var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
100664                     // ensure that types resolutions are still correct
100665                     var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
100666                     if (resolutionsChanged_1) {
100667                         oldProgram.structureIsReused = 1 /* SafeModules */;
100668                         newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
100669                     }
100670                     else {
100671                         newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
100672                     }
100673                 }
100674             }
100675             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100676                 return oldProgram.structureIsReused;
100677             }
100678             if (host.hasChangedAutomaticTypeDirectiveNames) {
100679                 return oldProgram.structureIsReused = 1 /* SafeModules */;
100680             }
100681             missingFilePaths = oldProgram.getMissingFilePaths();
100682             refFileMap = oldProgram.getRefFileMap();
100683             // update fileName -> file mapping
100684             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
100685             for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
100686                 var newSourceFile = newSourceFiles_1[_f];
100687                 filesByName.set(newSourceFile.path, newSourceFile);
100688             }
100689             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
100690             oldFilesByNameMap.forEach(function (oldFile, path) {
100691                 if (!oldFile) {
100692                     filesByName.set(path, oldFile);
100693                     return;
100694                 }
100695                 if (oldFile.path === path) {
100696                     // Set the file as found during node modules search if it was found that way in old progra,
100697                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
100698                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
100699                     }
100700                     return;
100701                 }
100702                 filesByName.set(path, filesByName.get(oldFile.path));
100703             });
100704             files = newSourceFiles;
100705             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
100706             for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
100707                 var modifiedFile = modifiedSourceFiles_2[_g];
100708                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
100709             }
100710             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
100711             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
100712             redirectTargetsMap = oldProgram.redirectTargetsMap;
100713             return oldProgram.structureIsReused = 2 /* Completely */;
100714         }
100715         function getEmitHost(writeFileCallback) {
100716             return {
100717                 getPrependNodes: getPrependNodes,
100718                 getCanonicalFileName: getCanonicalFileName,
100719                 getCommonSourceDirectory: program.getCommonSourceDirectory,
100720                 getCompilerOptions: program.getCompilerOptions,
100721                 getCurrentDirectory: function () { return currentDirectory; },
100722                 getNewLine: function () { return host.getNewLine(); },
100723                 getSourceFile: program.getSourceFile,
100724                 getSourceFileByPath: program.getSourceFileByPath,
100725                 getSourceFiles: program.getSourceFiles,
100726                 getLibFileFromReference: program.getLibFileFromReference,
100727                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100728                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100729                 getProjectReferenceRedirect: getProjectReferenceRedirect,
100730                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100731                 getProbableSymlinks: getProbableSymlinks,
100732                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
100733                 isEmitBlocked: isEmitBlocked,
100734                 readFile: function (f) { return host.readFile(f); },
100735                 fileExists: function (f) {
100736                     // Use local caches
100737                     var path = toPath(f);
100738                     if (getSourceFileByPath(path))
100739                         return true;
100740                     if (ts.contains(missingFilePaths, path))
100741                         return false;
100742                     // Before falling back to the host
100743                     return host.fileExists(f);
100744                 },
100745                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100746                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
100747                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
100748                 redirectTargetsMap: redirectTargetsMap,
100749             };
100750         }
100751         function emitBuildInfo(writeFileCallback) {
100752             ts.Debug.assert(!options.out && !options.outFile);
100753             ts.performance.mark("beforeEmit");
100754             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
100755             /*targetSourceFile*/ undefined, 
100756             /*transformers*/ ts.noTransformers, 
100757             /*emitOnlyDtsFiles*/ false, 
100758             /*onlyBuildInfo*/ true);
100759             ts.performance.mark("afterEmit");
100760             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100761             return emitResult;
100762         }
100763         function getResolvedProjectReferences() {
100764             return resolvedProjectReferences;
100765         }
100766         function getProjectReferences() {
100767             return projectReferences;
100768         }
100769         function getPrependNodes() {
100770             return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
100771                 var path = toPath(fileName);
100772                 var sourceFile = getSourceFileByPath(path);
100773                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
100774             });
100775         }
100776         function isSourceFileFromExternalLibrary(file) {
100777             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
100778         }
100779         function isSourceFileDefaultLibrary(file) {
100780             if (file.hasNoDefaultLib) {
100781                 return true;
100782             }
100783             if (!options.noLib) {
100784                 return false;
100785             }
100786             // If '--lib' is not specified, include default library file according to '--target'
100787             // otherwise, using options specified in '--lib' instead of '--target' default library file
100788             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
100789             if (!options.lib) {
100790                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
100791             }
100792             else {
100793                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
100794             }
100795         }
100796         function getDiagnosticsProducingTypeChecker() {
100797             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
100798         }
100799         function dropDiagnosticsProducingTypeChecker() {
100800             diagnosticsProducingTypeChecker = undefined;
100801         }
100802         function getTypeChecker() {
100803             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
100804         }
100805         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
100806             return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
100807         }
100808         function isEmitBlocked(emitFileName) {
100809             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
100810         }
100811         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
100812             if (!forceDtsEmit) {
100813                 var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
100814                 if (result)
100815                     return result;
100816             }
100817             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
100818             // any cost associated with it (like type checking) are appropriate associated with
100819             // the type-checking counter.
100820             //
100821             // If the -out option is specified, we should not pass the source file to getEmitResolver.
100822             // This is because in the -out scenario all files need to be emitted, and therefore all
100823             // files need to be type checked. And the way to specify that all files need to be type
100824             // checked is to not pass the file to getEmitResolver.
100825             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
100826             ts.performance.mark("beforeEmit");
100827             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
100828             /*onlyBuildInfo*/ false, forceDtsEmit);
100829             ts.performance.mark("afterEmit");
100830             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100831             return emitResult;
100832         }
100833         function getSourceFile(fileName) {
100834             return getSourceFileByPath(toPath(fileName));
100835         }
100836         function getSourceFileByPath(path) {
100837             return filesByName.get(path) || undefined;
100838         }
100839         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
100840             if (sourceFile) {
100841                 return getDiagnostics(sourceFile, cancellationToken);
100842             }
100843             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
100844                 if (cancellationToken) {
100845                     cancellationToken.throwIfCancellationRequested();
100846                 }
100847                 return getDiagnostics(sourceFile, cancellationToken);
100848             }));
100849         }
100850         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
100851             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
100852         }
100853         function getSemanticDiagnostics(sourceFile, cancellationToken) {
100854             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
100855         }
100856         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
100857             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
100858         }
100859         function getProgramDiagnostics(sourceFile) {
100860             if (ts.skipTypeChecking(sourceFile, options, program)) {
100861                 return ts.emptyArray;
100862             }
100863             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
100864             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
100865             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
100866         }
100867         function getMergedProgramDiagnostics(sourceFile) {
100868             var _a;
100869             var allDiagnostics = [];
100870             for (var _i = 1; _i < arguments.length; _i++) {
100871                 allDiagnostics[_i - 1] = arguments[_i];
100872             }
100873             var flatDiagnostics = ts.flatten(allDiagnostics);
100874             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100875                 return flatDiagnostics;
100876             }
100877             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
100878         }
100879         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
100880             var options = program.getCompilerOptions();
100881             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
100882             if (!sourceFile || options.out || options.outFile) {
100883                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
100884             }
100885             else {
100886                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
100887             }
100888         }
100889         function getSyntacticDiagnosticsForFile(sourceFile) {
100890             // For JavaScript files, we report semantic errors for using TypeScript-only
100891             // constructs from within a JavaScript file as syntactic errors.
100892             if (ts.isSourceFileJS(sourceFile)) {
100893                 if (!sourceFile.additionalSyntacticDiagnostics) {
100894                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
100895                 }
100896                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
100897             }
100898             return sourceFile.parseDiagnostics;
100899         }
100900         function runWithCancellationToken(func) {
100901             try {
100902                 return func();
100903             }
100904             catch (e) {
100905                 if (e instanceof ts.OperationCanceledException) {
100906                     // We were canceled while performing the operation.  Because our type checker
100907                     // might be a bad state, we need to throw it away.
100908                     //
100909                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
100910                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
100911                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
100912                     // cancel when the user has made a change anyways.  And, in that case, we (the
100913                     // program instance) will get thrown away anyways.  So trying to keep one of
100914                     // these type checkers alive doesn't serve much purpose.
100915                     noDiagnosticsTypeChecker = undefined;
100916                     diagnosticsProducingTypeChecker = undefined;
100917                 }
100918                 throw e;
100919             }
100920         }
100921         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
100922             return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
100923         }
100924         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
100925             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
100926         }
100927         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
100928             return runWithCancellationToken(function () {
100929                 if (ts.skipTypeChecking(sourceFile, options, program)) {
100930                     return ts.emptyArray;
100931                 }
100932                 var typeChecker = getDiagnosticsProducingTypeChecker();
100933                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
100934                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
100935                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
100936                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
100937                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
100938                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
100939                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
100940                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
100941                 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
100942             });
100943         }
100944         function getMergedBindAndCheckDiagnostics(sourceFile) {
100945             var _a;
100946             var allDiagnostics = [];
100947             for (var _i = 1; _i < arguments.length; _i++) {
100948                 allDiagnostics[_i - 1] = arguments[_i];
100949             }
100950             var flatDiagnostics = ts.flatten(allDiagnostics);
100951             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100952                 return flatDiagnostics;
100953             }
100954             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
100955             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
100956                 var errorExpectation = _d[_c];
100957                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
100958             }
100959             return diagnostics;
100960         }
100961         /**
100962          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
100963          * Comments that match to any of those diagnostics are marked as used.
100964          */
100965         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
100966             // Diagnostics are only reported if there is no comment directive preceding them
100967             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
100968             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
100969             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
100970             return { diagnostics: diagnostics, directives: directives };
100971         }
100972         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
100973             return runWithCancellationToken(function () {
100974                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
100975             });
100976         }
100977         /**
100978          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
100979          */
100980         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
100981             var file = diagnostic.file, start = diagnostic.start;
100982             if (!file) {
100983                 return -1;
100984             }
100985             // Start out with the line just before the text
100986             var lineStarts = ts.getLineStarts(file);
100987             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
100988             while (line >= 0) {
100989                 // As soon as that line is known to have a comment directive, use that
100990                 if (directives.markUsed(line)) {
100991                     return line;
100992                 }
100993                 // Stop searching if the line is not empty and not a comment
100994                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
100995                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
100996                     return -1;
100997                 }
100998                 line--;
100999             }
101000             return -1;
101001         }
101002         function getJSSyntacticDiagnosticsForFile(sourceFile) {
101003             return runWithCancellationToken(function () {
101004                 var diagnostics = [];
101005                 walk(sourceFile, sourceFile);
101006                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
101007                 return diagnostics;
101008                 function walk(node, parent) {
101009                     // Return directly from the case if the given node doesnt want to visit each child
101010                     // Otherwise break to visit each child
101011                     switch (parent.kind) {
101012                         case 156 /* Parameter */:
101013                         case 159 /* PropertyDeclaration */:
101014                         case 161 /* MethodDeclaration */:
101015                             if (parent.questionToken === node) {
101016                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
101017                                 return "skip";
101018                             }
101019                         // falls through
101020                         case 160 /* MethodSignature */:
101021                         case 162 /* Constructor */:
101022                         case 163 /* GetAccessor */:
101023                         case 164 /* SetAccessor */:
101024                         case 201 /* FunctionExpression */:
101025                         case 244 /* FunctionDeclaration */:
101026                         case 202 /* ArrowFunction */:
101027                         case 242 /* VariableDeclaration */:
101028                             // type annotation
101029                             if (parent.type === node) {
101030                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
101031                                 return "skip";
101032                             }
101033                     }
101034                     switch (node.kind) {
101035                         case 255 /* ImportClause */:
101036                             if (node.isTypeOnly) {
101037                                 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
101038                                 return "skip";
101039                             }
101040                             break;
101041                         case 260 /* ExportDeclaration */:
101042                             if (node.isTypeOnly) {
101043                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
101044                                 return "skip";
101045                             }
101046                             break;
101047                         case 253 /* ImportEqualsDeclaration */:
101048                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
101049                             return "skip";
101050                         case 259 /* ExportAssignment */:
101051                             if (node.isExportEquals) {
101052                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
101053                                 return "skip";
101054                             }
101055                             break;
101056                         case 279 /* HeritageClause */:
101057                             var heritageClause = node;
101058                             if (heritageClause.token === 113 /* ImplementsKeyword */) {
101059                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
101060                                 return "skip";
101061                             }
101062                             break;
101063                         case 246 /* InterfaceDeclaration */:
101064                             var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
101065                             ts.Debug.assertIsDefined(interfaceKeyword);
101066                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
101067                             return "skip";
101068                         case 249 /* ModuleDeclaration */:
101069                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
101070                             ts.Debug.assertIsDefined(moduleKeyword);
101071                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
101072                             return "skip";
101073                         case 247 /* TypeAliasDeclaration */:
101074                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
101075                             return "skip";
101076                         case 248 /* EnumDeclaration */:
101077                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */));
101078                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
101079                             return "skip";
101080                         case 218 /* NonNullExpression */:
101081                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
101082                             return "skip";
101083                         case 217 /* AsExpression */:
101084                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
101085                             return "skip";
101086                         case 199 /* TypeAssertionExpression */:
101087                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
101088                     }
101089                 }
101090                 function walkArray(nodes, parent) {
101091                     if (parent.decorators === nodes && !options.experimentalDecorators) {
101092                         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));
101093                     }
101094                     switch (parent.kind) {
101095                         case 245 /* ClassDeclaration */:
101096                         case 214 /* ClassExpression */:
101097                         case 161 /* MethodDeclaration */:
101098                         case 162 /* Constructor */:
101099                         case 163 /* GetAccessor */:
101100                         case 164 /* SetAccessor */:
101101                         case 201 /* FunctionExpression */:
101102                         case 244 /* FunctionDeclaration */:
101103                         case 202 /* ArrowFunction */:
101104                             // Check type parameters
101105                             if (nodes === parent.typeParameters) {
101106                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
101107                                 return "skip";
101108                             }
101109                         // falls through
101110                         case 225 /* VariableStatement */:
101111                             // Check modifiers
101112                             if (nodes === parent.modifiers) {
101113                                 checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
101114                                 return "skip";
101115                             }
101116                             break;
101117                         case 159 /* PropertyDeclaration */:
101118                             // Check modifiers of property declaration
101119                             if (nodes === parent.modifiers) {
101120                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
101121                                     var modifier = _a[_i];
101122                                     if (modifier.kind !== 120 /* StaticKeyword */) {
101123                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
101124                                     }
101125                                 }
101126                                 return "skip";
101127                             }
101128                             break;
101129                         case 156 /* Parameter */:
101130                             // Check modifiers of parameter declaration
101131                             if (nodes === parent.modifiers) {
101132                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
101133                                 return "skip";
101134                             }
101135                             break;
101136                         case 196 /* CallExpression */:
101137                         case 197 /* NewExpression */:
101138                         case 216 /* ExpressionWithTypeArguments */:
101139                         case 267 /* JsxSelfClosingElement */:
101140                         case 268 /* JsxOpeningElement */:
101141                         case 198 /* TaggedTemplateExpression */:
101142                             // Check type arguments
101143                             if (nodes === parent.typeArguments) {
101144                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
101145                                 return "skip";
101146                             }
101147                             break;
101148                     }
101149                 }
101150                 function checkModifiers(modifiers, isConstValid) {
101151                     for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
101152                         var modifier = modifiers_1[_i];
101153                         switch (modifier.kind) {
101154                             case 81 /* ConstKeyword */:
101155                                 if (isConstValid) {
101156                                     continue;
101157                                 }
101158                             // to report error,
101159                             // falls through
101160                             case 119 /* PublicKeyword */:
101161                             case 117 /* PrivateKeyword */:
101162                             case 118 /* ProtectedKeyword */:
101163                             case 138 /* ReadonlyKeyword */:
101164                             case 130 /* DeclareKeyword */:
101165                             case 122 /* AbstractKeyword */:
101166                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
101167                                 break;
101168                             // These are all legal modifiers.
101169                             case 120 /* StaticKeyword */:
101170                             case 89 /* ExportKeyword */:
101171                             case 84 /* DefaultKeyword */:
101172                         }
101173                     }
101174                 }
101175                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
101176                     var start = nodes.pos;
101177                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
101178                 }
101179                 // Since these are syntactic diagnostics, parent might not have been set
101180                 // this means the sourceFile cannot be infered from the node
101181                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
101182                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
101183                 }
101184             });
101185         }
101186         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
101187             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
101188         }
101189         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
101190             return runWithCancellationToken(function () {
101191                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
101192                 // Don't actually write any files since we're just getting diagnostics.
101193                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
101194             });
101195         }
101196         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
101197             var cachedResult = sourceFile
101198                 ? cache.perFile && cache.perFile.get(sourceFile.path)
101199                 : cache.allDiagnostics;
101200             if (cachedResult) {
101201                 return cachedResult;
101202             }
101203             var result = getDiagnostics(sourceFile, cancellationToken);
101204             if (sourceFile) {
101205                 if (!cache.perFile) {
101206                     cache.perFile = ts.createMap();
101207                 }
101208                 cache.perFile.set(sourceFile.path, result);
101209             }
101210             else {
101211                 cache.allDiagnostics = result;
101212             }
101213             return result;
101214         }
101215         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
101216             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
101217         }
101218         function getOptionsDiagnostics() {
101219             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
101220         }
101221         function getOptionsDiagnosticsOfConfigFile() {
101222             if (!options.configFile) {
101223                 return ts.emptyArray;
101224             }
101225             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
101226             forEachResolvedProjectReference(function (resolvedRef) {
101227                 if (resolvedRef) {
101228                     diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
101229                 }
101230             });
101231             return diagnostics;
101232         }
101233         function getGlobalDiagnostics() {
101234             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
101235         }
101236         function getConfigFileParsingDiagnostics() {
101237             return configFileParsingDiagnostics || ts.emptyArray;
101238         }
101239         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
101240             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
101241         }
101242         function fileReferenceIsEqualTo(a, b) {
101243             return a.fileName === b.fileName;
101244         }
101245         function moduleNameIsEqualTo(a, b) {
101246             return a.kind === 75 /* Identifier */
101247                 ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
101248                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
101249         }
101250         function collectExternalModuleReferences(file) {
101251             if (file.imports) {
101252                 return;
101253             }
101254             var isJavaScriptFile = ts.isSourceFileJS(file);
101255             var isExternalModuleFile = ts.isExternalModule(file);
101256             // file.imports may not be undefined if there exists dynamic import
101257             var imports;
101258             var moduleAugmentations;
101259             var ambientModules;
101260             // If we are importing helpers, we need to add a synthetic reference to resolve the
101261             // helpers library.
101262             if (options.importHelpers
101263                 && (options.isolatedModules || isExternalModuleFile)
101264                 && !file.isDeclarationFile) {
101265                 // synthesize 'import "tslib"' declaration
101266                 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
101267                 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
101268                 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
101269                 externalHelpersModuleReference.parent = importDecl;
101270                 importDecl.parent = file;
101271                 imports = [externalHelpersModuleReference];
101272             }
101273             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
101274                 var node = _a[_i];
101275                 collectModuleReferences(node, /*inAmbientModule*/ false);
101276             }
101277             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
101278                 collectDynamicImportOrRequireCalls(file);
101279             }
101280             file.imports = imports || ts.emptyArray;
101281             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
101282             file.ambientModuleNames = ambientModules || ts.emptyArray;
101283             return;
101284             function collectModuleReferences(node, inAmbientModule) {
101285                 if (ts.isAnyImportOrReExport(node)) {
101286                     var moduleNameExpr = ts.getExternalModuleName(node);
101287                     // TypeScript 1.0 spec (April 2014): 12.1.6
101288                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
101289                     // only through top - level external module names. Relative external module names are not permitted.
101290                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
101291                         imports = ts.append(imports, moduleNameExpr);
101292                     }
101293                 }
101294                 else if (ts.isModuleDeclaration(node)) {
101295                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
101296                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
101297                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
101298                         // This will happen in two cases:
101299                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
101300                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
101301                         //   immediately nested in top level ambient module declaration .
101302                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
101303                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
101304                         }
101305                         else if (!inAmbientModule) {
101306                             if (file.isDeclarationFile) {
101307                                 // for global .d.ts files record name of ambient module
101308                                 (ambientModules || (ambientModules = [])).push(nameText);
101309                             }
101310                             // An AmbientExternalModuleDeclaration declares an external module.
101311                             // This type of declaration is permitted only in the global module.
101312                             // The StringLiteral must specify a top - level external module name.
101313                             // Relative external module names are not permitted
101314                             // NOTE: body of ambient module is always a module block, if it exists
101315                             var body = node.body;
101316                             if (body) {
101317                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
101318                                     var statement = _a[_i];
101319                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
101320                                 }
101321                             }
101322                         }
101323                     }
101324                 }
101325             }
101326             function collectDynamicImportOrRequireCalls(file) {
101327                 var r = /import|require/g;
101328                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
101329                     var node = getNodeAtPosition(file, r.lastIndex);
101330                     if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
101331                         imports = ts.append(imports, node.arguments[0]);
101332                     }
101333                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
101334                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
101335                         imports = ts.append(imports, node.arguments[0]);
101336                     }
101337                     else if (ts.isLiteralImportTypeNode(node)) {
101338                         imports = ts.append(imports, node.argument.literal);
101339                     }
101340                 }
101341             }
101342             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
101343             function getNodeAtPosition(sourceFile, position) {
101344                 var current = sourceFile;
101345                 var getContainingChild = function (child) {
101346                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
101347                         return child;
101348                     }
101349                 };
101350                 while (true) {
101351                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
101352                     if (!child) {
101353                         return current;
101354                     }
101355                     current = child;
101356                 }
101357             }
101358         }
101359         function getLibFileFromReference(ref) {
101360             var libName = ts.toFileNameLowerCase(ref.fileName);
101361             var libFileName = ts.libMap.get(libName);
101362             if (libFileName) {
101363                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
101364             }
101365         }
101366         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
101367         function getSourceFileFromReference(referencingFile, ref) {
101368             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
101369         }
101370         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
101371             if (ts.hasExtension(fileName)) {
101372                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
101373                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
101374                     if (fail) {
101375                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
101376                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
101377                         }
101378                         else {
101379                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101380                         }
101381                     }
101382                     return undefined;
101383                 }
101384                 var sourceFile = getSourceFile(fileName);
101385                 if (fail) {
101386                     if (!sourceFile) {
101387                         var redirect = getProjectReferenceRedirect(fileName);
101388                         if (redirect) {
101389                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
101390                         }
101391                         else {
101392                             fail(ts.Diagnostics.File_0_not_found, fileName);
101393                         }
101394                     }
101395                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
101396                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
101397                     }
101398                 }
101399                 return sourceFile;
101400             }
101401             else {
101402                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
101403                 if (sourceFileNoExtension)
101404                     return sourceFileNoExtension;
101405                 if (fail && options.allowNonTsExtensions) {
101406                     fail(ts.Diagnostics.File_0_not_found, fileName);
101407                     return undefined;
101408                 }
101409                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
101410                 if (fail && !sourceFileWithAddedExtension)
101411                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101412                 return sourceFileWithAddedExtension;
101413             }
101414         }
101415         /** This has side effects through `findSourceFile`. */
101416         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
101417             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
101418             function (diagnostic) {
101419                 var args = [];
101420                 for (var _i = 1; _i < arguments.length; _i++) {
101421                     args[_i - 1] = arguments[_i];
101422                 }
101423                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
101424             }, refFile && refFile.file);
101425         }
101426         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
101427             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
101428             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
101429             fileProcessingDiagnostics.add(refToReportErrorOn ?
101430                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
101431                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
101432         }
101433         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
101434             var redirect = Object.create(redirectTarget);
101435             redirect.fileName = fileName;
101436             redirect.path = path;
101437             redirect.resolvedPath = resolvedPath;
101438             redirect.originalFileName = originalFileName;
101439             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
101440             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101441             Object.defineProperties(redirect, {
101442                 id: {
101443                     get: function () { return this.redirectInfo.redirectTarget.id; },
101444                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
101445                 },
101446                 symbol: {
101447                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
101448                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
101449                 },
101450             });
101451             return redirect;
101452         }
101453         // Get source file from normalized fileName
101454         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
101455             if (useSourceOfProjectReferenceRedirect) {
101456                 var source = getSourceOfProjectReferenceRedirect(fileName);
101457                 // If preserveSymlinks is true, module resolution wont jump the symlink
101458                 // but the resolved real path may be the .d.ts from project reference
101459                 // Note:: Currently we try the real path only if the
101460                 // file is from node_modules to avoid having to run real path on all file paths
101461                 if (!source &&
101462                     host.realpath &&
101463                     options.preserveSymlinks &&
101464                     ts.isDeclarationFileName(fileName) &&
101465                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
101466                     var realPath = host.realpath(fileName);
101467                     if (realPath !== fileName)
101468                         source = getSourceOfProjectReferenceRedirect(realPath);
101469                 }
101470                 if (source) {
101471                     var file_1 = ts.isString(source) ?
101472                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
101473                         undefined;
101474                     if (file_1)
101475                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
101476                     return file_1;
101477                 }
101478             }
101479             var originalFileName = fileName;
101480             if (filesByName.has(path)) {
101481                 var file_2 = filesByName.get(path);
101482                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
101483                 // try to check if we've already seen this file but with a different casing in path
101484                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
101485                 if (file_2 && options.forceConsistentCasingInFileNames) {
101486                     var checkedName = file_2.fileName;
101487                     var isRedirect = toPath(checkedName) !== toPath(fileName);
101488                     if (isRedirect) {
101489                         fileName = getProjectReferenceRedirect(fileName) || fileName;
101490                     }
101491                     // Check if it differs only in drive letters its ok to ignore that error:
101492                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
101493                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
101494                     if (checkedAbsolutePath !== inputAbsolutePath) {
101495                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
101496                     }
101497                 }
101498                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
101499                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
101500                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
101501                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
101502                     if (!options.noResolve) {
101503                         processReferencedFiles(file_2, isDefaultLib);
101504                         processTypeReferenceDirectives(file_2);
101505                     }
101506                     if (!options.noLib) {
101507                         processLibReferenceDirectives(file_2);
101508                     }
101509                     modulesWithElidedImports.set(file_2.path, false);
101510                     processImportedModules(file_2);
101511                 }
101512                 // See if we need to reprocess the imports due to prior skipped imports
101513                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
101514                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
101515                         modulesWithElidedImports.set(file_2.path, false);
101516                         processImportedModules(file_2);
101517                     }
101518                 }
101519                 return file_2 || undefined;
101520             }
101521             var redirectedPath;
101522             if (refFile && !useSourceOfProjectReferenceRedirect) {
101523                 var redirectProject = getProjectReferenceRedirectProject(fileName);
101524                 if (redirectProject) {
101525                     if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
101526                         // Shouldnt create many to 1 mapping file in --out scenario
101527                         return undefined;
101528                     }
101529                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
101530                     fileName = redirect;
101531                     // Once we start redirecting to a file, we can potentially come back to it
101532                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
101533                     // end up trying to add it to the program *again* because we were tracking it via its
101534                     // original (un-redirected) name. So we have to map both the original path and the redirected path
101535                     // to the source file we're about to find/create
101536                     redirectedPath = toPath(redirect);
101537                 }
101538             }
101539             // We haven't looked for this file, do so now and cache result
101540             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);
101541             if (packageId) {
101542                 var packageIdKey = ts.packageIdToString(packageId);
101543                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
101544                 if (fileFromPackageId) {
101545                     // Some other SourceFile already exists with this package name and version.
101546                     // Instead of creating a duplicate, just redirect to the existing one.
101547                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
101548                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
101549                     addFileToFilesByName(dupFile, path, redirectedPath);
101550                     sourceFileToPackageName.set(path, packageId.name);
101551                     processingOtherFiles.push(dupFile);
101552                     return dupFile;
101553                 }
101554                 else if (file) {
101555                     // This is the first source file to have this packageId.
101556                     packageIdToSourceFile.set(packageIdKey, file);
101557                     sourceFileToPackageName.set(path, packageId.name);
101558                 }
101559             }
101560             addFileToFilesByName(file, path, redirectedPath);
101561             if (file) {
101562                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101563                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
101564                 file.path = path;
101565                 file.resolvedPath = toPath(fileName);
101566                 file.originalFileName = originalFileName;
101567                 addFileToRefFileMap(fileName, file, refFile);
101568                 if (host.useCaseSensitiveFileNames()) {
101569                     var pathLowerCase = ts.toFileNameLowerCase(path);
101570                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
101571                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
101572                     if (existingFile) {
101573                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
101574                     }
101575                     else {
101576                         filesByNameIgnoreCase.set(pathLowerCase, file);
101577                     }
101578                 }
101579                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
101580                 if (!options.noResolve) {
101581                     processReferencedFiles(file, isDefaultLib);
101582                     processTypeReferenceDirectives(file);
101583                 }
101584                 if (!options.noLib) {
101585                     processLibReferenceDirectives(file);
101586                 }
101587                 // always process imported modules to record module name resolutions
101588                 processImportedModules(file);
101589                 if (isDefaultLib) {
101590                     processingDefaultLibFiles.push(file);
101591                 }
101592                 else {
101593                     processingOtherFiles.push(file);
101594                 }
101595             }
101596             return file;
101597         }
101598         function addFileToRefFileMap(referencedFileName, file, refFile) {
101599             if (refFile && file) {
101600                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
101601                     referencedFileName: referencedFileName,
101602                     kind: refFile.kind,
101603                     index: refFile.index,
101604                     file: refFile.file.path
101605                 });
101606             }
101607         }
101608         function addFileToFilesByName(file, path, redirectedPath) {
101609             if (redirectedPath) {
101610                 filesByName.set(redirectedPath, file);
101611                 filesByName.set(path, file || false);
101612             }
101613             else {
101614                 filesByName.set(path, file);
101615             }
101616         }
101617         function getProjectReferenceRedirect(fileName) {
101618             var referencedProject = getProjectReferenceRedirectProject(fileName);
101619             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
101620         }
101621         function getProjectReferenceRedirectProject(fileName) {
101622             // Ignore dts or any json files
101623             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101624                 return undefined;
101625             }
101626             // If this file is produced by a referenced project, we need to rewrite it to
101627             // look in the output folder of the referenced project rather than the input
101628             return getResolvedProjectReferenceToRedirect(fileName);
101629         }
101630         function getProjectReferenceOutputName(referencedProject, fileName) {
101631             var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
101632             return out ?
101633                 ts.changeExtension(out, ".d.ts" /* Dts */) :
101634                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
101635         }
101636         /**
101637          * Get the referenced project if the file is input file from that reference project
101638          */
101639         function getResolvedProjectReferenceToRedirect(fileName) {
101640             if (mapFromFileToProjectReferenceRedirects === undefined) {
101641                 mapFromFileToProjectReferenceRedirects = ts.createMap();
101642                 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
101643                     // not input file from the referenced project, ignore
101644                     if (referencedProject &&
101645                         toPath(options.configFilePath) !== referenceProjectPath) {
101646                         referencedProject.commandLine.fileNames.forEach(function (f) {
101647                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
101648                         });
101649                     }
101650                 });
101651             }
101652             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
101653             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
101654         }
101655         function forEachResolvedProjectReference(cb) {
101656             return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
101657                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
101658                 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
101659                 return cb(resolvedRef, resolvedRefPath);
101660             });
101661         }
101662         function getSourceOfProjectReferenceRedirect(file) {
101663             if (!ts.isDeclarationFileName(file))
101664                 return undefined;
101665             if (mapFromToProjectReferenceRedirectSource === undefined) {
101666                 mapFromToProjectReferenceRedirectSource = ts.createMap();
101667                 forEachResolvedProjectReference(function (resolvedRef) {
101668                     if (resolvedRef) {
101669                         var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
101670                         if (out) {
101671                             // Dont know which source file it means so return true?
101672                             var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
101673                             mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
101674                         }
101675                         else {
101676                             ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
101677                                 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101678                                     var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
101679                                     mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
101680                                 }
101681                             });
101682                         }
101683                     }
101684                 });
101685             }
101686             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
101687         }
101688         function isSourceOfProjectReferenceRedirect(fileName) {
101689             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
101690         }
101691         function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
101692             var seenResolvedRefs;
101693             return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
101694             function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
101695                 // Visit project references first
101696                 if (cbRef) {
101697                     var result = cbRef(projectReferences, parent);
101698                     if (result) {
101699                         return result;
101700                     }
101701                 }
101702                 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
101703                     if (ts.contains(seenResolvedRefs, resolvedRef)) {
101704                         // ignore recursives
101705                         return undefined;
101706                     }
101707                     var result = cbResolvedRef(resolvedRef, index, parent);
101708                     if (result) {
101709                         return result;
101710                     }
101711                     if (!resolvedRef)
101712                         return undefined;
101713                     (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
101714                     return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
101715                 });
101716             }
101717         }
101718         function getResolvedProjectReferenceByPath(projectReferencePath) {
101719             if (!projectReferenceRedirects) {
101720                 return undefined;
101721             }
101722             return projectReferenceRedirects.get(projectReferencePath) || undefined;
101723         }
101724         function processReferencedFiles(file, isDefaultLib) {
101725             ts.forEach(file.referencedFiles, function (ref, index) {
101726                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
101727                 processSourceFile(referencedFileName, isDefaultLib, 
101728                 /*ignoreNoDefaultLib*/ false, 
101729                 /*packageId*/ undefined, {
101730                     kind: ts.RefFileKind.ReferenceFile,
101731                     index: index,
101732                     file: file,
101733                     pos: ref.pos,
101734                     end: ref.end
101735                 });
101736             });
101737         }
101738         function processTypeReferenceDirectives(file) {
101739             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
101740             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
101741             if (!typeDirectives) {
101742                 return;
101743             }
101744             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
101745             for (var i = 0; i < typeDirectives.length; i++) {
101746                 var ref = file.typeReferenceDirectives[i];
101747                 var resolvedTypeReferenceDirective = resolutions[i];
101748                 // store resolved type directive on the file
101749                 var fileName = ts.toFileNameLowerCase(ref.fileName);
101750                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
101751                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
101752                     kind: ts.RefFileKind.TypeReferenceDirective,
101753                     index: i,
101754                     file: file,
101755                     pos: ref.pos,
101756                     end: ref.end
101757                 });
101758             }
101759         }
101760         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
101761             // If we already found this library as a primary reference - nothing to do
101762             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
101763             if (previousResolution && previousResolution.primary) {
101764                 return;
101765             }
101766             var saveResolution = true;
101767             if (resolvedTypeReferenceDirective) {
101768                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101769                     currentNodeModulesDepth++;
101770                 if (resolvedTypeReferenceDirective.primary) {
101771                     // resolved from the primary path
101772                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
101773                 }
101774                 else {
101775                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
101776                     // for sameness and possibly issue an error
101777                     if (previousResolution) {
101778                         // Don't bother reading the file again if it's the same file.
101779                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
101780                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
101781                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
101782                             if (otherFileText !== existingFile_1.text) {
101783                                 // Try looking up ref for original file
101784                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
101785                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
101786                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
101787                                     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) :
101788                                     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));
101789                             }
101790                         }
101791                         // don't overwrite previous resolution result
101792                         saveResolution = false;
101793                     }
101794                     else {
101795                         // First resolution of this library
101796                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
101797                     }
101798                 }
101799                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101800                     currentNodeModulesDepth--;
101801             }
101802             else {
101803                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
101804             }
101805             if (saveResolution) {
101806                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
101807             }
101808         }
101809         function processLibReferenceDirectives(file) {
101810             ts.forEach(file.libReferenceDirectives, function (libReference) {
101811                 var libName = ts.toFileNameLowerCase(libReference.fileName);
101812                 var libFileName = ts.libMap.get(libName);
101813                 if (libFileName) {
101814                     // we ignore any 'no-default-lib' reference set on this file.
101815                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
101816                 }
101817                 else {
101818                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
101819                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
101820                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
101821                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
101822                 }
101823             });
101824         }
101825         function createRefFileDiagnostic(refFile, message) {
101826             var args = [];
101827             for (var _i = 2; _i < arguments.length; _i++) {
101828                 args[_i - 2] = arguments[_i];
101829             }
101830             if (!refFile) {
101831                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
101832             }
101833             else {
101834                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
101835             }
101836         }
101837         function getCanonicalFileName(fileName) {
101838             return host.getCanonicalFileName(fileName);
101839         }
101840         function processImportedModules(file) {
101841             collectExternalModuleReferences(file);
101842             if (file.imports.length || file.moduleAugmentations.length) {
101843                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
101844                 var moduleNames = getModuleNames(file);
101845                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
101846                 ts.Debug.assert(resolutions.length === moduleNames.length);
101847                 for (var i = 0; i < moduleNames.length; i++) {
101848                     var resolution = resolutions[i];
101849                     ts.setResolvedModule(file, moduleNames[i], resolution);
101850                     if (!resolution) {
101851                         continue;
101852                     }
101853                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
101854                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
101855                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
101856                     var resolvedFileName = resolution.resolvedFileName;
101857                     if (isFromNodeModulesSearch) {
101858                         currentNodeModulesDepth++;
101859                     }
101860                     // add file to program only if:
101861                     // - resolution was successful
101862                     // - noResolve is falsy
101863                     // - module name comes from the list of imports
101864                     // - it's not a top level JavaScript module that exceeded the search max
101865                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
101866                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
101867                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
101868                     var shouldAddFile = resolvedFileName
101869                         && !getResolutionDiagnostic(options, resolution)
101870                         && !options.noResolve
101871                         && i < file.imports.length
101872                         && !elideImport
101873                         && !(isJsFile && !options.allowJs)
101874                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
101875                     if (elideImport) {
101876                         modulesWithElidedImports.set(file.path, true);
101877                     }
101878                     else if (shouldAddFile) {
101879                         var path = toPath(resolvedFileName);
101880                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
101881                         findSourceFile(resolvedFileName, path, 
101882                         /*isDefaultLib*/ false, 
101883                         /*ignoreNoDefaultLib*/ false, {
101884                             kind: ts.RefFileKind.Import,
101885                             index: i,
101886                             file: file,
101887                             pos: pos,
101888                             end: file.imports[i].end
101889                         }, resolution.packageId);
101890                     }
101891                     if (isFromNodeModulesSearch) {
101892                         currentNodeModulesDepth--;
101893                     }
101894                 }
101895             }
101896             else {
101897                 // no imports - drop cached module resolutions
101898                 file.resolvedModules = undefined;
101899             }
101900         }
101901         function computeCommonSourceDirectory(sourceFiles) {
101902             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
101903             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
101904         }
101905         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
101906             var allFilesBelongToPath = true;
101907             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
101908             var rootPaths;
101909             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
101910                 var sourceFile = sourceFiles_2[_i];
101911                 if (!sourceFile.isDeclarationFile) {
101912                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
101913                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
101914                         if (!rootPaths)
101915                             rootPaths = ts.arrayToSet(rootNames, toPath);
101916                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
101917                         allFilesBelongToPath = false;
101918                     }
101919                 }
101920             }
101921             return allFilesBelongToPath;
101922         }
101923         function parseProjectReferenceConfigFile(ref) {
101924             if (!projectReferenceRedirects) {
101925                 projectReferenceRedirects = ts.createMap();
101926             }
101927             // The actual filename (i.e. add "/tsconfig.json" if necessary)
101928             var refPath = resolveProjectReferencePath(ref);
101929             var sourceFilePath = toPath(refPath);
101930             var fromCache = projectReferenceRedirects.get(sourceFilePath);
101931             if (fromCache !== undefined) {
101932                 return fromCache || undefined;
101933             }
101934             var commandLine;
101935             var sourceFile;
101936             if (host.getParsedCommandLine) {
101937                 commandLine = host.getParsedCommandLine(refPath);
101938                 if (!commandLine) {
101939                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
101940                     projectReferenceRedirects.set(sourceFilePath, false);
101941                     return undefined;
101942                 }
101943                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
101944                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
101945                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101946             }
101947             else {
101948                 // An absolute path pointing to the containing directory of the config file
101949                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
101950                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
101951                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101952                 if (sourceFile === undefined) {
101953                     projectReferenceRedirects.set(sourceFilePath, false);
101954                     return undefined;
101955                 }
101956                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
101957             }
101958             sourceFile.fileName = refPath;
101959             sourceFile.path = sourceFilePath;
101960             sourceFile.resolvedPath = sourceFilePath;
101961             sourceFile.originalFileName = refPath;
101962             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
101963             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
101964             if (commandLine.projectReferences) {
101965                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
101966             }
101967             return resolvedRef;
101968         }
101969         function verifyCompilerOptions() {
101970             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
101971                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
101972             }
101973             if (options.isolatedModules) {
101974                 if (options.out) {
101975                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
101976                 }
101977                 if (options.outFile) {
101978                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
101979                 }
101980             }
101981             if (options.inlineSourceMap) {
101982                 if (options.sourceMap) {
101983                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
101984                 }
101985                 if (options.mapRoot) {
101986                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
101987                 }
101988             }
101989             if (options.paths && options.baseUrl === undefined) {
101990                 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
101991             }
101992             if (options.composite) {
101993                 if (options.declaration === false) {
101994                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
101995                 }
101996                 if (options.incremental === false) {
101997                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
101998                 }
101999             }
102000             if (options.tsBuildInfoFile) {
102001                 if (!ts.isIncrementalCompilation(options)) {
102002                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
102003                 }
102004             }
102005             else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
102006                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
102007             }
102008             if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
102009                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
102010             }
102011             verifyProjectReferences();
102012             // List of collected files is complete; validate exhautiveness if this is a project with a file list
102013             if (options.composite) {
102014                 var rootPaths = ts.arrayToSet(rootNames, toPath);
102015                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
102016                     var file = files_3[_i];
102017                     // Ignore file that is not emitted
102018                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
102019                         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 || "");
102020                     }
102021                 }
102022             }
102023             if (options.paths) {
102024                 for (var key in options.paths) {
102025                     if (!ts.hasProperty(options.paths, key)) {
102026                         continue;
102027                     }
102028                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
102029                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
102030                     }
102031                     if (ts.isArray(options.paths[key])) {
102032                         var len = options.paths[key].length;
102033                         if (len === 0) {
102034                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
102035                         }
102036                         for (var i = 0; i < len; i++) {
102037                             var subst = options.paths[key][i];
102038                             var typeOfSubst = typeof subst;
102039                             if (typeOfSubst === "string") {
102040                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
102041                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
102042                                 }
102043                             }
102044                             else {
102045                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
102046                             }
102047                         }
102048                     }
102049                     else {
102050                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
102051                     }
102052                 }
102053             }
102054             if (!options.sourceMap && !options.inlineSourceMap) {
102055                 if (options.inlineSources) {
102056                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
102057                 }
102058                 if (options.sourceRoot) {
102059                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
102060                 }
102061             }
102062             if (options.out && options.outFile) {
102063                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
102064             }
102065             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
102066                 // Error to specify --mapRoot without --sourcemap
102067                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
102068             }
102069             if (options.declarationDir) {
102070                 if (!ts.getEmitDeclarations(options)) {
102071                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
102072                 }
102073                 if (options.out || options.outFile) {
102074                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
102075                 }
102076             }
102077             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
102078                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
102079             }
102080             if (options.lib && options.noLib) {
102081                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
102082             }
102083             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
102084                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
102085             }
102086             var languageVersion = options.target || 0 /* ES3 */;
102087             var outFile = options.outFile || options.out;
102088             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
102089             if (options.isolatedModules) {
102090                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
102091                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
102092                 }
102093                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
102094                 if (firstNonExternalModuleSourceFile) {
102095                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
102096                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
102097                 }
102098             }
102099             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
102100                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
102101                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
102102                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
102103             }
102104             // Cannot specify module gen that isn't amd or system with --out
102105             if (outFile && !options.emitDeclarationOnly) {
102106                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
102107                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
102108                 }
102109                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
102110                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
102111                     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"));
102112                 }
102113             }
102114             if (options.resolveJsonModule) {
102115                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
102116                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
102117                 }
102118                 // Any emit other than common js, amd, es2015 or esnext is error
102119                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
102120                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
102121                 }
102122             }
102123             // there has to be common source directory if user specified --outdir || --sourceRoot
102124             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
102125             if (options.outDir || // there is --outDir specified
102126                 options.sourceRoot || // there is --sourceRoot specified
102127                 options.mapRoot) { // there is --mapRoot specified
102128                 // Precalculate and cache the common source directory
102129                 var dir = getCommonSourceDirectory();
102130                 // 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
102131                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
102132                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
102133                 }
102134             }
102135             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
102136                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
102137             }
102138             if (options.checkJs && !options.allowJs) {
102139                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
102140             }
102141             if (options.emitDeclarationOnly) {
102142                 if (!ts.getEmitDeclarations(options)) {
102143                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
102144                 }
102145                 if (options.noEmit) {
102146                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
102147                 }
102148             }
102149             if (options.emitDecoratorMetadata &&
102150                 !options.experimentalDecorators) {
102151                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
102152             }
102153             if (options.jsxFactory) {
102154                 if (options.reactNamespace) {
102155                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
102156                 }
102157                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
102158                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
102159                 }
102160             }
102161             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
102162                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
102163             }
102164             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
102165             if (!options.noEmit && !options.suppressOutputPathCheck) {
102166                 var emitHost = getEmitHost();
102167                 var emitFilesSeen_1 = ts.createMap();
102168                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
102169                     if (!options.emitDeclarationOnly) {
102170                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
102171                     }
102172                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
102173                 });
102174             }
102175             // Verify that all the emit files are unique and don't overwrite input files
102176             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
102177                 if (emitFileName) {
102178                     var emitFilePath = toPath(emitFileName);
102179                     // Report error if the output overwrites input file
102180                     if (filesByName.has(emitFilePath)) {
102181                         var chain = void 0;
102182                         if (!options.configFilePath) {
102183                             // The program is from either an inferred project or an external project
102184                             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);
102185                         }
102186                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
102187                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
102188                     }
102189                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
102190                     // Report error if multiple files write into same file
102191                     if (emitFilesSeen.has(emitFileKey)) {
102192                         // Already seen the same emit file - report error
102193                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
102194                     }
102195                     else {
102196                         emitFilesSeen.set(emitFileKey, true);
102197                     }
102198                 }
102199             }
102200         }
102201         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
102202             var _a, _b;
102203             var args = [];
102204             for (var _i = 2; _i < arguments.length; _i++) {
102205                 args[_i - 2] = arguments[_i];
102206             }
102207             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
102208             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
102209             var pos, end;
102210             switch (kind) {
102211                 case ts.RefFileKind.Import:
102212                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
102213                     end = refFile.imports[index].end;
102214                     break;
102215                 case ts.RefFileKind.ReferenceFile:
102216                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
102217                     break;
102218                 case ts.RefFileKind.TypeReferenceDirective:
102219                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
102220                     break;
102221                 default:
102222                     return ts.Debug.assertNever(kind);
102223             }
102224             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
102225         }
102226         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
102227             var args = [];
102228             for (var _i = 3; _i < arguments.length; _i++) {
102229                 args[_i - 3] = arguments[_i];
102230             }
102231             var refPaths = refFileMap && refFileMap.get(file.path);
102232             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
102233                 ts.elementAt(refPaths, 0);
102234             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
102235         }
102236         function verifyProjectReferences() {
102237             var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
102238             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
102239                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
102240                 var parentFile = parent && parent.sourceFile;
102241                 if (!resolvedRef) {
102242                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
102243                     return;
102244                 }
102245                 var options = resolvedRef.commandLine.options;
102246                 if (!options.composite) {
102247                     // ok to not have composite if the current program is container only
102248                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
102249                     if (inputs.length) {
102250                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
102251                     }
102252                 }
102253                 if (ref.prepend) {
102254                     var out = options.outFile || options.out;
102255                     if (out) {
102256                         if (!host.fileExists(out)) {
102257                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
102258                         }
102259                     }
102260                     else {
102261                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
102262                     }
102263                 }
102264                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
102265                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
102266                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
102267                 }
102268             });
102269         }
102270         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
102271             var needCompilerDiagnostic = true;
102272             var pathsSyntax = getOptionPathsSyntax();
102273             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
102274                 var pathProp = pathsSyntax_1[_i];
102275                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
102276                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
102277                         var keyProps = _b[_a];
102278                         var initializer = keyProps.initializer;
102279                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
102280                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
102281                             needCompilerDiagnostic = false;
102282                         }
102283                     }
102284                 }
102285             }
102286             if (needCompilerDiagnostic) {
102287                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102288             }
102289         }
102290         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
102291             var needCompilerDiagnostic = true;
102292             var pathsSyntax = getOptionPathsSyntax();
102293             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
102294                 var pathProp = pathsSyntax_2[_i];
102295                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
102296                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
102297                     needCompilerDiagnostic = false;
102298                 }
102299             }
102300             if (needCompilerDiagnostic) {
102301                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
102302             }
102303         }
102304         function getOptionsSyntaxByName(name) {
102305             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102306             if (compilerOptionsObjectLiteralSyntax) {
102307                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
102308             }
102309             return undefined;
102310         }
102311         function getOptionPathsSyntax() {
102312             return getOptionsSyntaxByName("paths") || ts.emptyArray;
102313         }
102314         function createDiagnosticForOptionName(message, option1, option2, option3) {
102315             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
102316         }
102317         function createOptionValueDiagnostic(option1, message, arg0) {
102318             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
102319         }
102320         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
102321             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
102322             if (referencesSyntax && referencesSyntax.elements.length > index) {
102323                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
102324             }
102325             else {
102326                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
102327             }
102328         }
102329         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
102330             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102331             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
102332                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
102333             if (needCompilerDiagnostic) {
102334                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102335             }
102336         }
102337         function getCompilerOptionsObjectLiteralSyntax() {
102338             if (_compilerOptionsObjectLiteralSyntax === undefined) {
102339                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
102340                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
102341                 if (jsonObjectLiteral) {
102342                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
102343                         var prop = _a[_i];
102344                         if (ts.isObjectLiteralExpression(prop.initializer)) {
102345                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
102346                             break;
102347                         }
102348                     }
102349                 }
102350             }
102351             return _compilerOptionsObjectLiteralSyntax;
102352         }
102353         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
102354             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
102355             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
102356                 var prop = props_3[_i];
102357                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
102358             }
102359             return !!props.length;
102360         }
102361         function blockEmittingOfFile(emitFileName, diag) {
102362             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
102363             programDiagnostics.add(diag);
102364         }
102365         function isEmittedFile(file) {
102366             if (options.noEmit) {
102367                 return false;
102368             }
102369             // If this is source file, its not emitted file
102370             var filePath = toPath(file);
102371             if (getSourceFileByPath(filePath)) {
102372                 return false;
102373             }
102374             // If options have --outFile or --out just check that
102375             var out = options.outFile || options.out;
102376             if (out) {
102377                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
102378             }
102379             // If declarationDir is specified, return if its a file in that directory
102380             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
102381                 return true;
102382             }
102383             // If --outDir, check if file is in that directory
102384             if (options.outDir) {
102385                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
102386             }
102387             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
102388                 // Otherwise just check if sourceFile with the name exists
102389                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
102390                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
102391                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
102392             }
102393             return false;
102394         }
102395         function isSameFile(file1, file2) {
102396             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
102397         }
102398         function getProbableSymlinks() {
102399             if (host.getSymlinks) {
102400                 return host.getSymlinks();
102401             }
102402             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
102403         }
102404     }
102405     ts.createProgram = createProgram;
102406     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
102407         var mapOfDeclarationDirectories;
102408         var symlinkedDirectories;
102409         var symlinkedFiles;
102410         var originalFileExists = host.compilerHost.fileExists;
102411         var originalDirectoryExists = host.compilerHost.directoryExists;
102412         var originalGetDirectories = host.compilerHost.getDirectories;
102413         var originalRealpath = host.compilerHost.realpath;
102414         if (!host.useSourceOfProjectReferenceRedirect)
102415             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
102416         host.compilerHost.fileExists = fileExists;
102417         if (originalDirectoryExists) {
102418             // This implementation of directoryExists checks if the directory being requested is
102419             // directory of .d.ts file for the referenced Project.
102420             // If it is it returns true irrespective of whether that directory exists on host
102421             host.compilerHost.directoryExists = function (path) {
102422                 if (originalDirectoryExists.call(host.compilerHost, path)) {
102423                     handleDirectoryCouldBeSymlink(path);
102424                     return true;
102425                 }
102426                 if (!host.getResolvedProjectReferences())
102427                     return false;
102428                 if (!mapOfDeclarationDirectories) {
102429                     mapOfDeclarationDirectories = ts.createMap();
102430                     host.forEachResolvedProjectReference(function (ref) {
102431                         if (!ref)
102432                             return;
102433                         var out = ref.commandLine.options.outFile || ref.commandLine.options.out;
102434                         if (out) {
102435                             mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true);
102436                         }
102437                         else {
102438                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
102439                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
102440                             if (declarationDir) {
102441                                 mapOfDeclarationDirectories.set(host.toPath(declarationDir), true);
102442                             }
102443                         }
102444                     });
102445                 }
102446                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
102447             };
102448         }
102449         if (originalGetDirectories) {
102450             // Call getDirectories only if directory actually present on the host
102451             // This is needed to ensure that we arent getting directories that we fake about presence for
102452             host.compilerHost.getDirectories = function (path) {
102453                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
102454                     originalGetDirectories.call(host.compilerHost, path) :
102455                     [];
102456             };
102457         }
102458         // This is something we keep for life time of the host
102459         if (originalRealpath) {
102460             host.compilerHost.realpath = function (s) {
102461                 return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) ||
102462                     originalRealpath.call(host.compilerHost, s);
102463             };
102464         }
102465         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists };
102466         function onProgramCreateComplete() {
102467             host.compilerHost.fileExists = originalFileExists;
102468             host.compilerHost.directoryExists = originalDirectoryExists;
102469             host.compilerHost.getDirectories = originalGetDirectories;
102470             // DO not revert realpath as it could be used later
102471         }
102472         // This implementation of fileExists checks if the file being requested is
102473         // .d.ts file for the referenced Project.
102474         // If it is it returns true irrespective of whether that file exists on host
102475         function fileExists(file) {
102476             if (originalFileExists.call(host.compilerHost, file))
102477                 return true;
102478             if (!host.getResolvedProjectReferences())
102479                 return false;
102480             if (!ts.isDeclarationFileName(file))
102481                 return false;
102482             // Project references go to source file instead of .d.ts file
102483             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
102484         }
102485         function fileExistsIfProjectReferenceDts(file) {
102486             var source = host.getSourceOfProjectReferenceRedirect(file);
102487             return source !== undefined ?
102488                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
102489                 undefined;
102490         }
102491         function directoryExistsIfProjectReferenceDeclDir(dir) {
102492             var dirPath = host.toPath(dir);
102493             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
102494             return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
102495                 // Any parent directory of declaration dir
102496                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
102497                 // Any directory inside declaration dir
102498                 ts.startsWith(dirPath, declDirPath + "/"); });
102499         }
102500         function handleDirectoryCouldBeSymlink(directory) {
102501             if (!host.getResolvedProjectReferences())
102502                 return;
102503             // Because we already watch node_modules, handle symlinks in there
102504             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
102505                 return;
102506             if (!symlinkedDirectories)
102507                 symlinkedDirectories = ts.createMap();
102508             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
102509             if (symlinkedDirectories.has(directoryPath))
102510                 return;
102511             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
102512             var realPath;
102513             if (real === directory ||
102514                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
102515                 // not symlinked
102516                 symlinkedDirectories.set(directoryPath, false);
102517                 return;
102518             }
102519             symlinkedDirectories.set(directoryPath, {
102520                 real: ts.ensureTrailingDirectorySeparator(real),
102521                 realPath: realPath
102522             });
102523         }
102524         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
102525             var fileOrDirectoryExistsUsingSource = isFile ?
102526                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
102527                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
102528             // Check current directory or file
102529             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
102530             if (result !== undefined)
102531                 return result;
102532             if (!symlinkedDirectories)
102533                 return false;
102534             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
102535             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
102536                 return false;
102537             if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath))
102538                 return true;
102539             // If it contains node_modules check if its one of the symlinked path we know of
102540             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
102541                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
102542                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
102543                     return undefined;
102544                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
102545                 if (isFile && result) {
102546                     if (!symlinkedFiles)
102547                         symlinkedFiles = ts.createMap();
102548                     // Store the real path for the file'
102549                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
102550                     symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
102551                 }
102552                 return result;
102553             }) || false;
102554         }
102555     }
102556     /*@internal*/
102557     function handleNoEmitOptions(program, sourceFile, cancellationToken) {
102558         var options = program.getCompilerOptions();
102559         if (options.noEmit) {
102560             return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
102561         }
102562         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
102563         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
102564         // get any preEmit diagnostics, not just the ones
102565         if (!options.noEmitOnError)
102566             return undefined;
102567         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
102568         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
102569             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
102570         }
102571         return diagnostics.length > 0 ?
102572             { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
102573             undefined;
102574     }
102575     ts.handleNoEmitOptions = handleNoEmitOptions;
102576     /* @internal */
102577     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
102578         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
102579         return {
102580             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
102581             readDirectory: function (root, extensions, excludes, includes, depth) {
102582                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
102583                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
102584             },
102585             readFile: function (f) { return directoryStructureHost.readFile(f); },
102586             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
102587             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
102588             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
102589             trace: host.trace ? function (s) { return host.trace(s); } : undefined
102590         };
102591     }
102592     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
102593     /* @internal */
102594     function createPrependNodes(projectReferences, getCommandLine, readFile) {
102595         if (!projectReferences)
102596             return ts.emptyArray;
102597         var nodes;
102598         for (var i = 0; i < projectReferences.length; i++) {
102599             var ref = projectReferences[i];
102600             var resolvedRefOpts = getCommandLine(ref, i);
102601             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
102602                 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
102603                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
102604                 if (!out)
102605                     continue;
102606                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
102607                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
102608                 (nodes || (nodes = [])).push(node);
102609             }
102610         }
102611         return nodes || ts.emptyArray;
102612     }
102613     ts.createPrependNodes = createPrependNodes;
102614     function resolveProjectReferencePath(hostOrRef, ref) {
102615         var passedInRef = ref ? ref : hostOrRef;
102616         return ts.resolveConfigFileProjectName(passedInRef.path);
102617     }
102618     ts.resolveProjectReferencePath = resolveProjectReferencePath;
102619     /* @internal */
102620     /**
102621      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
102622      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
102623      * This returns a diagnostic even if the module will be an untyped module.
102624      */
102625     function getResolutionDiagnostic(options, _a) {
102626         var extension = _a.extension;
102627         switch (extension) {
102628             case ".ts" /* Ts */:
102629             case ".d.ts" /* Dts */:
102630                 // These are always allowed.
102631                 return undefined;
102632             case ".tsx" /* Tsx */:
102633                 return needJsx();
102634             case ".jsx" /* Jsx */:
102635                 return needJsx() || needAllowJs();
102636             case ".js" /* Js */:
102637                 return needAllowJs();
102638             case ".json" /* Json */:
102639                 return needResolveJsonModule();
102640         }
102641         function needJsx() {
102642             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
102643         }
102644         function needAllowJs() {
102645             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;
102646         }
102647         function needResolveJsonModule() {
102648             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
102649         }
102650     }
102651     ts.getResolutionDiagnostic = getResolutionDiagnostic;
102652     function getModuleNames(_a) {
102653         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
102654         var res = imports.map(function (i) { return i.text; });
102655         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
102656             var aug = moduleAugmentations_1[_i];
102657             if (aug.kind === 10 /* StringLiteral */) {
102658                 res.push(aug.text);
102659             }
102660             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
102661         }
102662         return res;
102663     }
102664 })(ts || (ts = {}));
102665 /*@internal*/
102666 var ts;
102667 (function (ts) {
102668     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
102669         var outputFiles = [];
102670         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
102671         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
102672         function writeFile(fileName, text, writeByteOrderMark) {
102673             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
102674         }
102675     }
102676     ts.getFileEmitOutput = getFileEmitOutput;
102677     var BuilderState;
102678     (function (BuilderState) {
102679         /**
102680          * Get the referencedFile from the imported module symbol
102681          */
102682         function getReferencedFileFromImportedModuleSymbol(symbol) {
102683             if (symbol.declarations && symbol.declarations[0]) {
102684                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
102685                 return declarationSourceFile && declarationSourceFile.resolvedPath;
102686             }
102687         }
102688         /**
102689          * Get the referencedFile from the import name node from file
102690          */
102691         function getReferencedFileFromImportLiteral(checker, importName) {
102692             var symbol = checker.getSymbolAtLocation(importName);
102693             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
102694         }
102695         /**
102696          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
102697          */
102698         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
102699             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
102700         }
102701         /**
102702          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
102703          */
102704         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
102705             var referencedFiles;
102706             // We need to use a set here since the code can contain the same import twice,
102707             // but that will only be one dependency.
102708             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
102709             if (sourceFile.imports && sourceFile.imports.length > 0) {
102710                 var checker = program.getTypeChecker();
102711                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
102712                     var importName = _a[_i];
102713                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
102714                     if (declarationSourceFilePath) {
102715                         addReferencedFile(declarationSourceFilePath);
102716                     }
102717                 }
102718             }
102719             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
102720             // Handle triple slash references
102721             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
102722                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
102723                     var referencedFile = _c[_b];
102724                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
102725                     addReferencedFile(referencedPath);
102726                 }
102727             }
102728             // Handle type reference directives
102729             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
102730                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
102731                     if (!resolvedTypeReferenceDirective) {
102732                         return;
102733                     }
102734                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
102735                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
102736                     addReferencedFile(typeFilePath);
102737                 });
102738             }
102739             // Add module augmentation as references
102740             if (sourceFile.moduleAugmentations.length) {
102741                 var checker = program.getTypeChecker();
102742                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
102743                     var moduleName = _e[_d];
102744                     if (!ts.isStringLiteral(moduleName)) {
102745                         continue;
102746                     }
102747                     var symbol = checker.getSymbolAtLocation(moduleName);
102748                     if (!symbol) {
102749                         continue;
102750                     }
102751                     // Add any file other than our own as reference
102752                     addReferenceFromAmbientModule(symbol);
102753                 }
102754             }
102755             // From ambient modules
102756             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
102757                 var ambientModule = _g[_f];
102758                 if (ambientModule.declarations.length > 1) {
102759                     addReferenceFromAmbientModule(ambientModule);
102760                 }
102761             }
102762             return referencedFiles;
102763             function addReferenceFromAmbientModule(symbol) {
102764                 // Add any file other than our own as reference
102765                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
102766                     var declaration = _a[_i];
102767                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
102768                     if (declarationSourceFile &&
102769                         declarationSourceFile !== sourceFile) {
102770                         addReferencedFile(declarationSourceFile.resolvedPath);
102771                     }
102772                 }
102773             }
102774             function addReferencedFile(referencedPath) {
102775                 if (!referencedFiles) {
102776                     referencedFiles = ts.createMap();
102777                 }
102778                 referencedFiles.set(referencedPath, true);
102779             }
102780         }
102781         /**
102782          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
102783          */
102784         function canReuseOldState(newReferencedMap, oldState) {
102785             return oldState && !oldState.referencedMap === !newReferencedMap;
102786         }
102787         BuilderState.canReuseOldState = canReuseOldState;
102788         /**
102789          * Creates the state of file references and signature for the new program from oldState if it is safe
102790          */
102791         function create(newProgram, getCanonicalFileName, oldState) {
102792             var fileInfos = ts.createMap();
102793             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
102794             var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
102795             var hasCalledUpdateShapeSignature = ts.createMap();
102796             var useOldState = canReuseOldState(referencedMap, oldState);
102797             // Create the reference map, and set the file infos
102798             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
102799                 var sourceFile = _a[_i];
102800                 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
102801                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
102802                 if (referencedMap) {
102803                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
102804                     if (newReferences) {
102805                         referencedMap.set(sourceFile.resolvedPath, newReferences);
102806                     }
102807                     // Copy old visible to outside files map
102808                     if (useOldState) {
102809                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
102810                         if (exportedModules) {
102811                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
102812                         }
102813                     }
102814                 }
102815                 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
102816             }
102817             return {
102818                 fileInfos: fileInfos,
102819                 referencedMap: referencedMap,
102820                 exportedModulesMap: exportedModulesMap,
102821                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
102822             };
102823         }
102824         BuilderState.create = create;
102825         /**
102826          * Releases needed properties
102827          */
102828         function releaseCache(state) {
102829             state.allFilesExcludingDefaultLibraryFile = undefined;
102830             state.allFileNames = undefined;
102831         }
102832         BuilderState.releaseCache = releaseCache;
102833         /**
102834          * Creates a clone of the state
102835          */
102836         function clone(state) {
102837             var fileInfos = ts.createMap();
102838             state.fileInfos.forEach(function (value, key) {
102839                 fileInfos.set(key, __assign({}, value));
102840             });
102841             // Dont need to backup allFiles info since its cache anyway
102842             return {
102843                 fileInfos: fileInfos,
102844                 referencedMap: cloneMapOrUndefined(state.referencedMap),
102845                 exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
102846                 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
102847             };
102848         }
102849         BuilderState.clone = clone;
102850         /**
102851          * Gets the files affected by the path from the program
102852          */
102853         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
102854             // Since the operation could be cancelled, the signatures are always stored in the cache
102855             // They will be committed once it is safe to use them
102856             // eg when calling this api from tsserver, if there is no cancellation of the operation
102857             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
102858             var signatureCache = cacheToUpdateSignature || ts.createMap();
102859             var sourceFile = programOfThisState.getSourceFileByPath(path);
102860             if (!sourceFile) {
102861                 return ts.emptyArray;
102862             }
102863             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
102864                 return [sourceFile];
102865             }
102866             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
102867             if (!cacheToUpdateSignature) {
102868                 // Commit all the signatures in the signature cache
102869                 updateSignaturesFromCache(state, signatureCache);
102870             }
102871             return result;
102872         }
102873         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
102874         /**
102875          * Updates the signatures from the cache into state's fileinfo signatures
102876          * This should be called whenever it is safe to commit the state of the builder
102877          */
102878         function updateSignaturesFromCache(state, signatureCache) {
102879             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
102880         }
102881         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
102882         function updateSignatureOfFile(state, signature, path) {
102883             state.fileInfos.get(path).signature = signature;
102884             state.hasCalledUpdateShapeSignature.set(path, true);
102885         }
102886         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
102887         /**
102888          * Returns if the shape of the signature has changed since last emit
102889          */
102890         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102891             ts.Debug.assert(!!sourceFile);
102892             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
102893             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
102894             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
102895                 return false;
102896             }
102897             var info = state.fileInfos.get(sourceFile.resolvedPath);
102898             if (!info)
102899                 return ts.Debug.fail();
102900             var prevSignature = info.signature;
102901             var latestSignature;
102902             if (sourceFile.isDeclarationFile) {
102903                 latestSignature = sourceFile.version;
102904                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
102905                     // All the references in this file are exported
102906                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
102907                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
102908                 }
102909             }
102910             else {
102911                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
102912                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
102913                 /*customTransformers*/ undefined, 
102914                 /*forceDtsEmit*/ true);
102915                 var firstDts_1 = emitOutput_1.outputFiles &&
102916                     programOfThisState.getCompilerOptions().declarationMap ?
102917                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
102918                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
102919                 if (firstDts_1) {
102920                     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; })); });
102921                     latestSignature = computeHash(firstDts_1.text);
102922                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
102923                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
102924                     }
102925                 }
102926                 else {
102927                     latestSignature = prevSignature; // TODO: GH#18217
102928                 }
102929             }
102930             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
102931             return !prevSignature || latestSignature !== prevSignature;
102932         }
102933         BuilderState.updateShapeSignature = updateShapeSignature;
102934         /**
102935          * Coverts the declaration emit result into exported modules map
102936          */
102937         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
102938             if (!exportedModulesFromDeclarationEmit) {
102939                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
102940                 return;
102941             }
102942             var exportedModules;
102943             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
102944             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
102945             function addExportedModule(exportedModulePath) {
102946                 if (exportedModulePath) {
102947                     if (!exportedModules) {
102948                         exportedModules = ts.createMap();
102949                     }
102950                     exportedModules.set(exportedModulePath, true);
102951                 }
102952             }
102953         }
102954         /**
102955          * Updates the exported modules from cache into state's exported modules map
102956          * This should be called whenever it is safe to commit the state of the builder
102957          */
102958         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
102959             if (exportedModulesMapCache) {
102960                 ts.Debug.assert(!!state.exportedModulesMap);
102961                 exportedModulesMapCache.forEach(function (exportedModules, path) {
102962                     if (exportedModules) {
102963                         state.exportedModulesMap.set(path, exportedModules);
102964                     }
102965                     else {
102966                         state.exportedModulesMap.delete(path);
102967                     }
102968                 });
102969             }
102970         }
102971         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
102972         /**
102973          * Get all the dependencies of the sourceFile
102974          */
102975         function getAllDependencies(state, programOfThisState, sourceFile) {
102976             var compilerOptions = programOfThisState.getCompilerOptions();
102977             // With --out or --outFile all outputs go into single file, all files depend on each other
102978             if (compilerOptions.outFile || compilerOptions.out) {
102979                 return getAllFileNames(state, programOfThisState);
102980             }
102981             // If this is non module emit, or its a global file, it depends on all the source files
102982             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
102983                 return getAllFileNames(state, programOfThisState);
102984             }
102985             // Get the references, traversing deep from the referenceMap
102986             var seenMap = ts.createMap();
102987             var queue = [sourceFile.resolvedPath];
102988             while (queue.length) {
102989                 var path = queue.pop();
102990                 if (!seenMap.has(path)) {
102991                     seenMap.set(path, true);
102992                     var references = state.referencedMap.get(path);
102993                     if (references) {
102994                         var iterator = references.keys();
102995                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
102996                             queue.push(iterResult.value);
102997                         }
102998                     }
102999                 }
103000             }
103001             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
103002                 var file = programOfThisState.getSourceFileByPath(path);
103003                 return file ? file.fileName : path;
103004             }));
103005         }
103006         BuilderState.getAllDependencies = getAllDependencies;
103007         /**
103008          * Gets the names of all files from the program
103009          */
103010         function getAllFileNames(state, programOfThisState) {
103011             if (!state.allFileNames) {
103012                 var sourceFiles = programOfThisState.getSourceFiles();
103013                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
103014             }
103015             return state.allFileNames;
103016         }
103017         /**
103018          * Gets the files referenced by the the file path
103019          */
103020         function getReferencedByPaths(state, referencedFilePath) {
103021             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
103022                 var filePath = _a[0], referencesInFile = _a[1];
103023                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
103024             }));
103025         }
103026         BuilderState.getReferencedByPaths = getReferencedByPaths;
103027         /**
103028          * For script files that contains only ambient external modules, although they are not actually external module files,
103029          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
103030          * there are no point to rebuild all script files if these special files have changed. However, if any statement
103031          * in the file is not ambient external module, we treat it as a regular script file.
103032          */
103033         function containsOnlyAmbientModules(sourceFile) {
103034             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
103035                 var statement = _a[_i];
103036                 if (!ts.isModuleWithStringLiteralName(statement)) {
103037                     return false;
103038                 }
103039             }
103040             return true;
103041         }
103042         /**
103043          * Return true if file contains anything that augments to global scope we need to build them as if
103044          * they are global files as well as module
103045          */
103046         function containsGlobalScopeAugmentation(sourceFile) {
103047             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
103048         }
103049         /**
103050          * Return true if the file will invalidate all files because it affectes global scope
103051          */
103052         function isFileAffectingGlobalScope(sourceFile) {
103053             return containsGlobalScopeAugmentation(sourceFile) ||
103054                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
103055         }
103056         /**
103057          * Gets all files of the program excluding the default library file
103058          */
103059         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
103060             // Use cached result
103061             if (state.allFilesExcludingDefaultLibraryFile) {
103062                 return state.allFilesExcludingDefaultLibraryFile;
103063             }
103064             var result;
103065             if (firstSourceFile)
103066                 addSourceFile(firstSourceFile);
103067             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
103068                 var sourceFile = _a[_i];
103069                 if (sourceFile !== firstSourceFile) {
103070                     addSourceFile(sourceFile);
103071                 }
103072             }
103073             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
103074             return state.allFilesExcludingDefaultLibraryFile;
103075             function addSourceFile(sourceFile) {
103076                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
103077                     (result || (result = [])).push(sourceFile);
103078                 }
103079             }
103080         }
103081         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
103082         /**
103083          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
103084          */
103085         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
103086             var compilerOptions = programOfThisState.getCompilerOptions();
103087             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
103088             // so returning the file itself is good enough.
103089             if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
103090                 return [sourceFileWithUpdatedShape];
103091             }
103092             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
103093         }
103094         /**
103095          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
103096          */
103097         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
103098             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
103099                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
103100             }
103101             var compilerOptions = programOfThisState.getCompilerOptions();
103102             if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
103103                 return [sourceFileWithUpdatedShape];
103104             }
103105             // Now we need to if each file in the referencedBy list has a shape change as well.
103106             // Because if so, its own referencedBy files need to be saved as well to make the
103107             // emitting result consistent with files on disk.
103108             var seenFileNamesMap = ts.createMap();
103109             // Start with the paths this file was referenced by
103110             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
103111             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
103112             while (queue.length > 0) {
103113                 var currentPath = queue.pop();
103114                 if (!seenFileNamesMap.has(currentPath)) {
103115                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
103116                     seenFileNamesMap.set(currentPath, currentSourceFile);
103117                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
103118                         queue.push.apply(// TODO: GH#18217
103119                         queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
103120                     }
103121                 }
103122             }
103123             // Return array of values that needs emit
103124             // Return array of values that needs emit
103125             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
103126         }
103127     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
103128     function cloneMapOrUndefined(map) {
103129         return map ? ts.cloneMap(map) : undefined;
103130     }
103131     ts.cloneMapOrUndefined = cloneMapOrUndefined;
103132 })(ts || (ts = {}));
103133 /*@internal*/
103134 var ts;
103135 (function (ts) {
103136     var BuilderFileEmit;
103137     (function (BuilderFileEmit) {
103138         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
103139         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
103140     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
103141     function hasSameKeys(map1, map2) {
103142         // Has same size and every key is present in both maps
103143         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
103144     }
103145     /**
103146      * Create the state so that we can iterate on changedFiles/affected files
103147      */
103148     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
103149         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
103150         state.program = newProgram;
103151         var compilerOptions = newProgram.getCompilerOptions();
103152         state.compilerOptions = compilerOptions;
103153         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
103154         if (!compilerOptions.outFile && !compilerOptions.out) {
103155             state.semanticDiagnosticsPerFile = ts.createMap();
103156         }
103157         state.changedFilesSet = ts.createMap();
103158         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
103159         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
103160         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
103161             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
103162         if (useOldState) {
103163             // Verify the sanity of old state
103164             if (!oldState.currentChangedFilePath) {
103165                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
103166                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
103167             }
103168             var changedFilesSet = oldState.changedFilesSet;
103169             if (canCopySemanticDiagnostics) {
103170                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
103171             }
103172             // Copy old state's changed files set
103173             if (changedFilesSet) {
103174                 ts.copyEntries(changedFilesSet, state.changedFilesSet);
103175             }
103176             if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
103177                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
103178                 state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
103179                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
103180                 state.seenAffectedFiles = ts.createMap();
103181             }
103182         }
103183         // Update changed files and copy semantic diagnostics if we can
103184         var referencedMap = state.referencedMap;
103185         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
103186         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
103187         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
103188         state.fileInfos.forEach(function (info, sourceFilePath) {
103189             var oldInfo;
103190             var newReferences;
103191             // if not using old state, every file is changed
103192             if (!useOldState ||
103193                 // File wasnt present in old state
103194                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
103195                 // versions dont match
103196                 oldInfo.version !== info.version ||
103197                 // Referenced files changed
103198                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
103199                 // Referenced file was deleted in the new program
103200                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
103201                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
103202                 state.changedFilesSet.set(sourceFilePath, true);
103203             }
103204             else if (canCopySemanticDiagnostics) {
103205                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
103206                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
103207                     return;
103208                 }
103209                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
103210                     return;
103211                 }
103212                 // Unchanged file copy diagnostics
103213                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
103214                 if (diagnostics) {
103215                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
103216                     if (!state.semanticDiagnosticsFromOldState) {
103217                         state.semanticDiagnosticsFromOldState = ts.createMap();
103218                     }
103219                     state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
103220                 }
103221             }
103222         });
103223         // If the global file is removed, add all files as changed
103224         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
103225             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
103226                 .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); });
103227         }
103228         else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
103229             // Add all files to affectedFilesPendingEmit since emit changed
103230             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
103231             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
103232             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103233         }
103234         state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
103235         return state;
103236     }
103237     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
103238         if (!diagnostics.length)
103239             return ts.emptyArray;
103240         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
103241         return diagnostics.map(function (diagnostic) {
103242             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
103243             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103244             result.source = diagnostic.source;
103245             var relatedInformation = diagnostic.relatedInformation;
103246             result.relatedInformation = relatedInformation ?
103247                 relatedInformation.length ?
103248                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
103249                     ts.emptyArray :
103250                 undefined;
103251             return result;
103252         });
103253         function toPath(path) {
103254             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103255         }
103256     }
103257     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
103258         var file = diagnostic.file;
103259         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
103260     }
103261     /**
103262      * Releases program and other related not needed properties
103263      */
103264     function releaseCache(state) {
103265         ts.BuilderState.releaseCache(state);
103266         state.program = undefined;
103267     }
103268     /**
103269      * Creates a clone of the state
103270      */
103271     function cloneBuilderProgramState(state) {
103272         var newState = ts.BuilderState.clone(state);
103273         newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
103274         newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
103275         newState.affectedFiles = state.affectedFiles;
103276         newState.affectedFilesIndex = state.affectedFilesIndex;
103277         newState.currentChangedFilePath = state.currentChangedFilePath;
103278         newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
103279         newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
103280         newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
103281         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
103282         newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
103283         newState.program = state.program;
103284         newState.compilerOptions = state.compilerOptions;
103285         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
103286         newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
103287         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
103288         newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
103289         newState.programEmitComplete = state.programEmitComplete;
103290         return newState;
103291     }
103292     /**
103293      * Verifies that source file is ok to be used in calls that arent handled by next
103294      */
103295     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
103296         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
103297     }
103298     /**
103299      * This function returns the next affected file to be processed.
103300      * Note that until doneAffected is called it would keep reporting same result
103301      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
103302      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
103303      */
103304     function getNextAffectedFile(state, cancellationToken, computeHash) {
103305         while (true) {
103306             var affectedFiles = state.affectedFiles;
103307             if (affectedFiles) {
103308                 var seenAffectedFiles = state.seenAffectedFiles;
103309                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
103310                 while (affectedFilesIndex < affectedFiles.length) {
103311                     var affectedFile = affectedFiles[affectedFilesIndex];
103312                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
103313                         // Set the next affected file as seen and remove the cached semantic diagnostics
103314                         state.affectedFilesIndex = affectedFilesIndex;
103315                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
103316                         return affectedFile;
103317                     }
103318                     affectedFilesIndex++;
103319                 }
103320                 // Remove the changed file from the change set
103321                 state.changedFilesSet.delete(state.currentChangedFilePath);
103322                 state.currentChangedFilePath = undefined;
103323                 // Commit the changes in file signature
103324                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
103325                 state.currentAffectedFilesSignatures.clear();
103326                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
103327                 state.affectedFiles = undefined;
103328             }
103329             // Get next changed file
103330             var nextKey = state.changedFilesSet.keys().next();
103331             if (nextKey.done) {
103332                 // Done
103333                 return undefined;
103334             }
103335             // With --out or --outFile all outputs go into single file
103336             // so operations are performed directly on program, return program
103337             var program = ts.Debug.checkDefined(state.program);
103338             var compilerOptions = program.getCompilerOptions();
103339             if (compilerOptions.outFile || compilerOptions.out) {
103340                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103341                 return program;
103342             }
103343             // Get next batch of affected files
103344             state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
103345             if (state.exportedModulesMap) {
103346                 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
103347             }
103348             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
103349             state.currentChangedFilePath = nextKey.value;
103350             state.affectedFilesIndex = 0;
103351             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103352         }
103353     }
103354     /**
103355      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
103356      */
103357     function getNextAffectedFilePendingEmit(state) {
103358         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
103359         if (affectedFilesPendingEmit) {
103360             var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
103361             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
103362                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
103363                 if (affectedFile) {
103364                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
103365                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
103366                     if (seenKind === undefined || seenKind < emitKind) {
103367                         // emit this file
103368                         state.affectedFilesPendingEmitIndex = i;
103369                         return { affectedFile: affectedFile, emitKind: emitKind };
103370                     }
103371                 }
103372             }
103373             state.affectedFilesPendingEmit = undefined;
103374             state.affectedFilesPendingEmitKind = undefined;
103375             state.affectedFilesPendingEmitIndex = undefined;
103376         }
103377         return undefined;
103378     }
103379     /**
103380      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
103381      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
103382      */
103383     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
103384         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
103385         // If affected files is everything except default library, then nothing more to do
103386         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
103387             if (!state.cleanedDiagnosticsOfLibFiles) {
103388                 state.cleanedDiagnosticsOfLibFiles = true;
103389                 var program_1 = ts.Debug.checkDefined(state.program);
103390                 var options_2 = program_1.getCompilerOptions();
103391                 ts.forEach(program_1.getSourceFiles(), function (f) {
103392                     return program_1.isSourceFileDefaultLibrary(f) &&
103393                         !ts.skipTypeChecking(f, options_2, program_1) &&
103394                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
103395                 });
103396             }
103397             return;
103398         }
103399         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
103400             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
103401         }
103402     }
103403     /**
103404      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
103405      * Also we need to make sure signature is updated for these files
103406      */
103407     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
103408         removeSemanticDiagnosticsOf(state, path);
103409         if (!state.changedFilesSet.has(path)) {
103410             var program = ts.Debug.checkDefined(state.program);
103411             var sourceFile = program.getSourceFileByPath(path);
103412             if (sourceFile) {
103413                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
103414                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
103415                 // This ensures that we dont later during incremental builds considering wrong signature.
103416                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
103417                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
103418                 // If not dts emit, nothing more to do
103419                 if (ts.getEmitDeclarations(state.compilerOptions)) {
103420                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
103421                 }
103422             }
103423         }
103424         return false;
103425     }
103426     /**
103427      * Removes semantic diagnostics for path and
103428      * returns true if there are no more semantic diagnostics from the old state
103429      */
103430     function removeSemanticDiagnosticsOf(state, path) {
103431         if (!state.semanticDiagnosticsFromOldState) {
103432             return true;
103433         }
103434         state.semanticDiagnosticsFromOldState.delete(path);
103435         state.semanticDiagnosticsPerFile.delete(path);
103436         return !state.semanticDiagnosticsFromOldState.size;
103437     }
103438     function isChangedSignagure(state, path) {
103439         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
103440         var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
103441         return newSignature !== oldSignagure;
103442     }
103443     /**
103444      * Iterate on referencing modules that export entities from affected file
103445      */
103446     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
103447         // If there was change in signature (dts output) for the changed file,
103448         // then only we need to handle pending file emit
103449         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
103450             return;
103451         }
103452         if (!isChangedSignagure(state, affectedFile.resolvedPath))
103453             return;
103454         // Since isolated modules dont change js files, files affected by change in signature is itself
103455         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
103456         if (state.compilerOptions.isolatedModules) {
103457             var seenFileNamesMap = ts.createMap();
103458             seenFileNamesMap.set(affectedFile.resolvedPath, true);
103459             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
103460             while (queue.length > 0) {
103461                 var currentPath = queue.pop();
103462                 if (!seenFileNamesMap.has(currentPath)) {
103463                     seenFileNamesMap.set(currentPath, true);
103464                     var result = fn(state, currentPath);
103465                     if (result && isChangedSignagure(state, currentPath)) {
103466                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
103467                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
103468                     }
103469                 }
103470             }
103471         }
103472         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103473         var seenFileAndExportsOfFile = ts.createMap();
103474         // Go through exported modules from cache first
103475         // If exported modules has path, all files referencing file exported from are affected
103476         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103477             return exportedModules &&
103478                 exportedModules.has(affectedFile.resolvedPath) &&
103479                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103480         })) {
103481             return;
103482         }
103483         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103484         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103485             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103486                 exportedModules.has(affectedFile.resolvedPath) &&
103487                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103488         });
103489     }
103490     /**
103491      * Iterate on files referencing referencedPath
103492      */
103493     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
103494         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
103495             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
103496         });
103497     }
103498     /**
103499      * fn on file and iterate on anything that exports this file
103500      */
103501     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
103502         if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
103503             return false;
103504         }
103505         if (fn(state, filePath)) {
103506             // If there are no more diagnostics from old cache, done
103507             return true;
103508         }
103509         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103510         // Go through exported modules from cache first
103511         // If exported modules has path, all files referencing file exported from are affected
103512         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103513             return exportedModules &&
103514                 exportedModules.has(filePath) &&
103515                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103516         })) {
103517             return true;
103518         }
103519         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103520         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103521             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103522                 exportedModules.has(filePath) &&
103523                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103524         })) {
103525             return true;
103526         }
103527         // Remove diagnostics of files that import this file (without going to exports of referencing files)
103528         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
103529             return referencesInFile.has(filePath) &&
103530                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
103531                 fn(state, referencingFilePath);
103532         } // Dont add to seen since this is not yet done with the export removal
103533         );
103534     }
103535     /**
103536      * This is called after completing operation on the next affected file.
103537      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
103538      */
103539     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103540         if (isBuildInfoEmit) {
103541             state.emittedBuildInfo = true;
103542         }
103543         else if (affected === state.program) {
103544             state.changedFilesSet.clear();
103545             state.programEmitComplete = true;
103546         }
103547         else {
103548             state.seenAffectedFiles.set(affected.resolvedPath, true);
103549             if (emitKind !== undefined) {
103550                 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
103551             }
103552             if (isPendingEmit) {
103553                 state.affectedFilesPendingEmitIndex++;
103554             }
103555             else {
103556                 state.affectedFilesIndex++;
103557             }
103558         }
103559     }
103560     /**
103561      * Returns the result with affected file
103562      */
103563     function toAffectedFileResult(state, result, affected) {
103564         doneWithAffectedFile(state, affected);
103565         return { result: result, affected: affected };
103566     }
103567     /**
103568      * Returns the result with affected file
103569      */
103570     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103571         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
103572         return { result: result, affected: affected };
103573     }
103574     /**
103575      * Gets semantic diagnostics for the file which are
103576      * bindAndCheckDiagnostics (from cache) and program diagnostics
103577      */
103578     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103579         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
103580     }
103581     /**
103582      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
103583      * 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
103584      */
103585     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103586         var path = sourceFile.resolvedPath;
103587         if (state.semanticDiagnosticsPerFile) {
103588             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
103589             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
103590             if (cachedDiagnostics) {
103591                 return cachedDiagnostics;
103592             }
103593         }
103594         // Diagnostics werent cached, get them from program, and cache the result
103595         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
103596         if (state.semanticDiagnosticsPerFile) {
103597             state.semanticDiagnosticsPerFile.set(path, diagnostics);
103598         }
103599         return diagnostics;
103600     }
103601     /**
103602      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
103603      */
103604     function getProgramBuildInfo(state, getCanonicalFileName) {
103605         if (state.compilerOptions.outFile || state.compilerOptions.out)
103606             return undefined;
103607         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
103608         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
103609         var fileInfos = {};
103610         state.fileInfos.forEach(function (value, key) {
103611             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
103612             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
103613         });
103614         var result = {
103615             fileInfos: fileInfos,
103616             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
103617         };
103618         if (state.referencedMap) {
103619             var referencedMap = {};
103620             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
103621                 var key = _a[_i];
103622                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103623             }
103624             result.referencedMap = referencedMap;
103625         }
103626         if (state.exportedModulesMap) {
103627             var exportedModulesMap = {};
103628             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
103629                 var key = _c[_b];
103630                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
103631                 // Not in temporary cache, use existing value
103632                 if (newValue === undefined)
103633                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103634                 // Value in cache and has updated value map, use that
103635                 else if (newValue)
103636                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103637             }
103638             result.exportedModulesMap = exportedModulesMap;
103639         }
103640         if (state.semanticDiagnosticsPerFile) {
103641             var semanticDiagnosticsPerFile = [];
103642             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
103643                 var key = _e[_d];
103644                 var value = state.semanticDiagnosticsPerFile.get(key);
103645                 semanticDiagnosticsPerFile.push(value.length ?
103646                     [
103647                         relativeToBuildInfo(key),
103648                         state.hasReusableDiagnostic ?
103649                             value :
103650                             convertToReusableDiagnostics(value, relativeToBuildInfo)
103651                     ] :
103652                     relativeToBuildInfo(key));
103653             }
103654             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
103655         }
103656         return result;
103657         function relativeToBuildInfoEnsuringAbsolutePath(path) {
103658             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
103659         }
103660         function relativeToBuildInfo(path) {
103661             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
103662         }
103663     }
103664     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
103665         var result = {};
103666         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
103667         for (var name in options) {
103668             if (ts.hasProperty(options, name)) {
103669                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
103670             }
103671         }
103672         if (result.configFilePath) {
103673             result.configFilePath = relativeToBuildInfo(result.configFilePath);
103674         }
103675         return result;
103676     }
103677     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
103678         if (option) {
103679             if (option.type === "list") {
103680                 var values = value;
103681                 if (option.element.isFilePath && values.length) {
103682                     return values.map(relativeToBuildInfo);
103683                 }
103684             }
103685             else if (option.isFilePath) {
103686                 return relativeToBuildInfo(value);
103687             }
103688         }
103689         return value;
103690     }
103691     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
103692         ts.Debug.assert(!!diagnostics.length);
103693         return diagnostics.map(function (diagnostic) {
103694             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
103695             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103696             result.source = diagnostic.source;
103697             var relatedInformation = diagnostic.relatedInformation;
103698             result.relatedInformation = relatedInformation ?
103699                 relatedInformation.length ?
103700                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
103701                     ts.emptyArray :
103702                 undefined;
103703             return result;
103704         });
103705     }
103706     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
103707         var file = diagnostic.file;
103708         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
103709     }
103710     var BuilderProgramKind;
103711     (function (BuilderProgramKind) {
103712         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
103713         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
103714     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
103715     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103716         var host;
103717         var newProgram;
103718         var oldProgram;
103719         if (newProgramOrRootNames === undefined) {
103720             ts.Debug.assert(hostOrOptions === undefined);
103721             host = oldProgramOrHost;
103722             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103723             ts.Debug.assert(!!oldProgram);
103724             newProgram = oldProgram.getProgram();
103725         }
103726         else if (ts.isArray(newProgramOrRootNames)) {
103727             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103728             newProgram = ts.createProgram({
103729                 rootNames: newProgramOrRootNames,
103730                 options: hostOrOptions,
103731                 host: oldProgramOrHost,
103732                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
103733                 configFileParsingDiagnostics: configFileParsingDiagnostics,
103734                 projectReferences: projectReferences
103735             });
103736             host = oldProgramOrHost;
103737         }
103738         else {
103739             newProgram = newProgramOrRootNames;
103740             host = hostOrOptions;
103741             oldProgram = oldProgramOrHost;
103742             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
103743         }
103744         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
103745     }
103746     ts.getBuilderCreationParameters = getBuilderCreationParameters;
103747     function createBuilderProgram(kind, _a) {
103748         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103749         // Return same program if underlying program doesnt change
103750         var oldState = oldProgram && oldProgram.getState();
103751         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
103752             newProgram = undefined; // TODO: GH#18217
103753             oldState = undefined;
103754             return oldProgram;
103755         }
103756         /**
103757          * Create the canonical file name for identity
103758          */
103759         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103760         /**
103761          * Computing hash to for signature verification
103762          */
103763         var computeHash = host.createHash || ts.generateDjb2Hash;
103764         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
103765         var backupState;
103766         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
103767         // To ensure that we arent storing any references to old program or new program without state
103768         newProgram = undefined; // TODO: GH#18217
103769         oldProgram = undefined;
103770         oldState = undefined;
103771         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
103772         builderProgram.getState = function () { return state; };
103773         builderProgram.backupState = function () {
103774             ts.Debug.assert(backupState === undefined);
103775             backupState = cloneBuilderProgramState(state);
103776         };
103777         builderProgram.restoreState = function () {
103778             state = ts.Debug.checkDefined(backupState);
103779             backupState = undefined;
103780         };
103781         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
103782         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
103783         builderProgram.emit = emit;
103784         builderProgram.releaseProgram = function () {
103785             releaseCache(state);
103786             backupState = undefined;
103787         };
103788         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
103789             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103790         }
103791         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103792             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103793             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
103794         }
103795         else {
103796             ts.notImplemented();
103797         }
103798         return builderProgram;
103799         /**
103800          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
103801          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103802          * in that order would be used to write the files
103803          */
103804         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103805             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103806             var emitKind = 1 /* Full */;
103807             var isPendingEmitFile = false;
103808             if (!affected) {
103809                 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
103810                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
103811                     if (!pendingAffectedFile) {
103812                         if (state.emittedBuildInfo) {
103813                             return undefined;
103814                         }
103815                         var affected_1 = ts.Debug.checkDefined(state.program);
103816                         return toAffectedFileEmitResult(state, 
103817                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103818                         // Otherwise just affected file
103819                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
103820                         /*isPendingEmitFile*/ false, 
103821                         /*isBuildInfoEmit*/ true);
103822                     }
103823                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
103824                     isPendingEmitFile = true;
103825                 }
103826                 else {
103827                     var program = ts.Debug.checkDefined(state.program);
103828                     if (state.programEmitComplete)
103829                         return undefined;
103830                     affected = program;
103831                 }
103832             }
103833             return toAffectedFileEmitResult(state, 
103834             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103835             // Otherwise just affected file
103836             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);
103837         }
103838         /**
103839          * Emits the JavaScript and declaration files.
103840          * When targetSource file is specified, emits the files corresponding to that source file,
103841          * otherwise for the whole program.
103842          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
103843          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
103844          * it will only emit all the affected files instead of whole program
103845          *
103846          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103847          * in that order would be used to write the files
103848          */
103849         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103850             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103851                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
103852                 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
103853                 if (result)
103854                     return result;
103855                 if (!targetSourceFile) {
103856                     // Emit and report any errors we ran into.
103857                     var sourceMaps = [];
103858                     var emitSkipped = false;
103859                     var diagnostics = void 0;
103860                     var emittedFiles = [];
103861                     var affectedEmitResult = void 0;
103862                     while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
103863                         emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
103864                         diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
103865                         emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
103866                         sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
103867                     }
103868                     return {
103869                         emitSkipped: emitSkipped,
103870                         diagnostics: diagnostics || ts.emptyArray,
103871                         emittedFiles: emittedFiles,
103872                         sourceMaps: sourceMaps
103873                     };
103874                 }
103875             }
103876             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
103877         }
103878         /**
103879          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
103880          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
103881          */
103882         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
103883             while (true) {
103884                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103885                 if (!affected) {
103886                     // Done
103887                     return undefined;
103888                 }
103889                 else if (affected === state.program) {
103890                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
103891                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
103892                 }
103893                 // Add file to affected file pending emit to handle for later emit time
103894                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103895                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
103896                 }
103897                 // Get diagnostics for the affected file if its not ignored
103898                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
103899                     // Get next affected file
103900                     doneWithAffectedFile(state, affected);
103901                     continue;
103902                 }
103903                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
103904             }
103905         }
103906         /**
103907          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
103908          * The semantic diagnostics are cached and managed here
103909          * Note that it is assumed that when asked about semantic diagnostics through this API,
103910          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
103911          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
103912          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
103913          */
103914         function getSemanticDiagnostics(sourceFile, cancellationToken) {
103915             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
103916             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
103917             if (compilerOptions.outFile || compilerOptions.out) {
103918                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103919                 // We dont need to cache the diagnostics just return them from program
103920                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
103921             }
103922             if (sourceFile) {
103923                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
103924             }
103925             // When semantic builder asks for diagnostics of the whole program,
103926             // ensure that all the affected files are handled
103927             // eslint-disable-next-line no-empty
103928             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
103929             }
103930             var diagnostics;
103931             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
103932                 var sourceFile_1 = _a[_i];
103933                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
103934             }
103935             return diagnostics || ts.emptyArray;
103936         }
103937     }
103938     ts.createBuilderProgram = createBuilderProgram;
103939     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
103940         if (!state.affectedFilesPendingEmit)
103941             state.affectedFilesPendingEmit = [];
103942         if (!state.affectedFilesPendingEmitKind)
103943             state.affectedFilesPendingEmitKind = ts.createMap();
103944         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
103945         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
103946         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
103947         // affectedFilesPendingEmitIndex === undefined
103948         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
103949         //   so start from 0 as array would be affectedFilesPendingEmit
103950         // else, continue to iterate from existing index, the current set is appended to existing files
103951         if (state.affectedFilesPendingEmitIndex === undefined) {
103952             state.affectedFilesPendingEmitIndex = 0;
103953         }
103954     }
103955     function getMapOfReferencedSet(mapLike, toPath) {
103956         if (!mapLike)
103957             return undefined;
103958         var map = ts.createMap();
103959         // Copies keys/values from template. Note that for..in will not throw if
103960         // template is undefined, and instead will just exit the loop.
103961         for (var key in mapLike) {
103962             if (ts.hasProperty(mapLike, key)) {
103963                 map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
103964             }
103965         }
103966         return map;
103967     }
103968     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
103969         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
103970         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103971         var fileInfos = ts.createMap();
103972         for (var key in program.fileInfos) {
103973             if (ts.hasProperty(program.fileInfos, key)) {
103974                 fileInfos.set(toPath(key), program.fileInfos[key]);
103975             }
103976         }
103977         var state = {
103978             fileInfos: fileInfos,
103979             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
103980             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
103981             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
103982             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]; }),
103983             hasReusableDiagnostic: true
103984         };
103985         return {
103986             getState: function () { return state; },
103987             backupState: ts.noop,
103988             restoreState: ts.noop,
103989             getProgram: ts.notImplemented,
103990             getProgramOrUndefined: ts.returnUndefined,
103991             releaseProgram: ts.noop,
103992             getCompilerOptions: function () { return state.compilerOptions; },
103993             getSourceFile: ts.notImplemented,
103994             getSourceFiles: ts.notImplemented,
103995             getOptionsDiagnostics: ts.notImplemented,
103996             getGlobalDiagnostics: ts.notImplemented,
103997             getConfigFileParsingDiagnostics: ts.notImplemented,
103998             getSyntacticDiagnostics: ts.notImplemented,
103999             getDeclarationDiagnostics: ts.notImplemented,
104000             getSemanticDiagnostics: ts.notImplemented,
104001             emit: ts.notImplemented,
104002             getAllDependencies: ts.notImplemented,
104003             getCurrentDirectory: ts.notImplemented,
104004             emitNextAffectedFile: ts.notImplemented,
104005             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
104006             close: ts.noop,
104007         };
104008         function toPath(path) {
104009             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
104010         }
104011         function toAbsolutePath(path) {
104012             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
104013         }
104014     }
104015     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
104016     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
104017         return {
104018             getState: ts.notImplemented,
104019             backupState: ts.noop,
104020             restoreState: ts.noop,
104021             getProgram: getProgram,
104022             getProgramOrUndefined: function () { return state.program; },
104023             releaseProgram: function () { return state.program = undefined; },
104024             getCompilerOptions: function () { return state.compilerOptions; },
104025             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
104026             getSourceFiles: function () { return getProgram().getSourceFiles(); },
104027             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
104028             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
104029             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
104030             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
104031             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
104032             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
104033             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
104034             getAllDependencies: ts.notImplemented,
104035             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
104036             close: ts.noop,
104037         };
104038         function getProgram() {
104039             return ts.Debug.checkDefined(state.program);
104040         }
104041     }
104042     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
104043 })(ts || (ts = {}));
104044 var ts;
104045 (function (ts) {
104046     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
104047         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
104048     }
104049     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
104050     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
104051         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
104052     }
104053     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
104054     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
104055         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
104056         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
104057     }
104058     ts.createAbstractBuilder = createAbstractBuilder;
104059 })(ts || (ts = {}));
104060 /*@internal*/
104061 var ts;
104062 (function (ts) {
104063     function removeIgnoredPath(path) {
104064         // Consider whole staging folder as if node_modules changed.
104065         if (ts.endsWith(path, "/node_modules/.staging")) {
104066             return ts.removeSuffix(path, "/.staging");
104067         }
104068         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
104069             undefined :
104070             path;
104071     }
104072     ts.removeIgnoredPath = removeIgnoredPath;
104073     /**
104074      * Filter out paths like
104075      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
104076      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
104077      * @param dirPath
104078      */
104079     function canWatchDirectory(dirPath) {
104080         var rootLength = ts.getRootLength(dirPath);
104081         if (dirPath.length === rootLength) {
104082             // Ignore "/", "c:/"
104083             return false;
104084         }
104085         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
104086         if (nextDirectorySeparator === -1) {
104087             // ignore "/user", "c:/users" or "c:/folderAtRoot"
104088             return false;
104089         }
104090         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
104091         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
104092         if (isNonDirectorySeparatorRoot &&
104093             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
104094             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
104095             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
104096             if (nextDirectorySeparator === -1) {
104097                 // ignore "//vda1cs4850/c$/folderAtRoot"
104098                 return false;
104099             }
104100             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
104101         }
104102         if (isNonDirectorySeparatorRoot &&
104103             pathPartForUserCheck.search(/users\//i) !== 0) {
104104             // Paths like c:/folderAtRoot/subFolder are allowed
104105             return true;
104106         }
104107         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
104108             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
104109             if (searchIndex === 0) {
104110                 // Folder isnt at expected minimum levels
104111                 return false;
104112             }
104113         }
104114         return true;
104115     }
104116     ts.canWatchDirectory = canWatchDirectory;
104117     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
104118         var filesWithChangedSetOfUnresolvedImports;
104119         var filesWithInvalidatedResolutions;
104120         var filesWithInvalidatedNonRelativeUnresolvedImports;
104121         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
104122         var resolutionsWithFailedLookups = [];
104123         var resolvedFileToResolution = ts.createMultiMap();
104124         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
104125         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
104126         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
104127         // The key in the map is source file's path.
104128         // The values are Map of resolutions with key being name lookedup.
104129         var resolvedModuleNames = ts.createMap();
104130         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
104131         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
104132         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
104133         var resolvedTypeReferenceDirectives = ts.createMap();
104134         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
104135         /**
104136          * These are the extensions that failed lookup files will have by default,
104137          * any other extension of failed lookup will be store that path in custom failed lookup path
104138          * This helps in not having to comb through all resolutions when files are added/removed
104139          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
104140          */
104141         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
104142         var customFailedLookupPaths = ts.createMap();
104143         var directoryWatchesOfFailedLookups = ts.createMap();
104144         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
104145         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
104146         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
104147         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
104148         var typeRootsWatches = ts.createMap();
104149         return {
104150             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
104151             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
104152             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104153             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104154             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
104155             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
104156             resolveModuleNames: resolveModuleNames,
104157             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
104158             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
104159             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
104160             removeResolutionsOfFile: removeResolutionsOfFile,
104161             invalidateResolutionOfFile: invalidateResolutionOfFile,
104162             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
104163             createHasInvalidatedResolution: createHasInvalidatedResolution,
104164             updateTypeRootsWatch: updateTypeRootsWatch,
104165             closeTypeRootsWatch: closeTypeRootsWatch,
104166             clear: clear
104167         };
104168         function getResolvedModule(resolution) {
104169             return resolution.resolvedModule;
104170         }
104171         function getResolvedTypeReferenceDirective(resolution) {
104172             return resolution.resolvedTypeReferenceDirective;
104173         }
104174         function isInDirectoryPath(dir, file) {
104175             if (dir === undefined || file.length <= dir.length) {
104176                 return false;
104177             }
104178             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
104179         }
104180         function clear() {
104181             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
104182             customFailedLookupPaths.clear();
104183             nonRelativeExternalModuleResolutions.clear();
104184             closeTypeRootsWatch();
104185             resolvedModuleNames.clear();
104186             resolvedTypeReferenceDirectives.clear();
104187             resolvedFileToResolution.clear();
104188             resolutionsWithFailedLookups.length = 0;
104189             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104190             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104191             clearPerDirectoryResolutions();
104192         }
104193         function startRecordingFilesWithChangedResolutions() {
104194             filesWithChangedSetOfUnresolvedImports = [];
104195         }
104196         function finishRecordingFilesWithChangedResolutions() {
104197             var collected = filesWithChangedSetOfUnresolvedImports;
104198             filesWithChangedSetOfUnresolvedImports = undefined;
104199             return collected;
104200         }
104201         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
104202             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
104203                 return false;
104204             }
104205             // Invalidated if file has unresolved imports
104206             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
104207             return !!value && !!value.length;
104208         }
104209         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
104210             if (forceAllFilesAsInvalidated) {
104211                 // Any file asked would have invalidated resolution
104212                 filesWithInvalidatedResolutions = undefined;
104213                 return ts.returnTrue;
104214             }
104215             var collected = filesWithInvalidatedResolutions;
104216             filesWithInvalidatedResolutions = undefined;
104217             return function (path) { return (!!collected && collected.has(path)) ||
104218                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
104219         }
104220         function clearPerDirectoryResolutions() {
104221             perDirectoryResolvedModuleNames.clear();
104222             nonRelativeModuleNameCache.clear();
104223             perDirectoryResolvedTypeReferenceDirectives.clear();
104224             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
104225             nonRelativeExternalModuleResolutions.clear();
104226         }
104227         function finishCachingPerDirectoryResolution() {
104228             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
104229             clearPerDirectoryResolutions();
104230             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
104231                 if (watcher.refCount === 0) {
104232                     directoryWatchesOfFailedLookups.delete(path);
104233                     watcher.watcher.close();
104234                 }
104235             });
104236         }
104237         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
104238             var _a;
104239             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
104240             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
104241             if (!resolutionHost.getGlobalCache) {
104242                 return primaryResult;
104243             }
104244             // otherwise try to load typings from @types
104245             var globalCache = resolutionHost.getGlobalCache();
104246             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
104247                 // create different collection of failed lookup locations for second pass
104248                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
104249                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
104250                 if (resolvedModule) {
104251                     // Modify existing resolution so its saved in the directory cache as well
104252                     primaryResult.resolvedModule = resolvedModule;
104253                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
104254                     return primaryResult;
104255                 }
104256             }
104257             // Default return the result from the first pass
104258             return primaryResult;
104259         }
104260         function resolveNamesWithLocalCache(_a) {
104261             var _b;
104262             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;
104263             var path = resolutionHost.toPath(containingFile);
104264             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
104265             var dirPath = ts.getDirectoryPath(path);
104266             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
104267             var perDirectoryResolution = perDirectoryCache.get(dirPath);
104268             if (!perDirectoryResolution) {
104269                 perDirectoryResolution = ts.createMap();
104270                 perDirectoryCache.set(dirPath, perDirectoryResolution);
104271             }
104272             var resolvedModules = [];
104273             var compilerOptions = resolutionHost.getCompilationSettings();
104274             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
104275             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
104276             var program = resolutionHost.getCurrentProgram();
104277             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
104278             var unmatchedRedirects = oldRedirect ?
104279                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
104280                 !!redirectedReference;
104281             var seenNamesInFile = ts.createMap();
104282             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
104283                 var name = names_3[_i];
104284                 var resolution = resolutionsInFile.get(name);
104285                 // Resolution is valid if it is present and not invalidated
104286                 if (!seenNamesInFile.has(name) &&
104287                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
104288                     // If the name is unresolved import that was invalidated, recalculate
104289                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
104290                     var existingResolution = resolution;
104291                     var resolutionInDirectory = perDirectoryResolution.get(name);
104292                     if (resolutionInDirectory) {
104293                         resolution = resolutionInDirectory;
104294                     }
104295                     else {
104296                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
104297                         perDirectoryResolution.set(name, resolution);
104298                     }
104299                     resolutionsInFile.set(name, resolution);
104300                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
104301                     if (existingResolution) {
104302                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
104303                     }
104304                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
104305                         filesWithChangedSetOfUnresolvedImports.push(path);
104306                         // reset log changes to avoid recording the same file multiple times
104307                         logChanges = false;
104308                     }
104309                 }
104310                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
104311                 seenNamesInFile.set(name, true);
104312                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
104313             }
104314             // Stop watching and remove the unused name
104315             resolutionsInFile.forEach(function (resolution, name) {
104316                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
104317                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
104318                     resolutionsInFile.delete(name);
104319                 }
104320             });
104321             return resolvedModules;
104322             function resolutionIsEqualTo(oldResolution, newResolution) {
104323                 if (oldResolution === newResolution) {
104324                     return true;
104325                 }
104326                 if (!oldResolution || !newResolution) {
104327                     return false;
104328                 }
104329                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
104330                 var newResult = getResolutionWithResolvedFileName(newResolution);
104331                 if (oldResult === newResult) {
104332                     return true;
104333                 }
104334                 if (!oldResult || !newResult) {
104335                     return false;
104336                 }
104337                 return oldResult.resolvedFileName === newResult.resolvedFileName;
104338             }
104339         }
104340         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
104341             return resolveNamesWithLocalCache({
104342                 names: typeDirectiveNames,
104343                 containingFile: containingFile,
104344                 redirectedReference: redirectedReference,
104345                 cache: resolvedTypeReferenceDirectives,
104346                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
104347                 loader: ts.resolveTypeReferenceDirective,
104348                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
104349                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
104350             });
104351         }
104352         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
104353             return resolveNamesWithLocalCache({
104354                 names: moduleNames,
104355                 containingFile: containingFile,
104356                 redirectedReference: redirectedReference,
104357                 cache: resolvedModuleNames,
104358                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
104359                 loader: resolveModuleName,
104360                 getResolutionWithResolvedFileName: getResolvedModule,
104361                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
104362                 reusedNames: reusedNames,
104363                 logChanges: logChangesWhenResolvingModule
104364             });
104365         }
104366         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
104367             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
104368             return cache && cache.get(moduleName);
104369         }
104370         function isNodeModulesAtTypesDirectory(dirPath) {
104371             return ts.endsWith(dirPath, "/node_modules/@types");
104372         }
104373         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
104374             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
104375                 // Ensure failed look up is normalized path
104376                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
104377                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
104378                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
104379                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
104380                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
104381                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
104382                     return {
104383                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
104384                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
104385                     };
104386                 }
104387                 else {
104388                     // Always watch root directory non recursively
104389                     return {
104390                         dir: rootDir,
104391                         dirPath: rootPath,
104392                         nonRecursive: false
104393                     };
104394                 }
104395             }
104396             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
104397         }
104398         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
104399             // If directory path contains node module, get the most parent node_modules directory for watching
104400             while (ts.pathContainsNodeModules(dirPath)) {
104401                 dir = ts.getDirectoryPath(dir);
104402                 dirPath = ts.getDirectoryPath(dirPath);
104403             }
104404             // If the directory is node_modules use it to watch, always watch it recursively
104405             if (ts.isNodeModulesDirectory(dirPath)) {
104406                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
104407             }
104408             var nonRecursive = true;
104409             // Use some ancestor of the root directory
104410             var subDirectoryPath, subDirectory;
104411             if (rootPath !== undefined) {
104412                 while (!isInDirectoryPath(dirPath, rootPath)) {
104413                     var parentPath = ts.getDirectoryPath(dirPath);
104414                     if (parentPath === dirPath) {
104415                         break;
104416                     }
104417                     nonRecursive = false;
104418                     subDirectoryPath = dirPath;
104419                     subDirectory = dir;
104420                     dirPath = parentPath;
104421                     dir = ts.getDirectoryPath(dir);
104422                 }
104423             }
104424             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
104425         }
104426         function isPathWithDefaultFailedLookupExtension(path) {
104427             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
104428         }
104429         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
104430             if (resolution.refCount) {
104431                 resolution.refCount++;
104432                 ts.Debug.assertDefined(resolution.files);
104433             }
104434             else {
104435                 resolution.refCount = 1;
104436                 ts.Debug.assert(resolution.files === undefined);
104437                 if (ts.isExternalModuleNameRelative(name)) {
104438                     watchFailedLookupLocationOfResolution(resolution);
104439                 }
104440                 else {
104441                     nonRelativeExternalModuleResolutions.add(name, resolution);
104442                 }
104443                 var resolved = getResolutionWithResolvedFileName(resolution);
104444                 if (resolved && resolved.resolvedFileName) {
104445                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104446                 }
104447             }
104448             (resolution.files || (resolution.files = [])).push(filePath);
104449         }
104450         function watchFailedLookupLocationOfResolution(resolution) {
104451             ts.Debug.assert(!!resolution.refCount);
104452             var failedLookupLocations = resolution.failedLookupLocations;
104453             if (!failedLookupLocations.length)
104454                 return;
104455             resolutionsWithFailedLookups.push(resolution);
104456             var setAtRoot = false;
104457             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
104458                 var failedLookupLocation = failedLookupLocations_1[_i];
104459                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104460                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104461                 if (toWatch) {
104462                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
104463                     // If the failed lookup location path is not one of the supported extensions,
104464                     // store it in the custom path
104465                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
104466                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
104467                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
104468                     }
104469                     if (dirPath === rootPath) {
104470                         ts.Debug.assert(!nonRecursive);
104471                         setAtRoot = true;
104472                     }
104473                     else {
104474                         setDirectoryWatcher(dir, dirPath, nonRecursive);
104475                     }
104476                 }
104477             }
104478             if (setAtRoot) {
104479                 // This is always non recursive
104480                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
104481             }
104482         }
104483         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
104484             var program = resolutionHost.getCurrentProgram();
104485             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
104486                 resolutions.forEach(watchFailedLookupLocationOfResolution);
104487             }
104488         }
104489         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
104490             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104491             if (dirWatcher) {
104492                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
104493                 dirWatcher.refCount++;
104494             }
104495             else {
104496                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
104497             }
104498         }
104499         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
104500             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
104501             resolution.refCount--;
104502             if (resolution.refCount) {
104503                 return;
104504             }
104505             var resolved = getResolutionWithResolvedFileName(resolution);
104506             if (resolved && resolved.resolvedFileName) {
104507                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104508             }
104509             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
104510                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
104511                 return;
104512             }
104513             var failedLookupLocations = resolution.failedLookupLocations;
104514             var removeAtRoot = false;
104515             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
104516                 var failedLookupLocation = failedLookupLocations_2[_i];
104517                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104518                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104519                 if (toWatch) {
104520                     var dirPath = toWatch.dirPath;
104521                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
104522                     if (refCount) {
104523                         if (refCount === 1) {
104524                             customFailedLookupPaths.delete(failedLookupLocationPath);
104525                         }
104526                         else {
104527                             ts.Debug.assert(refCount > 1);
104528                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
104529                         }
104530                     }
104531                     if (dirPath === rootPath) {
104532                         removeAtRoot = true;
104533                     }
104534                     else {
104535                         removeDirectoryWatcher(dirPath);
104536                     }
104537                 }
104538             }
104539             if (removeAtRoot) {
104540                 removeDirectoryWatcher(rootPath);
104541             }
104542         }
104543         function removeDirectoryWatcher(dirPath) {
104544             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104545             // Do not close the watcher yet since it might be needed by other failed lookup locations.
104546             dirWatcher.refCount--;
104547         }
104548         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
104549             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
104550                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104551                 if (cachedDirectoryStructureHost) {
104552                     // Since the file existence changed, update the sourceFiles cache
104553                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104554                 }
104555                 if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104556                     resolutionHost.onInvalidatedResolution();
104557                 }
104558             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
104559         }
104560         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
104561             // Deleted file, stop watching failed lookups for all the resolutions in the file
104562             var resolutions = cache.get(filePath);
104563             if (resolutions) {
104564                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
104565                 cache.delete(filePath);
104566             }
104567         }
104568         function removeResolutionsFromProjectReferenceRedirects(filePath) {
104569             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
104570                 return;
104571             }
104572             var program = resolutionHost.getCurrentProgram();
104573             if (!program) {
104574                 return;
104575             }
104576             // If this file is input file for the referenced project, get it
104577             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
104578             if (!resolvedProjectReference) {
104579                 return;
104580             }
104581             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
104582             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
104583         }
104584         function removeResolutionsOfFile(filePath) {
104585             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
104586             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
104587         }
104588         function invalidateResolution(resolution) {
104589             resolution.isInvalidated = true;
104590             var changedInAutoTypeReferenced = false;
104591             for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) {
104592                 var containingFilePath = _a[_i];
104593                 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
104594                 // When its a file with inferred types resolution, invalidate type reference directive resolution
104595                 changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile);
104596             }
104597             if (changedInAutoTypeReferenced) {
104598                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104599             }
104600         }
104601         function invalidateResolutionOfFile(filePath) {
104602             removeResolutionsOfFile(filePath);
104603             // Resolution is invalidated if the resulting file name is same as the deleted file path
104604             ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution);
104605         }
104606         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
104607             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
104608             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
104609         }
104610         function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
104611             var isChangedFailedLookupLocation;
104612             if (isCreatingWatchedDirectory) {
104613                 // Watching directory is created
104614                 // Invalidate any resolution has failed lookup in this directory
104615                 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
104616             }
104617             else {
104618                 // If something to do with folder/file starting with "." in node_modules folder, skip it
104619                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
104620                 if (!updatedPath)
104621                     return false;
104622                 fileOrDirectoryPath = updatedPath;
104623                 // prevent saving an open file from over-eagerly triggering invalidation
104624                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
104625                     return false;
104626                 }
104627                 // Some file or directory in the watching directory is created
104628                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
104629                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
104630                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
104631                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
104632                     // Invalidate any resolution from this directory
104633                     isChangedFailedLookupLocation = function (location) {
104634                         var locationPath = resolutionHost.toPath(location);
104635                         return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
104636                     };
104637                 }
104638                 else {
104639                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
104640                         return false;
104641                     }
104642                     // Ignore emits from the program
104643                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
104644                         return false;
104645                     }
104646                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
104647                     isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
104648                 }
104649             }
104650             var invalidated = false;
104651             // Resolution is invalidated if the resulting file name is same as the deleted file path
104652             for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) {
104653                 var resolution = resolutionsWithFailedLookups_1[_i];
104654                 if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) {
104655                     invalidateResolution(resolution);
104656                     invalidated = true;
104657                 }
104658             }
104659             return invalidated;
104660         }
104661         function closeTypeRootsWatch() {
104662             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
104663         }
104664         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
104665             if (isInDirectoryPath(rootPath, typeRootPath)) {
104666                 return rootPath;
104667             }
104668             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
104669             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
104670         }
104671         function createTypeRootsWatch(typeRootPath, typeRoot) {
104672             // Create new watch and recursive info
104673             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
104674                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104675                 if (cachedDirectoryStructureHost) {
104676                     // Since the file existence changed, update the sourceFiles cache
104677                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104678                 }
104679                 // For now just recompile
104680                 // We could potentially store more data here about whether it was/would be really be used or not
104681                 // and with that determine to trigger compilation but for now this is enough
104682                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104683                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
104684                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
104685                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
104686                 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104687                     resolutionHost.onInvalidatedResolution();
104688                 }
104689             }, 1 /* Recursive */);
104690         }
104691         /**
104692          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
104693          * To be called when compiler options change
104694          */
104695         function updateTypeRootsWatch() {
104696             var options = resolutionHost.getCompilationSettings();
104697             if (options.types) {
104698                 // No need to do any watch since resolution cache is going to handle the failed lookups
104699                 // for the types added by this
104700                 closeTypeRootsWatch();
104701                 return;
104702             }
104703             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
104704             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
104705             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
104706             if (typeRoots) {
104707                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
104708                     createNewValue: createTypeRootsWatch,
104709                     onDeleteValue: ts.closeFileWatcher
104710                 });
104711             }
104712             else {
104713                 closeTypeRootsWatch();
104714             }
104715         }
104716         /**
104717          * Use this function to return if directory exists to get type roots to watch
104718          * If we return directory exists then only the paths will be added to type roots
104719          * Hence return true for all directories except root directories which are filtered from watching
104720          */
104721         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
104722             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
104723             var dirPath = resolutionHost.toPath(dir);
104724             return dirPath === rootPath || canWatchDirectory(dirPath);
104725         }
104726     }
104727     ts.createResolutionCache = createResolutionCache;
104728 })(ts || (ts = {}));
104729 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
104730 /* @internal */
104731 var ts;
104732 (function (ts) {
104733     var moduleSpecifiers;
104734     (function (moduleSpecifiers) {
104735         var RelativePreference;
104736         (function (RelativePreference) {
104737             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
104738             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
104739             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
104740         })(RelativePreference || (RelativePreference = {}));
104741         // See UserPreferences#importPathEnding
104742         var Ending;
104743         (function (Ending) {
104744             Ending[Ending["Minimal"] = 0] = "Minimal";
104745             Ending[Ending["Index"] = 1] = "Index";
104746             Ending[Ending["JsExtension"] = 2] = "JsExtension";
104747         })(Ending || (Ending = {}));
104748         function getPreferences(_a, compilerOptions, importingSourceFile) {
104749             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
104750             return {
104751                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
104752                 ending: getEnding(),
104753             };
104754             function getEnding() {
104755                 switch (importModuleSpecifierEnding) {
104756                     case "minimal": return 0 /* Minimal */;
104757                     case "index": return 1 /* Index */;
104758                     case "js": return 2 /* JsExtension */;
104759                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
104760                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
104761                 }
104762             }
104763         }
104764         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
104765             return {
104766                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
104767                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
104768                     2 /* JsExtension */ :
104769                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
104770             };
104771         }
104772         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
104773             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
104774             if (res === oldImportSpecifier)
104775                 return undefined;
104776             return res;
104777         }
104778         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
104779         // Note: importingSourceFile is just for usesJsExtensionOnImports
104780         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
104781             if (preferences === void 0) { preferences = {}; }
104782             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
104783         }
104784         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
104785         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
104786             var info = getInfo(importingSourceFileName, host);
104787             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
104788             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
104789         }
104790         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
104791         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
104792             var info = getInfo(importingSourceFileName, host);
104793             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
104794             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
104795                 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
104796         }
104797         /** Returns an import for each symlink and for the realpath. */
104798         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
104799             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
104800             if (ambient)
104801                 return [ambient];
104802             var info = getInfo(importingSourceFile.path, host);
104803             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
104804             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
104805             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
104806             var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
104807             return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
104808         }
104809         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
104810         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
104811         function getInfo(importingSourceFileName, host) {
104812             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
104813             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
104814             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
104815         }
104816         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
104817             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104818             var ending = _b.ending, relativePreference = _b.relativePreference;
104819             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
104820             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
104821                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
104822             if (!baseUrl || relativePreference === 0 /* Relative */) {
104823                 return relativePath;
104824             }
104825             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
104826             if (!relativeToBaseUrl) {
104827                 return relativePath;
104828             }
104829             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
104830             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
104831             var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
104832             if (relativePreference === 1 /* NonRelative */) {
104833                 return nonRelative;
104834             }
104835             if (relativePreference !== 2 /* Auto */)
104836                 ts.Debug.assertNever(relativePreference);
104837             // Prefer a relative import over a baseUrl import if it has fewer components.
104838             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
104839         }
104840         function countPathComponents(path) {
104841             var count = 0;
104842             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
104843                 if (path.charCodeAt(i) === 47 /* slash */)
104844                     count++;
104845             }
104846             return count;
104847         }
104848         moduleSpecifiers.countPathComponents = countPathComponents;
104849         function usesJsExtensionOnImports(_a) {
104850             var imports = _a.imports;
104851             return ts.firstDefined(imports, function (_a) {
104852                 var text = _a.text;
104853                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
104854             }) || false;
104855         }
104856         function numberOfDirectorySeparators(str) {
104857             var match = str.match(/\//g);
104858             return match ? match.length : 0;
104859         }
104860         function comparePathsByNumberOfDirectorySeparators(a, b) {
104861             return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
104862         }
104863         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
104864             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104865             var cwd = host.getCurrentDirectory();
104866             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
104867             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
104868             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
104869             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
104870             if (!preferSymlinks) {
104871                 var result_12 = ts.forEach(targets, cb);
104872                 if (result_12)
104873                     return result_12;
104874             }
104875             var links = host.getProbableSymlinks
104876                 ? host.getProbableSymlinks(host.getSourceFiles())
104877                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
104878             var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
104879             var result = ts.forEachEntry(links, function (resolved, path) {
104880                 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
104881                     return undefined; // Don't want to a package to globally import from itself
104882                 }
104883                 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
104884                 if (target === undefined)
104885                     return undefined;
104886                 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
104887                 var option = ts.resolvePath(path, relative);
104888                 if (!host.fileExists || host.fileExists(option)) {
104889                     var result_13 = cb(option);
104890                     if (result_13)
104891                         return result_13;
104892                 }
104893             });
104894             return result ||
104895                 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
104896         }
104897         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
104898         /**
104899          * Looks for existing imports that use symlinks to this module.
104900          * Symlinks will be returned first so they are preferred over the real path.
104901          */
104902         function getAllModulePaths(importingFileName, importedFileName, host) {
104903             var cwd = host.getCurrentDirectory();
104904             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104905             var allFileNames = ts.createMap();
104906             var importedFileFromNodeModules = false;
104907             forEachFileNameOfModule(importingFileName, importedFileName, host, 
104908             /*preferSymlinks*/ true, function (path) {
104909                 // dont return value, so we collect everything
104910                 allFileNames.set(path, getCanonicalFileName(path));
104911                 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
104912             });
104913             // Sort by paths closest to importing file Name directory
104914             var sortedPaths = [];
104915             var _loop_20 = function (directory) {
104916                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
104917                 var pathsInDirectory;
104918                 allFileNames.forEach(function (canonicalFileName, fileName) {
104919                     if (ts.startsWith(canonicalFileName, directoryStart)) {
104920                         // If the importedFile is from node modules, use only paths in node_modules folder as option
104921                         if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
104922                             (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
104923                         }
104924                         allFileNames.delete(fileName);
104925                     }
104926                 });
104927                 if (pathsInDirectory) {
104928                     if (pathsInDirectory.length > 1) {
104929                         pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
104930                     }
104931                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
104932                 }
104933                 var newDirectory = ts.getDirectoryPath(directory);
104934                 if (newDirectory === directory)
104935                     return out_directory_1 = directory, "break";
104936                 directory = newDirectory;
104937                 out_directory_1 = directory;
104938             };
104939             var out_directory_1;
104940             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
104941                 var state_8 = _loop_20(directory);
104942                 directory = out_directory_1;
104943                 if (state_8 === "break")
104944                     break;
104945             }
104946             if (allFileNames.size) {
104947                 var remainingPaths = ts.arrayFrom(allFileNames.values());
104948                 if (remainingPaths.length > 1)
104949                     remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
104950                 sortedPaths.push.apply(sortedPaths, remainingPaths);
104951             }
104952             return sortedPaths;
104953         }
104954         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
104955             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
104956             if (decl) {
104957                 return decl.name.text;
104958             }
104959         }
104960         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
104961             for (var key in paths) {
104962                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
104963                     var patternText_1 = _a[_i];
104964                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
104965                     var indexOfStar = pattern.indexOf("*");
104966                     if (indexOfStar !== -1) {
104967                         var prefix = pattern.substr(0, indexOfStar);
104968                         var suffix = pattern.substr(indexOfStar + 1);
104969                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
104970                             ts.startsWith(relativeToBaseUrl, prefix) &&
104971                             ts.endsWith(relativeToBaseUrl, suffix) ||
104972                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
104973                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
104974                             return key.replace("*", matchedStar);
104975                         }
104976                     }
104977                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
104978                         return key;
104979                     }
104980                 }
104981             }
104982         }
104983         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
104984             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
104985             if (normalizedTargetPath === undefined) {
104986                 return undefined;
104987             }
104988             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
104989             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
104990             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
104991                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
104992                 : ts.removeFileExtension(relativePath);
104993         }
104994         function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
104995             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104996             if (!host.fileExists || !host.readFile) {
104997                 return undefined;
104998             }
104999             var parts = getNodeModulePathParts(moduleFileName);
105000             if (!parts) {
105001                 return undefined;
105002             }
105003             // Simplify the full file path to something that can be resolved by Node.
105004             var moduleSpecifier = moduleFileName;
105005             if (!packageNameOnly) {
105006                 var packageRootIndex = parts.packageRootIndex;
105007                 var moduleFileNameForExtensionless = void 0;
105008                 while (true) {
105009                     // If the module could be imported by a directory name, use that directory's name
105010                     var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
105011                     if (packageRootPath) {
105012                         moduleSpecifier = packageRootPath;
105013                         break;
105014                     }
105015                     if (!moduleFileNameForExtensionless)
105016                         moduleFileNameForExtensionless = moduleFileToTry;
105017                     // try with next level of directory
105018                     packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
105019                     if (packageRootIndex === -1) {
105020                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
105021                         break;
105022                     }
105023                 }
105024             }
105025             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
105026             // Get a path that's relative to node_modules or the importing file's path
105027             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
105028             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
105029             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
105030                 return undefined;
105031             }
105032             // If the module was found in @types, get the actual Node package name
105033             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
105034             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
105035             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
105036             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
105037             function tryDirectoryWithPackageJson(packageRootIndex) {
105038                 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
105039                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
105040                 var moduleFileToTry = moduleFileName;
105041                 if (host.fileExists(packageJsonPath)) {
105042                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
105043                     var versionPaths = packageJsonContent.typesVersions
105044                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
105045                         : undefined;
105046                     if (versionPaths) {
105047                         var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
105048                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
105049                         if (fromPaths !== undefined) {
105050                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
105051                         }
105052                     }
105053                     // If the file is the main module, it can be imported by the package name
105054                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
105055                     if (ts.isString(mainFileRelative)) {
105056                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
105057                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
105058                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
105059                         }
105060                     }
105061                 }
105062                 return { moduleFileToTry: moduleFileToTry };
105063             }
105064             function getExtensionlessFileName(path) {
105065                 // We still have a file name - remove the extension
105066                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
105067                 // If the file is /index, it can be imported by its directory name
105068                 // IFF there is not _also_ a file by the same name
105069                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
105070                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
105071                 }
105072                 return fullModulePathWithoutExtension;
105073             }
105074         }
105075         function tryGetAnyFileFromPath(host, path) {
105076             if (!host.fileExists)
105077                 return;
105078             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
105079             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
105080             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
105081                 var e = extensions_3[_i];
105082                 var fullPath = path + e;
105083                 if (host.fileExists(fullPath)) {
105084                     return fullPath;
105085                 }
105086             }
105087         }
105088         function getNodeModulePathParts(fullPath) {
105089             // If fullPath can't be valid module file within node_modules, returns undefined.
105090             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
105091             // Returns indices:                       ^            ^                                                      ^             ^
105092             var topLevelNodeModulesIndex = 0;
105093             var topLevelPackageNameIndex = 0;
105094             var packageRootIndex = 0;
105095             var fileNameIndex = 0;
105096             var States;
105097             (function (States) {
105098                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
105099                 States[States["NodeModules"] = 1] = "NodeModules";
105100                 States[States["Scope"] = 2] = "Scope";
105101                 States[States["PackageContent"] = 3] = "PackageContent";
105102             })(States || (States = {}));
105103             var partStart = 0;
105104             var partEnd = 0;
105105             var state = 0 /* BeforeNodeModules */;
105106             while (partEnd >= 0) {
105107                 partStart = partEnd;
105108                 partEnd = fullPath.indexOf("/", partStart + 1);
105109                 switch (state) {
105110                     case 0 /* BeforeNodeModules */:
105111                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
105112                             topLevelNodeModulesIndex = partStart;
105113                             topLevelPackageNameIndex = partEnd;
105114                             state = 1 /* NodeModules */;
105115                         }
105116                         break;
105117                     case 1 /* NodeModules */:
105118                     case 2 /* Scope */:
105119                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
105120                             state = 2 /* Scope */;
105121                         }
105122                         else {
105123                             packageRootIndex = partEnd;
105124                             state = 3 /* PackageContent */;
105125                         }
105126                         break;
105127                     case 3 /* PackageContent */:
105128                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
105129                             state = 1 /* NodeModules */;
105130                         }
105131                         else {
105132                             state = 3 /* PackageContent */;
105133                         }
105134                         break;
105135                 }
105136             }
105137             fileNameIndex = partStart;
105138             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
105139         }
105140         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
105141             return ts.firstDefined(rootDirs, function (rootDir) {
105142                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
105143                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
105144             });
105145         }
105146         function removeExtensionAndIndexPostFix(fileName, ending, options) {
105147             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
105148                 return fileName;
105149             var noExtension = ts.removeFileExtension(fileName);
105150             switch (ending) {
105151                 case 0 /* Minimal */:
105152                     return ts.removeSuffix(noExtension, "/index");
105153                 case 1 /* Index */:
105154                     return noExtension;
105155                 case 2 /* JsExtension */:
105156                     return noExtension + getJSExtensionForFile(fileName, options);
105157                 default:
105158                     return ts.Debug.assertNever(ending);
105159             }
105160         }
105161         function getJSExtensionForFile(fileName, options) {
105162             var ext = ts.extensionFromPath(fileName);
105163             switch (ext) {
105164                 case ".ts" /* Ts */:
105165                 case ".d.ts" /* Dts */:
105166                     return ".js" /* Js */;
105167                 case ".tsx" /* Tsx */:
105168                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
105169                 case ".js" /* Js */:
105170                 case ".jsx" /* Jsx */:
105171                 case ".json" /* Json */:
105172                     return ext;
105173                 case ".tsbuildinfo" /* TsBuildInfo */:
105174                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
105175                 default:
105176                     return ts.Debug.assertNever(ext);
105177             }
105178         }
105179         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
105180             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
105181             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
105182         }
105183         function isPathRelativeToParent(path) {
105184             return ts.startsWith(path, "..");
105185         }
105186     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
105187 })(ts || (ts = {}));
105188 /*@internal*/
105189 var ts;
105190 (function (ts) {
105191     var sysFormatDiagnosticsHost = ts.sys ? {
105192         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
105193         getNewLine: function () { return ts.sys.newLine; },
105194         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
105195     } : undefined; // TODO: GH#18217
105196     /**
105197      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
105198      */
105199     function createDiagnosticReporter(system, pretty) {
105200         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
105201             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
105202             getNewLine: function () { return system.newLine; },
105203             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
105204         };
105205         if (!pretty) {
105206             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
105207         }
105208         var diagnostics = new Array(1);
105209         return function (diagnostic) {
105210             diagnostics[0] = diagnostic;
105211             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
105212             diagnostics[0] = undefined; // TODO: GH#18217
105213         };
105214     }
105215     ts.createDiagnosticReporter = createDiagnosticReporter;
105216     /**
105217      * @returns Whether the screen was cleared.
105218      */
105219     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
105220         if (system.clearScreen &&
105221             !options.preserveWatchOutput &&
105222             !options.extendedDiagnostics &&
105223             !options.diagnostics &&
105224             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
105225             system.clearScreen();
105226             return true;
105227         }
105228         return false;
105229     }
105230     ts.screenStartingMessageCodes = [
105231         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
105232         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
105233     ];
105234     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
105235         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
105236             ? newLine + newLine
105237             : newLine;
105238     }
105239     /**
105240      * Get locale specific time based on whether we are in test mode
105241      */
105242     function getLocaleTimeString(system) {
105243         return !system.now ?
105244             new Date().toLocaleTimeString() :
105245             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
105246     }
105247     ts.getLocaleTimeString = getLocaleTimeString;
105248     /**
105249      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105250      */
105251     function createWatchStatusReporter(system, pretty) {
105252         return pretty ?
105253             function (diagnostic, newLine, options) {
105254                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
105255                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
105256                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
105257                 system.write(output);
105258             } :
105259             function (diagnostic, newLine, options) {
105260                 var output = "";
105261                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
105262                     output += newLine;
105263                 }
105264                 output += getLocaleTimeString(system) + " - ";
105265                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
105266                 system.write(output);
105267             };
105268     }
105269     ts.createWatchStatusReporter = createWatchStatusReporter;
105270     /** Parses config file using System interface */
105271     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
105272         var host = system;
105273         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
105274         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
105275         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
105276         return result;
105277     }
105278     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
105279     function getErrorCountForSummary(diagnostics) {
105280         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
105281     }
105282     ts.getErrorCountForSummary = getErrorCountForSummary;
105283     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
105284         return errorCount === 1 ?
105285             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
105286             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
105287     }
105288     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
105289     function getErrorSummaryText(errorCount, newLine) {
105290         if (errorCount === 0)
105291             return "";
105292         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
105293         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
105294     }
105295     ts.getErrorSummaryText = getErrorSummaryText;
105296     function listFiles(program, writeFileName) {
105297         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
105298             ts.forEach(program.getSourceFiles(), function (file) {
105299                 writeFileName(file.fileName);
105300             });
105301         }
105302     }
105303     ts.listFiles = listFiles;
105304     /**
105305      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
105306      */
105307     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105308         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
105309         // First get and report any syntactic errors.
105310         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
105311         var configFileParsingDiagnosticsLength = allDiagnostics.length;
105312         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105313         // If we didn't have any syntactic errors, then also try getting the global and
105314         // semantic errors.
105315         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105316             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
105317             if (!isListFilesOnly) {
105318                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
105319                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105320                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105321                 }
105322             }
105323         }
105324         // Emit and report any errors we ran into.
105325         var emitResult = isListFilesOnly
105326             ? { emitSkipped: true, diagnostics: ts.emptyArray }
105327             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
105328         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
105329         ts.addRange(allDiagnostics, emitDiagnostics);
105330         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
105331         diagnostics.forEach(reportDiagnostic);
105332         if (writeFileName) {
105333             var currentDir_1 = program.getCurrentDirectory();
105334             ts.forEach(emittedFiles, function (file) {
105335                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
105336                 writeFileName("TSFILE: " + filepath);
105337             });
105338             listFiles(program, writeFileName);
105339         }
105340         if (reportSummary) {
105341             reportSummary(getErrorCountForSummary(diagnostics));
105342         }
105343         return {
105344             emitResult: emitResult,
105345             diagnostics: diagnostics,
105346         };
105347     }
105348     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
105349     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105350         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
105351         if (emitResult.emitSkipped && diagnostics.length > 0) {
105352             // If the emitter didn't emit anything, then pass that value along.
105353             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
105354         }
105355         else if (diagnostics.length > 0) {
105356             // The emitter emitted something, inform the caller if that happened in the presence
105357             // of diagnostics or not.
105358             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
105359         }
105360         return ts.ExitStatus.Success;
105361     }
105362     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
105363     ts.noopFileWatcher = { close: ts.noop };
105364     function createWatchHost(system, reportWatchStatus) {
105365         if (system === void 0) { system = ts.sys; }
105366         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
105367         return {
105368             onWatchStatusChange: onWatchStatusChange,
105369             watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
105370             watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
105371             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
105372             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
105373         };
105374     }
105375     ts.createWatchHost = createWatchHost;
105376     ts.WatchType = {
105377         ConfigFile: "Config file",
105378         SourceFile: "Source file",
105379         MissingFile: "Missing file",
105380         WildcardDirectory: "Wild card directory",
105381         FailedLookupLocations: "Failed Lookup Locations",
105382         TypeRoots: "Type roots"
105383     };
105384     function createWatchFactory(host, options) {
105385         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
105386         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
105387         var result = ts.getWatchFactory(watchLogLevel, writeLog);
105388         result.writeLog = writeLog;
105389         return result;
105390     }
105391     ts.createWatchFactory = createWatchFactory;
105392     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
105393         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105394         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105395         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
105396         return {
105397             getSourceFile: function (fileName, languageVersion, onError) {
105398                 var text;
105399                 try {
105400                     ts.performance.mark("beforeIORead");
105401                     text = host.readFile(fileName, getCompilerOptions().charset);
105402                     ts.performance.mark("afterIORead");
105403                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105404                 }
105405                 catch (e) {
105406                     if (onError) {
105407                         onError(e.message);
105408                     }
105409                     text = "";
105410                 }
105411                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
105412             },
105413             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
105414             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
105415             writeFile: writeFile,
105416             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
105417             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
105418             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
105419             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
105420             fileExists: function (f) { return host.fileExists(f); },
105421             readFile: function (f) { return host.readFile(f); },
105422             trace: ts.maybeBind(host, host.trace),
105423             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
105424             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
105425             realpath: ts.maybeBind(host, host.realpath),
105426             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
105427             createHash: ts.maybeBind(host, host.createHash),
105428             readDirectory: ts.maybeBind(host, host.readDirectory),
105429         };
105430         function writeFile(fileName, text, writeByteOrderMark, onError) {
105431             try {
105432                 ts.performance.mark("beforeIOWrite");
105433                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105434                 // the host.writeFile will do its own directory creation and
105435                 // the ensureDirectoriesExist call will always be redundant.
105436                 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); });
105437                 ts.performance.mark("afterIOWrite");
105438                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105439             }
105440             catch (e) {
105441                 if (onError) {
105442                     onError(e.message);
105443                 }
105444             }
105445         }
105446     }
105447     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
105448     function setGetSourceFileAsHashVersioned(compilerHost, host) {
105449         var originalGetSourceFile = compilerHost.getSourceFile;
105450         var computeHash = host.createHash || ts.generateDjb2Hash;
105451         compilerHost.getSourceFile = function () {
105452             var args = [];
105453             for (var _i = 0; _i < arguments.length; _i++) {
105454                 args[_i] = arguments[_i];
105455             }
105456             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
105457             if (result) {
105458                 result.version = computeHash.call(host, result.text);
105459             }
105460             return result;
105461         };
105462     }
105463     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
105464     /**
105465      * Creates the watch compiler host that can be extended with config file or root file names and options host
105466      */
105467     function createProgramHost(system, createProgram) {
105468         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
105469         return {
105470             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105471             getNewLine: function () { return system.newLine; },
105472             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105473             getDefaultLibLocation: getDefaultLibLocation,
105474             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105475             fileExists: function (path) { return system.fileExists(path); },
105476             readFile: function (path, encoding) { return system.readFile(path, encoding); },
105477             directoryExists: function (path) { return system.directoryExists(path); },
105478             getDirectories: function (path) { return system.getDirectories(path); },
105479             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
105480             realpath: ts.maybeBind(system, system.realpath),
105481             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
105482             trace: function (s) { return system.write(s + system.newLine); },
105483             createDirectory: function (path) { return system.createDirectory(path); },
105484             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
105485             createHash: ts.maybeBind(system, system.createHash),
105486             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
105487         };
105488     }
105489     ts.createProgramHost = createProgramHost;
105490     /**
105491      * Creates the watch compiler host that can be extended with config file or root file names and options host
105492      */
105493     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
105494         if (system === void 0) { system = ts.sys; }
105495         var writeFileName = function (s) { return system.write(s + system.newLine); };
105496         var result = createProgramHost(system, createProgram);
105497         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
105498         result.afterProgramCreate = function (builderProgram) {
105499             var compilerOptions = builderProgram.getCompilerOptions();
105500             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
105501             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
105502         };
105503         return result;
105504     }
105505     /**
105506      * Report error and exit
105507      */
105508     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
105509         reportDiagnostic(diagnostic);
105510         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
105511     }
105512     /**
105513      * Creates the watch compiler host from system for config file in watch mode
105514      */
105515     function createWatchCompilerHostOfConfigFile(_a) {
105516         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;
105517         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
105518         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
105519         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
105520         host.configFileName = configFileName;
105521         host.optionsToExtend = optionsToExtend;
105522         host.watchOptionsToExtend = watchOptionsToExtend;
105523         host.extraFileExtensions = extraFileExtensions;
105524         return host;
105525     }
105526     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
105527     /**
105528      * Creates the watch compiler host from system for compiling root files and options in watch mode
105529      */
105530     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
105531         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;
105532         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
105533         host.rootFiles = rootFiles;
105534         host.options = options;
105535         host.watchOptions = watchOptions;
105536         host.projectReferences = projectReferences;
105537         return host;
105538     }
105539     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
105540     function performIncrementalCompilation(input) {
105541         var system = input.system || ts.sys;
105542         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
105543         var builderProgram = ts.createIncrementalProgram(input);
105544         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);
105545         if (input.afterProgramEmitAndDiagnostics)
105546             input.afterProgramEmitAndDiagnostics(builderProgram);
105547         return exitStatus;
105548     }
105549     ts.performIncrementalCompilation = performIncrementalCompilation;
105550 })(ts || (ts = {}));
105551 var ts;
105552 (function (ts) {
105553     function readBuilderProgram(compilerOptions, host) {
105554         if (compilerOptions.out || compilerOptions.outFile)
105555             return undefined;
105556         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
105557         if (!buildInfoPath)
105558             return undefined;
105559         var content = host.readFile(buildInfoPath);
105560         if (!content)
105561             return undefined;
105562         var buildInfo = ts.getBuildInfo(content);
105563         if (buildInfo.version !== ts.version)
105564             return undefined;
105565         if (!buildInfo.program)
105566             return undefined;
105567         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
105568     }
105569     ts.readBuilderProgram = readBuilderProgram;
105570     function createIncrementalCompilerHost(options, system) {
105571         if (system === void 0) { system = ts.sys; }
105572         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
105573         host.createHash = ts.maybeBind(system, system.createHash);
105574         ts.setGetSourceFileAsHashVersioned(host, system);
105575         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
105576         return host;
105577     }
105578     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
105579     function createIncrementalProgram(_a) {
105580         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
105581         host = host || createIncrementalCompilerHost(options);
105582         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
105583         var oldProgram = readBuilderProgram(options, host);
105584         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
105585     }
105586     ts.createIncrementalProgram = createIncrementalProgram;
105587     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
105588         if (ts.isArray(rootFilesOrConfigFileName)) {
105589             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
105590                 rootFiles: rootFilesOrConfigFileName,
105591                 options: options,
105592                 watchOptions: watchOptionsOrExtraFileExtensions,
105593                 projectReferences: projectReferencesOrWatchOptionsToExtend,
105594                 system: system,
105595                 createProgram: createProgram,
105596                 reportDiagnostic: reportDiagnostic,
105597                 reportWatchStatus: reportWatchStatus,
105598             });
105599         }
105600         else {
105601             return ts.createWatchCompilerHostOfConfigFile({
105602                 configFileName: rootFilesOrConfigFileName,
105603                 optionsToExtend: options,
105604                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
105605                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
105606                 system: system,
105607                 createProgram: createProgram,
105608                 reportDiagnostic: reportDiagnostic,
105609                 reportWatchStatus: reportWatchStatus,
105610             });
105611         }
105612     }
105613     ts.createWatchCompilerHost = createWatchCompilerHost;
105614     function createWatchProgram(host) {
105615         var builderProgram;
105616         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
105617         var missingFilesMap; // Map of file watchers for the missing files
105618         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
105619         var timerToUpdateProgram; // timer callback to recompile the program
105620         var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
105621         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
105622         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
105623         var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
105624         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105625         var currentDirectory = host.getCurrentDirectory();
105626         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
105627         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
105628         var configFileSpecs;
105629         var configFileParsingDiagnostics;
105630         var canConfigFileJsonReportNoInputFiles = false;
105631         var hasChangedConfigFileParsingErrors = false;
105632         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
105633         var directoryStructureHost = cachedDirectoryStructureHost || host;
105634         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
105635         // From tsc we want to get already parsed result and hence check for rootFileNames
105636         var newLine = updateNewLine();
105637         if (configFileName && host.configFileParsingResult) {
105638             setConfigFileParsingResult(host.configFileParsingResult);
105639             newLine = updateNewLine();
105640         }
105641         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
105642         if (configFileName && !host.configFileParsingResult) {
105643             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105644             ts.Debug.assert(!rootFileNames);
105645             parseConfigFile();
105646             newLine = updateNewLine();
105647         }
105648         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
105649         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105650         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
105651         var configFileWatcher;
105652         if (configFileName) {
105653             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
105654         }
105655         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
105656         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
105657         // Members for CompilerHost
105658         var getNewSourceFile = compilerHost.getSourceFile;
105659         compilerHost.getSourceFile = function (fileName) {
105660             var args = [];
105661             for (var _i = 1; _i < arguments.length; _i++) {
105662                 args[_i - 1] = arguments[_i];
105663             }
105664             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
105665         };
105666         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
105667         compilerHost.getNewLine = function () { return newLine; };
105668         compilerHost.fileExists = fileExists;
105669         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
105670         // Members for ResolutionCacheHost
105671         compilerHost.toPath = toPath;
105672         compilerHost.getCompilationSettings = function () { return compilerOptions; };
105673         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
105674         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
105675         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
105676         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
105677         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
105678         compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
105679             hasChangedAutomaticTypeDirectiveNames = true;
105680             scheduleProgramUpdate();
105681         };
105682         compilerHost.fileIsOpen = ts.returnFalse;
105683         compilerHost.getCurrentProgram = getCurrentProgram;
105684         compilerHost.writeLog = writeLog;
105685         // Cache for the module resolution
105686         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
105687             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
105688             currentDirectory, 
105689         /*logChangesWhenResolvingModule*/ false);
105690         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
105691         compilerHost.resolveModuleNames = host.resolveModuleNames ?
105692             (function () {
105693                 var args = [];
105694                 for (var _i = 0; _i < arguments.length; _i++) {
105695                     args[_i] = arguments[_i];
105696                 }
105697                 return host.resolveModuleNames.apply(host, args);
105698             }) :
105699             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
105700         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
105701             (function () {
105702                 var args = [];
105703                 for (var _i = 0; _i < arguments.length; _i++) {
105704                     args[_i] = arguments[_i];
105705                 }
105706                 return host.resolveTypeReferenceDirectives.apply(host, args);
105707             }) :
105708             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
105709         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
105710         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
105711         synchronizeProgram();
105712         // Update the wild card directory watch
105713         watchConfigFileWildCardDirectories();
105714         return configFileName ?
105715             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
105716             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
105717         function close() {
105718             resolutionCache.clear();
105719             ts.clearMap(sourceFilesCache, function (value) {
105720                 if (value && value.fileWatcher) {
105721                     value.fileWatcher.close();
105722                     value.fileWatcher = undefined;
105723                 }
105724             });
105725             if (configFileWatcher) {
105726                 configFileWatcher.close();
105727                 configFileWatcher = undefined;
105728             }
105729             if (watchedWildcardDirectories) {
105730                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105731                 watchedWildcardDirectories = undefined;
105732             }
105733             if (missingFilesMap) {
105734                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
105735                 missingFilesMap = undefined;
105736             }
105737         }
105738         function getCurrentBuilderProgram() {
105739             return builderProgram;
105740         }
105741         function getCurrentProgram() {
105742             return builderProgram && builderProgram.getProgramOrUndefined();
105743         }
105744         function synchronizeProgram() {
105745             writeLog("Synchronizing program");
105746             var program = getCurrentBuilderProgram();
105747             if (hasChangedCompilerOptions) {
105748                 newLine = updateNewLine();
105749                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
105750                     resolutionCache.clear();
105751                 }
105752             }
105753             // All resolutions are invalid if user provided resolutions
105754             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
105755             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
105756                 if (hasChangedConfigFileParsingErrors) {
105757                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105758                     hasChangedConfigFileParsingErrors = false;
105759                 }
105760             }
105761             else {
105762                 createNewProgram(hasInvalidatedResolution);
105763             }
105764             if (host.afterProgramCreate && program !== builderProgram) {
105765                 host.afterProgramCreate(builderProgram);
105766             }
105767             return builderProgram;
105768         }
105769         function createNewProgram(hasInvalidatedResolution) {
105770             // Compile the program
105771             writeLog("CreatingProgramWith::");
105772             writeLog("  roots: " + JSON.stringify(rootFileNames));
105773             writeLog("  options: " + JSON.stringify(compilerOptions));
105774             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
105775             hasChangedCompilerOptions = false;
105776             hasChangedConfigFileParsingErrors = false;
105777             resolutionCache.startCachingPerDirectoryResolution();
105778             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
105779             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
105780             hasChangedAutomaticTypeDirectiveNames = false;
105781             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105782             resolutionCache.finishCachingPerDirectoryResolution();
105783             // Update watches
105784             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
105785             if (needsUpdateInTypeRootWatch) {
105786                 resolutionCache.updateTypeRootsWatch();
105787             }
105788             if (missingFilePathsRequestedForRelease) {
105789                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
105790                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
105791                 // if there is already watcher for it (for missing files)
105792                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
105793                 // so that at later time we have correct result of their presence
105794                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
105795                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
105796                     if (!missingFilesMap.has(missingFilePath)) {
105797                         sourceFilesCache.delete(missingFilePath);
105798                     }
105799                 }
105800                 missingFilePathsRequestedForRelease = undefined;
105801             }
105802         }
105803         function updateRootFileNames(files) {
105804             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
105805             rootFileNames = files;
105806             scheduleProgramUpdate();
105807         }
105808         function updateNewLine() {
105809             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105810         }
105811         function toPath(fileName) {
105812             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105813         }
105814         function isFileMissingOnHost(hostSourceFile) {
105815             return typeof hostSourceFile === "boolean";
105816         }
105817         function isFilePresenceUnknownOnHost(hostSourceFile) {
105818             return typeof hostSourceFile.version === "boolean";
105819         }
105820         function fileExists(fileName) {
105821             var path = toPath(fileName);
105822             // If file is missing on host from cache, we can definitely say file doesnt exist
105823             // otherwise we need to ensure from the disk
105824             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
105825                 return false;
105826             }
105827             return directoryStructureHost.fileExists(fileName);
105828         }
105829         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
105830             var hostSourceFile = sourceFilesCache.get(path);
105831             // No source file on the host
105832             if (isFileMissingOnHost(hostSourceFile)) {
105833                 return undefined;
105834             }
105835             // Create new source file if requested or the versions dont match
105836             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
105837                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
105838                 if (hostSourceFile) {
105839                     if (sourceFile) {
105840                         // Set the source file and create file watcher now that file was present on the disk
105841                         hostSourceFile.sourceFile = sourceFile;
105842                         hostSourceFile.version = sourceFile.version;
105843                         if (!hostSourceFile.fileWatcher) {
105844                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105845                         }
105846                     }
105847                     else {
105848                         // There is no source file on host any more, close the watch, missing file paths will track it
105849                         if (hostSourceFile.fileWatcher) {
105850                             hostSourceFile.fileWatcher.close();
105851                         }
105852                         sourceFilesCache.set(path, false);
105853                     }
105854                 }
105855                 else {
105856                     if (sourceFile) {
105857                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105858                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
105859                     }
105860                     else {
105861                         sourceFilesCache.set(path, false);
105862                     }
105863                 }
105864                 return sourceFile;
105865             }
105866             return hostSourceFile.sourceFile;
105867         }
105868         function nextSourceFileVersion(path) {
105869             var hostSourceFile = sourceFilesCache.get(path);
105870             if (hostSourceFile !== undefined) {
105871                 if (isFileMissingOnHost(hostSourceFile)) {
105872                     // The next version, lets set it as presence unknown file
105873                     sourceFilesCache.set(path, { version: false });
105874                 }
105875                 else {
105876                     hostSourceFile.version = false;
105877                 }
105878             }
105879         }
105880         function getSourceVersion(path) {
105881             var hostSourceFile = sourceFilesCache.get(path);
105882             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
105883         }
105884         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
105885             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
105886             // If this is the source file thats in the cache and new program doesnt need it,
105887             // remove the cached entry.
105888             // Note we arent deleting entry if file became missing in new program or
105889             // there was version update and new source file was created.
105890             if (hostSourceFileInfo !== undefined) {
105891                 // record the missing file paths so they can be removed later if watchers arent tracking them
105892                 if (isFileMissingOnHost(hostSourceFileInfo)) {
105893                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
105894                 }
105895                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
105896                     if (hostSourceFileInfo.fileWatcher) {
105897                         hostSourceFileInfo.fileWatcher.close();
105898                     }
105899                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
105900                     if (!hasSourceFileByPath) {
105901                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
105902                     }
105903                 }
105904             }
105905         }
105906         function reportWatchDiagnostic(message) {
105907             if (host.onWatchStatusChange) {
105908                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
105909             }
105910         }
105911         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
105912         // operations (such as saving all modified files in an editor) a chance to complete before we kick
105913         // off a new compilation.
105914         function scheduleProgramUpdate() {
105915             if (!host.setTimeout || !host.clearTimeout) {
105916                 return;
105917             }
105918             if (timerToUpdateProgram) {
105919                 host.clearTimeout(timerToUpdateProgram);
105920             }
105921             writeLog("Scheduling update");
105922             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
105923         }
105924         function scheduleProgramReload() {
105925             ts.Debug.assert(!!configFileName);
105926             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
105927             scheduleProgramUpdate();
105928         }
105929         function updateProgramWithWatchStatus() {
105930             timerToUpdateProgram = undefined;
105931             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
105932             updateProgram();
105933         }
105934         function updateProgram() {
105935             switch (reloadLevel) {
105936                 case ts.ConfigFileProgramReloadLevel.Partial:
105937                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
105938                     reloadFileNamesFromConfigFile();
105939                     break;
105940                 case ts.ConfigFileProgramReloadLevel.Full:
105941                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
105942                     reloadConfigFile();
105943                     break;
105944                 default:
105945                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
105946                     synchronizeProgram();
105947                     break;
105948             }
105949             ts.perfLogger.logStopUpdateProgram("Done");
105950             return getCurrentBuilderProgram();
105951         }
105952         function reloadFileNamesFromConfigFile() {
105953             writeLog("Reloading new file names and options");
105954             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
105955             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
105956                 hasChangedConfigFileParsingErrors = true;
105957             }
105958             rootFileNames = result.fileNames;
105959             // Update the program
105960             synchronizeProgram();
105961         }
105962         function reloadConfigFile() {
105963             writeLog("Reloading config file: " + configFileName);
105964             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
105965             if (cachedDirectoryStructureHost) {
105966                 cachedDirectoryStructureHost.clearCache();
105967             }
105968             parseConfigFile();
105969             hasChangedCompilerOptions = true;
105970             synchronizeProgram();
105971             // Update the wild card directory watch
105972             watchConfigFileWildCardDirectories();
105973         }
105974         function parseConfigFile() {
105975             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
105976         }
105977         function setConfigFileParsingResult(configFileParseResult) {
105978             rootFileNames = configFileParseResult.fileNames;
105979             compilerOptions = configFileParseResult.options;
105980             watchOptions = configFileParseResult.watchOptions;
105981             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
105982             projectReferences = configFileParseResult.projectReferences;
105983             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
105984             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
105985             hasChangedConfigFileParsingErrors = true;
105986         }
105987         function onSourceFileChange(fileName, eventKind, path) {
105988             updateCachedSystemWithFile(fileName, path, eventKind);
105989             // Update the source file cache
105990             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
105991                 resolutionCache.invalidateResolutionOfFile(path);
105992             }
105993             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
105994             nextSourceFileVersion(path);
105995             // Update the program
105996             scheduleProgramUpdate();
105997         }
105998         function updateCachedSystemWithFile(fileName, path, eventKind) {
105999             if (cachedDirectoryStructureHost) {
106000                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
106001             }
106002         }
106003         function watchMissingFilePath(missingFilePath) {
106004             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
106005         }
106006         function onMissingFileChange(fileName, eventKind, missingFilePath) {
106007             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
106008             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
106009                 missingFilesMap.get(missingFilePath).close();
106010                 missingFilesMap.delete(missingFilePath);
106011                 // Delete the entry in the source files cache so that new source file is created
106012                 nextSourceFileVersion(missingFilePath);
106013                 // When a missing file is created, we should update the graph.
106014                 scheduleProgramUpdate();
106015             }
106016         }
106017         function watchConfigFileWildCardDirectories() {
106018             if (configFileSpecs) {
106019                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
106020             }
106021             else if (watchedWildcardDirectories) {
106022                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
106023             }
106024         }
106025         function watchWildcardDirectory(directory, flags) {
106026             return watchDirectory(host, directory, function (fileOrDirectory) {
106027                 ts.Debug.assert(!!configFileName);
106028                 var fileOrDirectoryPath = toPath(fileOrDirectory);
106029                 // Since the file existence changed, update the sourceFiles cache
106030                 if (cachedDirectoryStructureHost) {
106031                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
106032                 }
106033                 nextSourceFileVersion(fileOrDirectoryPath);
106034                 fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
106035                 if (!fileOrDirectoryPath)
106036                     return;
106037                 // If the the added or created file or directory is not supported file name, ignore the file
106038                 // But when watched directory is added/removed, we need to reload the file list
106039                 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
106040                     writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
106041                     return;
106042                 }
106043                 // Reload is pending, do the reload
106044                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
106045                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
106046                     // Schedule Update the program
106047                     scheduleProgramUpdate();
106048                 }
106049             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
106050         }
106051     }
106052     ts.createWatchProgram = createWatchProgram;
106053 })(ts || (ts = {}));
106054 /*@internal*/
106055 var ts;
106056 (function (ts) {
106057     var UpToDateStatusType;
106058     (function (UpToDateStatusType) {
106059         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
106060         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
106061         /**
106062          * The project appears out of date because its upstream inputs are newer than its outputs,
106063          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
106064          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
106065          */
106066         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
106067         /**
106068          * The project appears out of date because its upstream inputs are newer than its outputs,
106069          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
106070          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
106071          */
106072         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
106073         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
106074         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
106075         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
106076         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
106077         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
106078         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
106079         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
106080         /**
106081          * Projects with no outputs (i.e. "solution" files)
106082          */
106083         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
106084     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
106085     function resolveConfigFileProjectName(project) {
106086         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
106087             return project;
106088         }
106089         return ts.combinePaths(project, "tsconfig.json");
106090     }
106091     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
106092 })(ts || (ts = {}));
106093 var ts;
106094 (function (ts) {
106095     var minimumDate = new Date(-8640000000000000);
106096     var maximumDate = new Date(8640000000000000);
106097     var BuildResultFlags;
106098     (function (BuildResultFlags) {
106099         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
106100         /**
106101          * No errors of any kind occurred during build
106102          */
106103         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
106104         /**
106105          * None of the .d.ts files emitted by this build were
106106          * different from the existing files on disk
106107          */
106108         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
106109         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
106110         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
106111         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
106112         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
106113         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
106114         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
106115     })(BuildResultFlags || (BuildResultFlags = {}));
106116     function createConfigFileMap() {
106117         return ts.createMap();
106118     }
106119     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
106120         var existingValue = configFileMap.get(resolved);
106121         var newValue;
106122         if (!existingValue) {
106123             newValue = createT();
106124             configFileMap.set(resolved, newValue);
106125         }
106126         return existingValue || newValue;
106127     }
106128     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
106129         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
106130     }
106131     function newer(date1, date2) {
106132         return date2 > date1 ? date2 : date1;
106133     }
106134     function isDeclarationFile(fileName) {
106135         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
106136     }
106137     /*@internal*/
106138     function isCircularBuildOrder(buildOrder) {
106139         return !!buildOrder && !!buildOrder.buildOrder;
106140     }
106141     ts.isCircularBuildOrder = isCircularBuildOrder;
106142     /*@internal*/
106143     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
106144         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
106145     }
106146     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
106147     /**
106148      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
106149      */
106150     function createBuilderStatusReporter(system, pretty) {
106151         return function (diagnostic) {
106152             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
106153             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
106154             system.write(output);
106155         };
106156     }
106157     ts.createBuilderStatusReporter = createBuilderStatusReporter;
106158     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
106159         var host = ts.createProgramHost(system, createProgram);
106160         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
106161         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
106162         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
106163         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
106164         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
106165         host.now = ts.maybeBind(system, system.now); // For testing
106166         return host;
106167     }
106168     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
106169         if (system === void 0) { system = ts.sys; }
106170         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106171         host.reportErrorSummary = reportErrorSummary;
106172         return host;
106173     }
106174     ts.createSolutionBuilderHost = createSolutionBuilderHost;
106175     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
106176         if (system === void 0) { system = ts.sys; }
106177         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106178         var watchHost = ts.createWatchHost(system, reportWatchStatus);
106179         ts.copyProperties(host, watchHost);
106180         return host;
106181     }
106182     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
106183     function getCompilerOptionsOfBuildOptions(buildOptions) {
106184         var result = {};
106185         ts.commonOptionsWithBuild.forEach(function (option) {
106186             if (ts.hasProperty(buildOptions, option.name))
106187                 result[option.name] = buildOptions[option.name];
106188         });
106189         return result;
106190     }
106191     function createSolutionBuilder(host, rootNames, defaultOptions) {
106192         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
106193     }
106194     ts.createSolutionBuilder = createSolutionBuilder;
106195     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
106196         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
106197     }
106198     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
106199     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
106200         var host = hostOrHostWithWatch;
106201         var hostWithWatch = hostOrHostWithWatch;
106202         var currentDirectory = host.getCurrentDirectory();
106203         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106204         // State of the solution
106205         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
106206         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
106207         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
106208         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
106209         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
106210         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
106211         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
106212         if (!compilerHost.resolveModuleNames) {
106213             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
106214             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
106215                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
106216             };
106217         }
106218         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
106219         var state = {
106220             host: host,
106221             hostWithWatch: hostWithWatch,
106222             currentDirectory: currentDirectory,
106223             getCanonicalFileName: getCanonicalFileName,
106224             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
106225             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
106226             // State of solution
106227             options: options,
106228             baseCompilerOptions: baseCompilerOptions,
106229             rootNames: rootNames,
106230             baseWatchOptions: baseWatchOptions,
106231             resolvedConfigFilePaths: ts.createMap(),
106232             configFileCache: createConfigFileMap(),
106233             projectStatus: createConfigFileMap(),
106234             buildInfoChecked: createConfigFileMap(),
106235             extendedConfigCache: ts.createMap(),
106236             builderPrograms: createConfigFileMap(),
106237             diagnostics: createConfigFileMap(),
106238             projectPendingBuild: createConfigFileMap(),
106239             projectErrorsReported: createConfigFileMap(),
106240             compilerHost: compilerHost,
106241             moduleResolutionCache: moduleResolutionCache,
106242             // Mutable state
106243             buildOrder: undefined,
106244             readFileWithCache: function (f) { return host.readFile(f); },
106245             projectCompilerOptions: baseCompilerOptions,
106246             cache: undefined,
106247             allProjectBuildPending: true,
106248             needsSummary: true,
106249             watchAllProjectsPending: watch,
106250             currentInvalidatedProject: undefined,
106251             // Watch state
106252             watch: watch,
106253             allWatchedWildcardDirectories: createConfigFileMap(),
106254             allWatchedInputFiles: createConfigFileMap(),
106255             allWatchedConfigFiles: createConfigFileMap(),
106256             timerToBuildInvalidatedProject: undefined,
106257             reportFileChangeDetected: false,
106258             watchFile: watchFile,
106259             watchFilePath: watchFilePath,
106260             watchDirectory: watchDirectory,
106261             writeLog: writeLog,
106262         };
106263         return state;
106264     }
106265     function toPath(state, fileName) {
106266         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
106267     }
106268     function toResolvedConfigFilePath(state, fileName) {
106269         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
106270         var path = resolvedConfigFilePaths.get(fileName);
106271         if (path !== undefined)
106272             return path;
106273         var resolvedPath = toPath(state, fileName);
106274         resolvedConfigFilePaths.set(fileName, resolvedPath);
106275         return resolvedPath;
106276     }
106277     function isParsedCommandLine(entry) {
106278         return !!entry.options;
106279     }
106280     function parseConfigFile(state, configFileName, configFilePath) {
106281         var configFileCache = state.configFileCache;
106282         var value = configFileCache.get(configFilePath);
106283         if (value) {
106284             return isParsedCommandLine(value) ? value : undefined;
106285         }
106286         var diagnostic;
106287         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
106288         var parsed;
106289         if (host.getParsedCommandLine) {
106290             parsed = host.getParsedCommandLine(configFileName);
106291             if (!parsed)
106292                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
106293         }
106294         else {
106295             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
106296             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
106297             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
106298         }
106299         configFileCache.set(configFilePath, parsed || diagnostic);
106300         return parsed;
106301     }
106302     function resolveProjectName(state, name) {
106303         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
106304     }
106305     function createBuildOrder(state, roots) {
106306         var temporaryMarks = ts.createMap();
106307         var permanentMarks = ts.createMap();
106308         var circularityReportStack = [];
106309         var buildOrder;
106310         var circularDiagnostics;
106311         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
106312             var root = roots_1[_i];
106313             visit(root);
106314         }
106315         return circularDiagnostics ?
106316             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
106317             buildOrder || ts.emptyArray;
106318         function visit(configFileName, inCircularContext) {
106319             var projPath = toResolvedConfigFilePath(state, configFileName);
106320             // Already visited
106321             if (permanentMarks.has(projPath))
106322                 return;
106323             // Circular
106324             if (temporaryMarks.has(projPath)) {
106325                 if (!inCircularContext) {
106326                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
106327                 }
106328                 return;
106329             }
106330             temporaryMarks.set(projPath, true);
106331             circularityReportStack.push(configFileName);
106332             var parsed = parseConfigFile(state, configFileName, projPath);
106333             if (parsed && parsed.projectReferences) {
106334                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
106335                     var ref = _a[_i];
106336                     var resolvedRefPath = resolveProjectName(state, ref.path);
106337                     visit(resolvedRefPath, inCircularContext || ref.circular);
106338                 }
106339             }
106340             circularityReportStack.pop();
106341             permanentMarks.set(projPath, true);
106342             (buildOrder || (buildOrder = [])).push(configFileName);
106343         }
106344     }
106345     function getBuildOrder(state) {
106346         return state.buildOrder || createStateBuildOrder(state);
106347     }
106348     function createStateBuildOrder(state) {
106349         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
106350         // Clear all to ResolvedConfigFilePaths cache to start fresh
106351         state.resolvedConfigFilePaths.clear();
106352         var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
106353         var noopOnDelete = { onDeleteValue: ts.noop };
106354         // Config file cache
106355         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
106356         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
106357         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
106358         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
106359         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
106360         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
106361         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
106362         // Remove watches for the program no longer in the solution
106363         if (state.watch) {
106364             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
106365             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
106366             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
106367         }
106368         return state.buildOrder = buildOrder;
106369     }
106370     function getBuildOrderFor(state, project, onlyReferences) {
106371         var resolvedProject = project && resolveProjectName(state, project);
106372         var buildOrderFromState = getBuildOrder(state);
106373         if (isCircularBuildOrder(buildOrderFromState))
106374             return buildOrderFromState;
106375         if (resolvedProject) {
106376             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
106377             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
106378             if (projectIndex === -1)
106379                 return undefined;
106380         }
106381         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
106382         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
106383         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
106384         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
106385         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
106386     }
106387     function enableCache(state) {
106388         if (state.cache) {
106389             disableCache(state);
106390         }
106391         var compilerHost = state.compilerHost, host = state.host;
106392         var originalReadFileWithCache = state.readFileWithCache;
106393         var originalGetSourceFile = compilerHost.getSourceFile;
106394         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
106395             var args = [];
106396             for (var _i = 0; _i < arguments.length; _i++) {
106397                 args[_i] = arguments[_i];
106398             }
106399             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
106400         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
106401         state.readFileWithCache = readFileWithCache;
106402         compilerHost.getSourceFile = getSourceFileWithCache;
106403         state.cache = {
106404             originalReadFile: originalReadFile,
106405             originalFileExists: originalFileExists,
106406             originalDirectoryExists: originalDirectoryExists,
106407             originalCreateDirectory: originalCreateDirectory,
106408             originalWriteFile: originalWriteFile,
106409             originalReadFileWithCache: originalReadFileWithCache,
106410             originalGetSourceFile: originalGetSourceFile,
106411         };
106412     }
106413     function disableCache(state) {
106414         if (!state.cache)
106415             return;
106416         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
106417         host.readFile = cache.originalReadFile;
106418         host.fileExists = cache.originalFileExists;
106419         host.directoryExists = cache.originalDirectoryExists;
106420         host.createDirectory = cache.originalCreateDirectory;
106421         host.writeFile = cache.originalWriteFile;
106422         compilerHost.getSourceFile = cache.originalGetSourceFile;
106423         state.readFileWithCache = cache.originalReadFileWithCache;
106424         extendedConfigCache.clear();
106425         if (moduleResolutionCache) {
106426             moduleResolutionCache.directoryToModuleNameMap.clear();
106427             moduleResolutionCache.moduleNameToDirectoryMap.clear();
106428         }
106429         state.cache = undefined;
106430     }
106431     function clearProjectStatus(state, resolved) {
106432         state.projectStatus.delete(resolved);
106433         state.diagnostics.delete(resolved);
106434     }
106435     function addProjToQueue(_a, proj, reloadLevel) {
106436         var projectPendingBuild = _a.projectPendingBuild;
106437         var value = projectPendingBuild.get(proj);
106438         if (value === undefined) {
106439             projectPendingBuild.set(proj, reloadLevel);
106440         }
106441         else if (value < reloadLevel) {
106442             projectPendingBuild.set(proj, reloadLevel);
106443         }
106444     }
106445     function setupInitialBuild(state, cancellationToken) {
106446         // Set initial build if not already built
106447         if (!state.allProjectBuildPending)
106448             return;
106449         state.allProjectBuildPending = false;
106450         if (state.options.watch) {
106451             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
106452         }
106453         enableCache(state);
106454         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
106455         buildOrder.forEach(function (configFileName) {
106456             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
106457         });
106458         if (cancellationToken) {
106459             cancellationToken.throwIfCancellationRequested();
106460         }
106461     }
106462     var InvalidatedProjectKind;
106463     (function (InvalidatedProjectKind) {
106464         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
106465         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
106466         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
106467     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
106468     function doneInvalidatedProject(state, projectPath) {
106469         state.projectPendingBuild.delete(projectPath);
106470         state.currentInvalidatedProject = undefined;
106471         return state.diagnostics.has(projectPath) ?
106472             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
106473             ts.ExitStatus.Success;
106474     }
106475     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
106476         var updateOutputFileStampsPending = true;
106477         return {
106478             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
106479             project: project,
106480             projectPath: projectPath,
106481             buildOrder: buildOrder,
106482             getCompilerOptions: function () { return config.options; },
106483             getCurrentDirectory: function () { return state.currentDirectory; },
106484             updateOutputFileStatmps: function () {
106485                 updateOutputTimestamps(state, config, projectPath);
106486                 updateOutputFileStampsPending = false;
106487             },
106488             done: function () {
106489                 if (updateOutputFileStampsPending) {
106490                     updateOutputTimestamps(state, config, projectPath);
106491                 }
106492                 return doneInvalidatedProject(state, projectPath);
106493             }
106494         };
106495     }
106496     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
106497         var Step;
106498         (function (Step) {
106499             Step[Step["CreateProgram"] = 0] = "CreateProgram";
106500             Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
106501             Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
106502             Step[Step["Emit"] = 3] = "Emit";
106503             Step[Step["EmitBundle"] = 4] = "EmitBundle";
106504             Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
106505             Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
106506             Step[Step["Done"] = 7] = "Done";
106507         })(Step || (Step = {}));
106508         var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
106509         var program;
106510         var buildResult;
106511         var invalidatedProjectOfBundle;
106512         return kind === InvalidatedProjectKind.Build ?
106513             {
106514                 kind: kind,
106515                 project: project,
106516                 projectPath: projectPath,
106517                 buildOrder: buildOrder,
106518                 getCompilerOptions: function () { return config.options; },
106519                 getCurrentDirectory: function () { return state.currentDirectory; },
106520                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
106521                 getProgram: function () {
106522                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
106523                 },
106524                 getSourceFile: function (fileName) {
106525                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
106526                 },
106527                 getSourceFiles: function () {
106528                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
106529                 },
106530                 getOptionsDiagnostics: function (cancellationToken) {
106531                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
106532                 },
106533                 getGlobalDiagnostics: function (cancellationToken) {
106534                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
106535                 },
106536                 getConfigFileParsingDiagnostics: function () {
106537                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
106538                 },
106539                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
106540                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
106541                 },
106542                 getAllDependencies: function (sourceFile) {
106543                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
106544                 },
106545                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
106546                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
106547                 },
106548                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
106549                     return withProgramOrUndefined(function (program) {
106550                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
106551                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
106552                     });
106553                 },
106554                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106555                     if (targetSourceFile || emitOnlyDtsFiles) {
106556                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
106557                     }
106558                     executeSteps(Step.SemanticDiagnostics, cancellationToken);
106559                     if (step !== Step.Emit)
106560                         return undefined;
106561                     return emit(writeFile, cancellationToken, customTransformers);
106562                 },
106563                 done: done
106564             } :
106565             {
106566                 kind: kind,
106567                 project: project,
106568                 projectPath: projectPath,
106569                 buildOrder: buildOrder,
106570                 getCompilerOptions: function () { return config.options; },
106571                 getCurrentDirectory: function () { return state.currentDirectory; },
106572                 emit: function (writeFile, customTransformers) {
106573                     if (step !== Step.EmitBundle)
106574                         return invalidatedProjectOfBundle;
106575                     return emitBundle(writeFile, customTransformers);
106576                 },
106577                 done: done,
106578             };
106579         function done(cancellationToken, writeFile, customTransformers) {
106580             executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
106581             return doneInvalidatedProject(state, projectPath);
106582         }
106583         function withProgramOrUndefined(action) {
106584             executeSteps(Step.CreateProgram);
106585             return program && action(program);
106586         }
106587         function withProgramOrEmptyArray(action) {
106588             return withProgramOrUndefined(action) || ts.emptyArray;
106589         }
106590         function createProgram() {
106591             ts.Debug.assert(program === undefined);
106592             if (state.options.dry) {
106593                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
106594                 buildResult = BuildResultFlags.Success;
106595                 step = Step.QueueReferencingProjects;
106596                 return;
106597             }
106598             if (state.options.verbose)
106599                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
106600             if (config.fileNames.length === 0) {
106601                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106602                 // Nothing to build - must be a solution file, basically
106603                 buildResult = BuildResultFlags.None;
106604                 step = Step.QueueReferencingProjects;
106605                 return;
106606             }
106607             var host = state.host, compilerHost = state.compilerHost;
106608             state.projectCompilerOptions = config.options;
106609             // Update module resolution cache if needed
106610             updateModuleResolutionCache(state, project, config);
106611             // Create program
106612             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
106613             step++;
106614         }
106615         function handleDiagnostics(diagnostics, errorFlags, errorType) {
106616             if (diagnostics.length) {
106617                 buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
106618                 step = Step.QueueReferencingProjects;
106619             }
106620             else {
106621                 step++;
106622             }
106623         }
106624         function getSyntaxDiagnostics(cancellationToken) {
106625             ts.Debug.assertIsDefined(program);
106626             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
106627         }
106628         function getSemanticDiagnostics(cancellationToken) {
106629             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
106630         }
106631         function emit(writeFileCallback, cancellationToken, customTransformers) {
106632             ts.Debug.assertIsDefined(program);
106633             ts.Debug.assert(step === Step.Emit);
106634             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
106635             program.backupState();
106636             var declDiagnostics;
106637             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
106638             var outputFiles = [];
106639             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
106640             /*writeFileName*/ undefined, 
106641             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
106642             /*emitOnlyDts*/ false, customTransformers).emitResult;
106643             // Don't emit .d.ts if there are decl file errors
106644             if (declDiagnostics) {
106645                 program.restoreState();
106646                 buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
106647                 step = Step.QueueReferencingProjects;
106648                 return {
106649                     emitSkipped: true,
106650                     diagnostics: emitResult.diagnostics
106651                 };
106652             }
106653             // Actual Emit
106654             var host = state.host, compilerHost = state.compilerHost;
106655             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
106656             var newestDeclarationFileContentChangedTime = minimumDate;
106657             var anyDtsChanged = false;
106658             var emitterDiagnostics = ts.createDiagnosticCollection();
106659             var emittedOutputs = ts.createMap();
106660             outputFiles.forEach(function (_a) {
106661                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106662                 var priorChangeTime;
106663                 if (!anyDtsChanged && isDeclarationFile(name)) {
106664                     // Check for unchanged .d.ts files
106665                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
106666                         priorChangeTime = host.getModifiedTime(name);
106667                     }
106668                     else {
106669                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
106670                         anyDtsChanged = true;
106671                     }
106672                 }
106673                 emittedOutputs.set(toPath(state, name), name);
106674                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106675                 if (priorChangeTime !== undefined) {
106676                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
106677                 }
106678             });
106679             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
106680             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
106681             return emitResult;
106682         }
106683         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
106684             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
106685             if (emitDiagnostics.length) {
106686                 buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
106687                 step = Step.QueueReferencingProjects;
106688                 return emitDiagnostics;
106689             }
106690             if (state.writeFileName) {
106691                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
106692                 if (program)
106693                     ts.listFiles(program, state.writeFileName);
106694             }
106695             // Update time stamps for rest of the outputs
106696             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
106697             state.diagnostics.delete(projectPath);
106698             state.projectStatus.set(projectPath, {
106699                 type: ts.UpToDateStatusType.UpToDate,
106700                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
106701                     maximumDate :
106702                     newestDeclarationFileContentChangedTime,
106703                 oldestOutputFileName: oldestOutputFileName
106704             });
106705             afterProgramDone(state, projectPath, program, config);
106706             state.projectCompilerOptions = state.baseCompilerOptions;
106707             step = Step.QueueReferencingProjects;
106708             buildResult = resultFlags;
106709             return emitDiagnostics;
106710         }
106711         function emitBundle(writeFileCallback, customTransformers) {
106712             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
106713             if (state.options.dry) {
106714                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
106715                 buildResult = BuildResultFlags.Success;
106716                 step = Step.QueueReferencingProjects;
106717                 return undefined;
106718             }
106719             if (state.options.verbose)
106720                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
106721             // Update js, and source map
106722             var compilerHost = state.compilerHost;
106723             state.projectCompilerOptions = config.options;
106724             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
106725                 var refName = resolveProjectName(state, ref.path);
106726                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
106727             }, customTransformers);
106728             if (ts.isString(outputFiles)) {
106729                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
106730                 step = Step.BuildInvalidatedProjectOfBundle;
106731                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
106732             }
106733             // Actual Emit
106734             ts.Debug.assert(!!outputFiles.length);
106735             var emitterDiagnostics = ts.createDiagnosticCollection();
106736             var emittedOutputs = ts.createMap();
106737             outputFiles.forEach(function (_a) {
106738                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106739                 emittedOutputs.set(toPath(state, name), name);
106740                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106741             });
106742             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
106743             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
106744             return { emitSkipped: false, diagnostics: emitDiagnostics };
106745         }
106746         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
106747             while (step <= till && step < Step.Done) {
106748                 var currentStep = step;
106749                 switch (step) {
106750                     case Step.CreateProgram:
106751                         createProgram();
106752                         break;
106753                     case Step.SyntaxDiagnostics:
106754                         getSyntaxDiagnostics(cancellationToken);
106755                         break;
106756                     case Step.SemanticDiagnostics:
106757                         getSemanticDiagnostics(cancellationToken);
106758                         break;
106759                     case Step.Emit:
106760                         emit(writeFile, cancellationToken, customTransformers);
106761                         break;
106762                     case Step.EmitBundle:
106763                         emitBundle(writeFile, customTransformers);
106764                         break;
106765                     case Step.BuildInvalidatedProjectOfBundle:
106766                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
106767                         step = Step.Done;
106768                         break;
106769                     case Step.QueueReferencingProjects:
106770                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
106771                         step++;
106772                         break;
106773                     // Should never be done
106774                     case Step.Done:
106775                     default:
106776                         ts.assertType(step);
106777                 }
106778                 ts.Debug.assert(step > currentStep);
106779             }
106780         }
106781     }
106782     function needsBuild(_a, status, config) {
106783         var options = _a.options;
106784         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
106785             return true;
106786         return config.fileNames.length === 0 ||
106787             !!ts.getConfigFileParsingDiagnostics(config).length ||
106788             !ts.isIncrementalCompilation(config.options);
106789     }
106790     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
106791         if (!state.projectPendingBuild.size)
106792             return undefined;
106793         if (isCircularBuildOrder(buildOrder))
106794             return undefined;
106795         if (state.currentInvalidatedProject) {
106796             // Only if same buildOrder the currentInvalidated project can be sent again
106797             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
106798                 state.currentInvalidatedProject :
106799                 undefined;
106800         }
106801         var options = state.options, projectPendingBuild = state.projectPendingBuild;
106802         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
106803             var project = buildOrder[projectIndex];
106804             var projectPath = toResolvedConfigFilePath(state, project);
106805             var reloadLevel = state.projectPendingBuild.get(projectPath);
106806             if (reloadLevel === undefined)
106807                 continue;
106808             if (reportQueue) {
106809                 reportQueue = false;
106810                 reportBuildQueue(state, buildOrder);
106811             }
106812             var config = parseConfigFile(state, project, projectPath);
106813             if (!config) {
106814                 reportParseConfigFileDiagnostic(state, projectPath);
106815                 projectPendingBuild.delete(projectPath);
106816                 continue;
106817             }
106818             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
106819                 watchConfigFile(state, project, projectPath, config);
106820                 watchWildCardDirectories(state, project, projectPath, config);
106821                 watchInputFiles(state, project, projectPath, config);
106822             }
106823             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
106824                 // Update file names
106825                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
106826                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
106827                 config.fileNames = result.fileNames;
106828                 watchInputFiles(state, project, projectPath, config);
106829             }
106830             var status = getUpToDateStatus(state, config, projectPath);
106831             verboseReportProjectStatus(state, project, status);
106832             if (!options.force) {
106833                 if (status.type === ts.UpToDateStatusType.UpToDate) {
106834                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106835                     projectPendingBuild.delete(projectPath);
106836                     // Up to date, skip
106837                     if (options.dry) {
106838                         // In a dry build, inform the user of this fact
106839                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
106840                     }
106841                     continue;
106842                 }
106843                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
106844                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106845                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
106846                 }
106847             }
106848             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
106849                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106850                 projectPendingBuild.delete(projectPath);
106851                 if (options.verbose) {
106852                     reportStatus(state, status.upstreamProjectBlocked ?
106853                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
106854                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
106855                 }
106856                 continue;
106857             }
106858             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
106859                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106860                 projectPendingBuild.delete(projectPath);
106861                 // Do nothing
106862                 continue;
106863             }
106864             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
106865                 InvalidatedProjectKind.Build :
106866                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
106867         }
106868         return undefined;
106869     }
106870     function listEmittedFile(_a, proj, file) {
106871         var writeFileName = _a.writeFileName;
106872         if (writeFileName && proj.options.listEmittedFiles) {
106873             writeFileName("TSFILE: " + file);
106874         }
106875     }
106876     function getOldProgram(_a, proj, parsed) {
106877         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
106878         if (options.force)
106879             return undefined;
106880         var value = builderPrograms.get(proj);
106881         if (value)
106882             return value;
106883         return ts.readBuilderProgram(parsed.options, compilerHost);
106884     }
106885     function afterProgramDone(_a, proj, program, config) {
106886         var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
106887         if (program) {
106888             if (host.afterProgramEmitAndDiagnostics) {
106889                 host.afterProgramEmitAndDiagnostics(program);
106890             }
106891             if (watch) {
106892                 program.releaseProgram();
106893                 builderPrograms.set(proj, program);
106894             }
106895         }
106896         else if (host.afterEmitBundle) {
106897             host.afterEmitBundle(config);
106898         }
106899     }
106900     function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
106901         reportAndStoreErrors(state, resolvedPath, diagnostics);
106902         // List files if any other build error using program (emit errors already report files)
106903         if (program && state.writeFileName)
106904             ts.listFiles(program, state.writeFileName);
106905         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
106906         afterProgramDone(state, resolvedPath, program, config);
106907         state.projectCompilerOptions = state.baseCompilerOptions;
106908         return errorFlags;
106909     }
106910     function updateModuleResolutionCache(state, proj, config) {
106911         if (!state.moduleResolutionCache)
106912             return;
106913         // Update module resolution cache if needed
106914         var moduleResolutionCache = state.moduleResolutionCache;
106915         var projPath = toPath(state, proj);
106916         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
106917             // The own map will be for projectCompilerOptions
106918             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
106919             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
106920             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
106921         }
106922         else {
106923             // Set correct own map
106924             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
106925             var ref = {
106926                 sourceFile: config.options.configFile,
106927                 commandLine: config
106928             };
106929             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
106930             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
106931         }
106932         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
106933         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
106934     }
106935     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
106936         // Check tsconfig time
106937         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
106938         if (oldestOutputFileTime < tsconfigTime) {
106939             return {
106940                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106941                 outOfDateOutputFileName: oldestOutputFileName,
106942                 newerInputFileName: configFile
106943             };
106944         }
106945     }
106946     function getUpToDateStatusWorker(state, project, resolvedPath) {
106947         var newestInputFileName = undefined;
106948         var newestInputFileTime = minimumDate;
106949         var host = state.host;
106950         // Get timestamps of input files
106951         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
106952             var inputFile = _a[_i];
106953             if (!host.fileExists(inputFile)) {
106954                 return {
106955                     type: ts.UpToDateStatusType.Unbuildable,
106956                     reason: inputFile + " does not exist"
106957                 };
106958             }
106959             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
106960             if (inputTime > newestInputFileTime) {
106961                 newestInputFileName = inputFile;
106962                 newestInputFileTime = inputTime;
106963             }
106964         }
106965         // Container if no files are specified in the project
106966         if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
106967             return {
106968                 type: ts.UpToDateStatusType.ContainerOnly
106969             };
106970         }
106971         // Collect the expected outputs of this project
106972         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
106973         // Now see if all outputs are newer than the newest input
106974         var oldestOutputFileName = "(none)";
106975         var oldestOutputFileTime = maximumDate;
106976         var newestOutputFileName = "(none)";
106977         var newestOutputFileTime = minimumDate;
106978         var missingOutputFileName;
106979         var newestDeclarationFileContentChangedTime = minimumDate;
106980         var isOutOfDateWithInputs = false;
106981         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
106982             var output = outputs_1[_b];
106983             // Output is missing; can stop checking
106984             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106985             if (!host.fileExists(output)) {
106986                 missingOutputFileName = output;
106987                 break;
106988             }
106989             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106990             if (outputTime < oldestOutputFileTime) {
106991                 oldestOutputFileTime = outputTime;
106992                 oldestOutputFileName = output;
106993             }
106994             // If an output is older than the newest input, we can stop checking
106995             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106996             if (outputTime < newestInputFileTime) {
106997                 isOutOfDateWithInputs = true;
106998                 break;
106999             }
107000             if (outputTime > newestOutputFileTime) {
107001                 newestOutputFileTime = outputTime;
107002                 newestOutputFileName = output;
107003             }
107004             // Keep track of when the most recent time a .d.ts file was changed.
107005             // In addition to file timestamps, we also keep track of when a .d.ts file
107006             // had its file touched but not had its contents changed - this allows us
107007             // to skip a downstream typecheck
107008             if (isDeclarationFile(output)) {
107009                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
107010                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
107011             }
107012         }
107013         var pseudoUpToDate = false;
107014         var usesPrepend = false;
107015         var upstreamChangedProject;
107016         if (project.projectReferences) {
107017             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
107018             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
107019                 var ref = _d[_c];
107020                 usesPrepend = usesPrepend || !!(ref.prepend);
107021                 var resolvedRef = ts.resolveProjectReferencePath(ref);
107022                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
107023                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
107024                 // Its a circular reference ignore the status of this project
107025                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
107026                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
107027                     continue;
107028                 }
107029                 // An upstream project is blocked
107030                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
107031                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
107032                     return {
107033                         type: ts.UpToDateStatusType.UpstreamBlocked,
107034                         upstreamProjectName: ref.path,
107035                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
107036                     };
107037                 }
107038                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
107039                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
107040                     return {
107041                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
107042                         upstreamProjectName: ref.path
107043                     };
107044                 }
107045                 // Check oldest output file name only if there is no missing output file name
107046                 if (!missingOutputFileName) {
107047                     // If the upstream project's newest file is older than our oldest output, we
107048                     // can't be out of date because of it
107049                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
107050                         continue;
107051                     }
107052                     // If the upstream project has only change .d.ts files, and we've built
107053                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
107054                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
107055                         pseudoUpToDate = true;
107056                         upstreamChangedProject = ref.path;
107057                         continue;
107058                     }
107059                     // We have an output older than an upstream output - we are out of date
107060                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
107061                     return {
107062                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107063                         outOfDateOutputFileName: oldestOutputFileName,
107064                         newerProjectName: ref.path
107065                     };
107066                 }
107067             }
107068         }
107069         if (missingOutputFileName !== undefined) {
107070             return {
107071                 type: ts.UpToDateStatusType.OutputMissing,
107072                 missingOutputFileName: missingOutputFileName
107073             };
107074         }
107075         if (isOutOfDateWithInputs) {
107076             return {
107077                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
107078                 outOfDateOutputFileName: oldestOutputFileName,
107079                 newerInputFileName: newestInputFileName
107080             };
107081         }
107082         else {
107083             // Check tsconfig time
107084             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
107085             if (configStatus)
107086                 return configStatus;
107087             // Check extended config time
107088             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
107089             if (extendedConfigStatus)
107090                 return extendedConfigStatus;
107091         }
107092         if (!state.buildInfoChecked.has(resolvedPath)) {
107093             state.buildInfoChecked.set(resolvedPath, true);
107094             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
107095             if (buildInfoPath) {
107096                 var value = state.readFileWithCache(buildInfoPath);
107097                 var buildInfo = value && ts.getBuildInfo(value);
107098                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
107099                     return {
107100                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
107101                         version: buildInfo.version
107102                     };
107103                 }
107104             }
107105         }
107106         if (usesPrepend && pseudoUpToDate) {
107107             return {
107108                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107109                 outOfDateOutputFileName: oldestOutputFileName,
107110                 newerProjectName: upstreamChangedProject
107111             };
107112         }
107113         // Up to date
107114         return {
107115             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
107116             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
107117             newestInputFileTime: newestInputFileTime,
107118             newestOutputFileTime: newestOutputFileTime,
107119             newestInputFileName: newestInputFileName,
107120             newestOutputFileName: newestOutputFileName,
107121             oldestOutputFileName: oldestOutputFileName
107122         };
107123     }
107124     function getUpToDateStatus(state, project, resolvedPath) {
107125         if (project === undefined) {
107126             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
107127         }
107128         var prior = state.projectStatus.get(resolvedPath);
107129         if (prior !== undefined) {
107130             return prior;
107131         }
107132         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
107133         state.projectStatus.set(resolvedPath, actual);
107134         return actual;
107135     }
107136     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
107137         var host = state.host;
107138         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
107139         if (!skipOutputs || outputs.length !== skipOutputs.size) {
107140             var reportVerbose = !!state.options.verbose;
107141             var now = host.now ? host.now() : new Date();
107142             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
107143                 var file = outputs_2[_i];
107144                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
107145                     continue;
107146                 }
107147                 if (reportVerbose) {
107148                     reportVerbose = false;
107149                     reportStatus(state, verboseMessage, proj.options.configFilePath);
107150                 }
107151                 if (isDeclarationFile(file)) {
107152                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
107153                 }
107154                 host.setModifiedTime(file, now);
107155             }
107156         }
107157         return priorNewestUpdateTime;
107158     }
107159     function updateOutputTimestamps(state, proj, resolvedPath) {
107160         if (state.options.dry) {
107161             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
107162         }
107163         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
107164         state.projectStatus.set(resolvedPath, {
107165             type: ts.UpToDateStatusType.UpToDate,
107166             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
107167             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
107168         });
107169     }
107170     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
107171         // Queue only if there are no errors
107172         if (buildResult & BuildResultFlags.AnyErrors)
107173             return;
107174         // Only composite projects can be referenced by other projects
107175         if (!config.options.composite)
107176             return;
107177         // Always use build order to queue projects
107178         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
107179             var nextProject = buildOrder[index];
107180             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
107181             if (state.projectPendingBuild.has(nextProjectPath))
107182                 continue;
107183             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
107184             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
107185                 continue;
107186             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
107187                 var ref = _a[_i];
107188                 var resolvedRefPath = resolveProjectName(state, ref.path);
107189                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
107190                     continue;
107191                 // If the project is referenced with prepend, always build downstream projects,
107192                 // If declaration output is changed, build the project
107193                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
107194                 var status = state.projectStatus.get(nextProjectPath);
107195                 if (status) {
107196                     switch (status.type) {
107197                         case ts.UpToDateStatusType.UpToDate:
107198                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
107199                                 if (ref.prepend) {
107200                                     state.projectStatus.set(nextProjectPath, {
107201                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107202                                         outOfDateOutputFileName: status.oldestOutputFileName,
107203                                         newerProjectName: project
107204                                     });
107205                                 }
107206                                 else {
107207                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
107208                                 }
107209                                 break;
107210                             }
107211                         // falls through
107212                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107213                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
107214                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
107215                                 state.projectStatus.set(nextProjectPath, {
107216                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107217                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
107218                                     newerProjectName: project
107219                                 });
107220                             }
107221                             break;
107222                         case ts.UpToDateStatusType.UpstreamBlocked:
107223                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
107224                                 clearProjectStatus(state, nextProjectPath);
107225                             }
107226                             break;
107227                     }
107228                 }
107229                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
107230                 break;
107231             }
107232         }
107233     }
107234     function build(state, project, cancellationToken, onlyReferences) {
107235         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107236         if (!buildOrder)
107237             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107238         setupInitialBuild(state, cancellationToken);
107239         var reportQueue = true;
107240         var successfulProjects = 0;
107241         while (true) {
107242             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
107243             if (!invalidatedProject)
107244                 break;
107245             reportQueue = false;
107246             invalidatedProject.done(cancellationToken);
107247             if (!state.diagnostics.has(invalidatedProject.projectPath))
107248                 successfulProjects++;
107249         }
107250         disableCache(state);
107251         reportErrorSummary(state, buildOrder);
107252         startWatching(state, buildOrder);
107253         return isCircularBuildOrder(buildOrder)
107254             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
107255             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
107256                 ? ts.ExitStatus.Success
107257                 : successfulProjects
107258                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
107259                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
107260     }
107261     function clean(state, project, onlyReferences) {
107262         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107263         if (!buildOrder)
107264             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107265         if (isCircularBuildOrder(buildOrder)) {
107266             reportErrors(state, buildOrder.circularDiagnostics);
107267             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
107268         }
107269         var options = state.options, host = state.host;
107270         var filesToDelete = options.dry ? [] : undefined;
107271         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
107272             var proj = buildOrder_1[_i];
107273             var resolvedPath = toResolvedConfigFilePath(state, proj);
107274             var parsed = parseConfigFile(state, proj, resolvedPath);
107275             if (parsed === undefined) {
107276                 // File has gone missing; fine to ignore here
107277                 reportParseConfigFileDiagnostic(state, resolvedPath);
107278                 continue;
107279             }
107280             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
107281             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
107282                 var output = outputs_3[_a];
107283                 if (host.fileExists(output)) {
107284                     if (filesToDelete) {
107285                         filesToDelete.push(output);
107286                     }
107287                     else {
107288                         host.deleteFile(output);
107289                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
107290                     }
107291                 }
107292             }
107293         }
107294         if (filesToDelete) {
107295             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
107296         }
107297         return ts.ExitStatus.Success;
107298     }
107299     function invalidateProject(state, resolved, reloadLevel) {
107300         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
107301         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
107302             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
107303         }
107304         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
107305             state.configFileCache.delete(resolved);
107306             state.buildOrder = undefined;
107307         }
107308         state.needsSummary = true;
107309         clearProjectStatus(state, resolved);
107310         addProjToQueue(state, resolved, reloadLevel);
107311         enableCache(state);
107312     }
107313     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
107314         state.reportFileChangeDetected = true;
107315         invalidateProject(state, resolvedPath, reloadLevel);
107316         scheduleBuildInvalidatedProject(state);
107317     }
107318     function scheduleBuildInvalidatedProject(state) {
107319         var hostWithWatch = state.hostWithWatch;
107320         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
107321             return;
107322         }
107323         if (state.timerToBuildInvalidatedProject) {
107324             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
107325         }
107326         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
107327     }
107328     function buildNextInvalidatedProject(state) {
107329         state.timerToBuildInvalidatedProject = undefined;
107330         if (state.reportFileChangeDetected) {
107331             state.reportFileChangeDetected = false;
107332             state.projectErrorsReported.clear();
107333             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
107334         }
107335         var buildOrder = getBuildOrder(state);
107336         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
107337         if (invalidatedProject) {
107338             invalidatedProject.done();
107339             if (state.projectPendingBuild.size) {
107340                 // Schedule next project for build
107341                 if (state.watch && !state.timerToBuildInvalidatedProject) {
107342                     scheduleBuildInvalidatedProject(state);
107343                 }
107344                 return;
107345             }
107346         }
107347         disableCache(state);
107348         reportErrorSummary(state, buildOrder);
107349     }
107350     function watchConfigFile(state, resolved, resolvedPath, parsed) {
107351         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
107352             return;
107353         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
107354             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
107355         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
107356     }
107357     function isSameFile(state, file1, file2) {
107358         return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107359     }
107360     function isOutputFile(state, fileName, configFile) {
107361         if (configFile.options.noEmit)
107362             return false;
107363         // ts or tsx files are not output
107364         if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
107365             (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
107366             return false;
107367         }
107368         // If options have --outFile or --out, check if its that
107369         var out = configFile.options.outFile || configFile.options.out;
107370         if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
107371             return true;
107372         }
107373         // If declarationDir is specified, return if its a file in that directory
107374         if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107375             return true;
107376         }
107377         // If --outDir, check if file is in that directory
107378         if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107379             return true;
107380         }
107381         return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
107382     }
107383     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
107384         if (!state.watch)
107385             return;
107386         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
107387             var fileOrDirectoryPath = toPath(state, fileOrDirectory);
107388             if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
107389                 state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
107390                 return;
107391             }
107392             if (isOutputFile(state, fileOrDirectory, parsed)) {
107393                 state.writeLog(fileOrDirectory + " is output file");
107394                 return;
107395             }
107396             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
107397         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
107398     }
107399     function watchInputFiles(state, resolved, resolvedPath, parsed) {
107400         if (!state.watch)
107401             return;
107402         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
107403             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); },
107404             onDeleteValue: ts.closeFileWatcher,
107405         });
107406     }
107407     function startWatching(state, buildOrder) {
107408         if (!state.watchAllProjectsPending)
107409             return;
107410         state.watchAllProjectsPending = false;
107411         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
107412             var resolved = _a[_i];
107413             var resolvedPath = toResolvedConfigFilePath(state, resolved);
107414             var cfg = parseConfigFile(state, resolved, resolvedPath);
107415             // Watch this file
107416             watchConfigFile(state, resolved, resolvedPath, cfg);
107417             if (cfg) {
107418                 // Update watchers for wildcard directories
107419                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
107420                 // Watch input files
107421                 watchInputFiles(state, resolved, resolvedPath, cfg);
107422             }
107423         }
107424     }
107425     function stopWatching(state) {
107426         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
107427         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
107428         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
107429     }
107430     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
107431         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
107432         return {
107433             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
107434             clean: function (project) { return clean(state, project); },
107435             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
107436             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
107437             getNextInvalidatedProject: function (cancellationToken) {
107438                 setupInitialBuild(state, cancellationToken);
107439                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
107440             },
107441             getBuildOrder: function () { return getBuildOrder(state); },
107442             getUpToDateStatusOfProject: function (project) {
107443                 var configFileName = resolveProjectName(state, project);
107444                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
107445                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
107446             },
107447             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
107448             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
107449             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
107450             close: function () { return stopWatching(state); },
107451         };
107452     }
107453     function relName(state, path) {
107454         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
107455     }
107456     function reportStatus(state, message) {
107457         var args = [];
107458         for (var _i = 2; _i < arguments.length; _i++) {
107459             args[_i - 2] = arguments[_i];
107460         }
107461         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107462     }
107463     function reportWatchStatus(state, message) {
107464         var args = [];
107465         for (var _i = 2; _i < arguments.length; _i++) {
107466             args[_i - 2] = arguments[_i];
107467         }
107468         if (state.hostWithWatch.onWatchStatusChange) {
107469             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
107470         }
107471     }
107472     function reportErrors(_a, errors) {
107473         var host = _a.host;
107474         errors.forEach(function (err) { return host.reportDiagnostic(err); });
107475     }
107476     function reportAndStoreErrors(state, proj, errors) {
107477         reportErrors(state, errors);
107478         state.projectErrorsReported.set(proj, true);
107479         if (errors.length) {
107480             state.diagnostics.set(proj, errors);
107481         }
107482     }
107483     function reportParseConfigFileDiagnostic(state, proj) {
107484         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
107485     }
107486     function reportErrorSummary(state, buildOrder) {
107487         if (!state.needsSummary)
107488             return;
107489         state.needsSummary = false;
107490         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
107491         var diagnostics = state.diagnostics;
107492         var totalErrors = 0;
107493         if (isCircularBuildOrder(buildOrder)) {
107494             reportBuildQueue(state, buildOrder.buildOrder);
107495             reportErrors(state, buildOrder.circularDiagnostics);
107496             if (canReportSummary)
107497                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
107498         }
107499         else {
107500             // Report errors from the other projects
107501             buildOrder.forEach(function (project) {
107502                 var projectPath = toResolvedConfigFilePath(state, project);
107503                 if (!state.projectErrorsReported.has(projectPath)) {
107504                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
107505                 }
107506             });
107507             if (canReportSummary)
107508                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
107509         }
107510         if (state.watch) {
107511             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
107512         }
107513         else if (state.host.reportErrorSummary) {
107514             state.host.reportErrorSummary(totalErrors);
107515         }
107516     }
107517     /**
107518      * Report the build ordering inferred from the current project graph if we're in verbose mode
107519      */
107520     function reportBuildQueue(state, buildQueue) {
107521         if (state.options.verbose) {
107522             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
107523         }
107524     }
107525     function reportUpToDateStatus(state, configFileName, status) {
107526         switch (status.type) {
107527             case ts.UpToDateStatusType.OutOfDateWithSelf:
107528                 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));
107529             case ts.UpToDateStatusType.OutOfDateWithUpstream:
107530                 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));
107531             case ts.UpToDateStatusType.OutputMissing:
107532                 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));
107533             case ts.UpToDateStatusType.UpToDate:
107534                 if (status.newestInputFileTime !== undefined) {
107535                     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 || ""));
107536                 }
107537                 // Don't report anything for "up to date because it was already built" -- too verbose
107538                 break;
107539             case ts.UpToDateStatusType.OutOfDateWithPrepend:
107540                 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));
107541             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107542                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
107543             case ts.UpToDateStatusType.UpstreamOutOfDate:
107544                 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));
107545             case ts.UpToDateStatusType.UpstreamBlocked:
107546                 return reportStatus(state, status.upstreamProjectBlocked ?
107547                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
107548                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
107549             case ts.UpToDateStatusType.Unbuildable:
107550                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
107551             case ts.UpToDateStatusType.TsVersionOutputOfDate:
107552                 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);
107553             case ts.UpToDateStatusType.ContainerOnly:
107554             // Don't report status on "solution" projects
107555             // falls through
107556             case ts.UpToDateStatusType.ComputingUpstream:
107557                 // Should never leak from getUptoDateStatusWorker
107558                 break;
107559             default:
107560                 ts.assertType(status);
107561         }
107562     }
107563     /**
107564      * Report the up-to-date status of a project if we're in verbose mode
107565      */
107566     function verboseReportProjectStatus(state, configFileName, status) {
107567         if (state.options.verbose) {
107568             reportUpToDateStatus(state, configFileName, status);
107569         }
107570     }
107571 })(ts || (ts = {}));
107572 var ts;
107573 (function (ts) {
107574     var server;
107575     (function (server) {
107576         /* @internal */
107577         server.ActionSet = "action::set";
107578         /* @internal */
107579         server.ActionInvalidate = "action::invalidate";
107580         /* @internal */
107581         server.ActionPackageInstalled = "action::packageInstalled";
107582         /* @internal */
107583         server.EventTypesRegistry = "event::typesRegistry";
107584         /* @internal */
107585         server.EventBeginInstallTypes = "event::beginInstallTypes";
107586         /* @internal */
107587         server.EventEndInstallTypes = "event::endInstallTypes";
107588         /* @internal */
107589         server.EventInitializationFailed = "event::initializationFailed";
107590         /* @internal */
107591         var Arguments;
107592         (function (Arguments) {
107593             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
107594             Arguments.LogFile = "--logFile";
107595             Arguments.EnableTelemetry = "--enableTelemetry";
107596             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
107597             Arguments.TypesMapLocation = "--typesMapLocation";
107598             /**
107599              * This argument specifies the location of the NPM executable.
107600              * typingsInstaller will run the command with `${npmLocation} install ...`.
107601              */
107602             Arguments.NpmLocation = "--npmLocation";
107603             /**
107604              * Flag indicating that the typings installer should try to validate the default npm location.
107605              * If the default npm is not found when this flag is enabled, fallback to `npm install`
107606              */
107607             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
107608         })(Arguments = server.Arguments || (server.Arguments = {}));
107609         /* @internal */
107610         function hasArgument(argumentName) {
107611             return ts.sys.args.indexOf(argumentName) >= 0;
107612         }
107613         server.hasArgument = hasArgument;
107614         /* @internal */
107615         function findArgument(argumentName) {
107616             var index = ts.sys.args.indexOf(argumentName);
107617             return index >= 0 && index < ts.sys.args.length - 1
107618                 ? ts.sys.args[index + 1]
107619                 : undefined;
107620         }
107621         server.findArgument = findArgument;
107622         /* @internal */
107623         function nowString() {
107624             // E.g. "12:34:56.789"
107625             var d = new Date();
107626             return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
107627         }
107628         server.nowString = nowString;
107629     })(server = ts.server || (ts.server = {}));
107630 })(ts || (ts = {}));
107631 /* @internal */
107632 var ts;
107633 (function (ts) {
107634     var JsTyping;
107635     (function (JsTyping) {
107636         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
107637             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
107638             return availableVersion.compareTo(cachedTyping.version) <= 0;
107639         }
107640         JsTyping.isTypingUpToDate = isTypingUpToDate;
107641         JsTyping.nodeCoreModuleList = [
107642             "assert",
107643             "async_hooks",
107644             "buffer",
107645             "child_process",
107646             "cluster",
107647             "console",
107648             "constants",
107649             "crypto",
107650             "dgram",
107651             "dns",
107652             "domain",
107653             "events",
107654             "fs",
107655             "http",
107656             "https",
107657             "http2",
107658             "inspector",
107659             "net",
107660             "os",
107661             "path",
107662             "perf_hooks",
107663             "process",
107664             "punycode",
107665             "querystring",
107666             "readline",
107667             "repl",
107668             "stream",
107669             "string_decoder",
107670             "timers",
107671             "tls",
107672             "tty",
107673             "url",
107674             "util",
107675             "v8",
107676             "vm",
107677             "zlib"
107678         ];
107679         JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
107680         function nonRelativeModuleNameForTypingCache(moduleName) {
107681             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
107682         }
107683         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
107684         function loadSafeList(host, safeListPath) {
107685             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
107686             return ts.createMapFromTemplate(result.config);
107687         }
107688         JsTyping.loadSafeList = loadSafeList;
107689         function loadTypesMap(host, typesMapPath) {
107690             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
107691             if (result.config) {
107692                 return ts.createMapFromTemplate(result.config.simpleMap);
107693             }
107694             return undefined;
107695         }
107696         JsTyping.loadTypesMap = loadTypesMap;
107697         /**
107698          * @param host is the object providing I/O related operations.
107699          * @param fileNames are the file names that belong to the same project
107700          * @param projectRootPath is the path to the project root directory
107701          * @param safeListPath is the path used to retrieve the safe list
107702          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
107703          * @param typeAcquisition is used to customize the typing acquisition process
107704          * @param compilerOptions are used as a source for typing inference
107705          */
107706         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
107707             if (!typeAcquisition || !typeAcquisition.enable) {
107708                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
107709             }
107710             // A typing name to typing file path mapping
107711             var inferredTypings = ts.createMap();
107712             // Only infer typings for .js and .jsx files
107713             fileNames = ts.mapDefined(fileNames, function (fileName) {
107714                 var path = ts.normalizePath(fileName);
107715                 if (ts.hasJSFileExtension(path)) {
107716                     return path;
107717                 }
107718             });
107719             var filesToWatch = [];
107720             if (typeAcquisition.include)
107721                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
107722             var exclude = typeAcquisition.exclude || [];
107723             // Directories to search for package.json, bower.json and other typing information
107724             var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
107725             possibleSearchDirs.set(projectRootPath, true);
107726             possibleSearchDirs.forEach(function (_true, searchDir) {
107727                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
107728                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
107729                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
107730                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
107731                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
107732                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
107733                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
107734                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
107735             });
107736             getTypingNamesFromSourceFileNames(fileNames);
107737             // add typings for unresolved imports
107738             if (unresolvedImports) {
107739                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
107740                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
107741             }
107742             // Add the cached typing locations for inferred typings that are already installed
107743             packageNameToTypingLocation.forEach(function (typing, name) {
107744                 var registryEntry = typesRegistry.get(name);
107745                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
107746                     inferredTypings.set(name, typing.typingLocation);
107747                 }
107748             });
107749             // Remove typings that the user has added to the exclude list
107750             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
107751                 var excludeTypingName = exclude_1[_i];
107752                 var didDelete = inferredTypings.delete(excludeTypingName);
107753                 if (didDelete && log)
107754                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
107755             }
107756             var newTypingNames = [];
107757             var cachedTypingPaths = [];
107758             inferredTypings.forEach(function (inferred, typing) {
107759                 if (inferred !== undefined) {
107760                     cachedTypingPaths.push(inferred);
107761                 }
107762                 else {
107763                     newTypingNames.push(typing);
107764                 }
107765             });
107766             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
107767             if (log)
107768                 log("Result: " + JSON.stringify(result));
107769             return result;
107770             function addInferredTyping(typingName) {
107771                 if (!inferredTypings.has(typingName)) {
107772                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
107773                 }
107774             }
107775             function addInferredTypings(typingNames, message) {
107776                 if (log)
107777                     log(message + ": " + JSON.stringify(typingNames));
107778                 ts.forEach(typingNames, addInferredTyping);
107779             }
107780             /**
107781              * Get the typing info from common package manager json files like package.json or bower.json
107782              */
107783             function getTypingNamesFromJson(jsonPath, filesToWatch) {
107784                 if (!host.fileExists(jsonPath)) {
107785                     return;
107786                 }
107787                 filesToWatch.push(jsonPath);
107788                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
107789                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
107790                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
107791             }
107792             /**
107793              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
107794              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
107795              * to the 'angular-route' typing name.
107796              * @param fileNames are the names for source files in the project
107797              */
107798             function getTypingNamesFromSourceFileNames(fileNames) {
107799                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
107800                     if (!ts.hasJSFileExtension(j))
107801                         return undefined;
107802                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
107803                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
107804                     return safeList.get(cleanedTypingName);
107805                 });
107806                 if (fromFileNames.length) {
107807                     addInferredTypings(fromFileNames, "Inferred typings from file names");
107808                 }
107809                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
107810                 if (hasJsxFile) {
107811                     if (log)
107812                         log("Inferred 'react' typings due to presence of '.jsx' extension");
107813                     addInferredTyping("react");
107814                 }
107815             }
107816             /**
107817              * Infer typing names from packages folder (ex: node_module, bower_components)
107818              * @param packagesFolderPath is the path to the packages folder
107819              */
107820             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
107821                 filesToWatch.push(packagesFolderPath);
107822                 // Todo: add support for ModuleResolutionHost too
107823                 if (!host.directoryExists(packagesFolderPath)) {
107824                     return;
107825                 }
107826                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
107827                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
107828                 if (log)
107829                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
107830                 var packageNames = [];
107831                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
107832                     var fileName = fileNames_1[_i];
107833                     var normalizedFileName = ts.normalizePath(fileName);
107834                     var baseFileName = ts.getBaseFileName(normalizedFileName);
107835                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
107836                         continue;
107837                     }
107838                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
107839                     var packageJson = result_1.config;
107840                     // npm 3's package.json contains a "_requiredBy" field
107841                     // we should include all the top level module names for npm 2, and only module names whose
107842                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
107843                     if (baseFileName === "package.json" && packageJson._requiredBy &&
107844                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
107845                         continue;
107846                     }
107847                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
107848                     // to download d.ts files from DefinitelyTyped
107849                     if (!packageJson.name) {
107850                         continue;
107851                     }
107852                     var ownTypes = packageJson.types || packageJson.typings;
107853                     if (ownTypes) {
107854                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
107855                         if (log)
107856                             log("    Package '" + packageJson.name + "' provides its own types.");
107857                         inferredTypings.set(packageJson.name, absolutePath);
107858                     }
107859                     else {
107860                         packageNames.push(packageJson.name);
107861                     }
107862                 }
107863                 addInferredTypings(packageNames, "    Found package names");
107864             }
107865         }
107866         JsTyping.discoverTypings = discoverTypings;
107867         var NameValidationResult;
107868         (function (NameValidationResult) {
107869             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
107870             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
107871             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
107872             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
107873             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
107874             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
107875         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
107876         var maxPackageNameLength = 214;
107877         /**
107878          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
107879          */
107880         function validatePackageName(packageName) {
107881             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
107882         }
107883         JsTyping.validatePackageName = validatePackageName;
107884         function validatePackageNameWorker(packageName, supportScopedPackage) {
107885             if (!packageName) {
107886                 return 1 /* EmptyName */;
107887             }
107888             if (packageName.length > maxPackageNameLength) {
107889                 return 2 /* NameTooLong */;
107890             }
107891             if (packageName.charCodeAt(0) === 46 /* dot */) {
107892                 return 3 /* NameStartsWithDot */;
107893             }
107894             if (packageName.charCodeAt(0) === 95 /* _ */) {
107895                 return 4 /* NameStartsWithUnderscore */;
107896             }
107897             // check if name is scope package like: starts with @ and has one '/' in the middle
107898             // scoped packages are not currently supported
107899             if (supportScopedPackage) {
107900                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
107901                 if (matches) {
107902                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
107903                     if (scopeResult !== 0 /* Ok */) {
107904                         return { name: matches[1], isScopeName: true, result: scopeResult };
107905                     }
107906                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
107907                     if (packageResult !== 0 /* Ok */) {
107908                         return { name: matches[2], isScopeName: false, result: packageResult };
107909                     }
107910                     return 0 /* Ok */;
107911                 }
107912             }
107913             if (encodeURIComponent(packageName) !== packageName) {
107914                 return 5 /* NameContainsNonURISafeCharacters */;
107915             }
107916             return 0 /* Ok */;
107917         }
107918         function renderPackageNameValidationFailure(result, typing) {
107919             return typeof result === "object" ?
107920                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
107921                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
107922         }
107923         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
107924         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
107925             var kind = isScopeName ? "Scope" : "Package";
107926             switch (result) {
107927                 case 1 /* EmptyName */:
107928                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
107929                 case 2 /* NameTooLong */:
107930                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
107931                 case 3 /* NameStartsWithDot */:
107932                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
107933                 case 4 /* NameStartsWithUnderscore */:
107934                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
107935                 case 5 /* NameContainsNonURISafeCharacters */:
107936                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
107937                 case 0 /* Ok */:
107938                     return ts.Debug.fail(); // Shouldn't have called this.
107939                 default:
107940                     throw ts.Debug.assertNever(result);
107941             }
107942         }
107943     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
107944 })(ts || (ts = {}));
107945 var ts;
107946 (function (ts) {
107947     var ScriptSnapshot;
107948     (function (ScriptSnapshot) {
107949         var StringScriptSnapshot = /** @class */ (function () {
107950             function StringScriptSnapshot(text) {
107951                 this.text = text;
107952             }
107953             StringScriptSnapshot.prototype.getText = function (start, end) {
107954                 return start === 0 && end === this.text.length
107955                     ? this.text
107956                     : this.text.substring(start, end);
107957             };
107958             StringScriptSnapshot.prototype.getLength = function () {
107959                 return this.text.length;
107960             };
107961             StringScriptSnapshot.prototype.getChangeRange = function () {
107962                 // Text-based snapshots do not support incremental parsing. Return undefined
107963                 // to signal that to the caller.
107964                 return undefined;
107965             };
107966             return StringScriptSnapshot;
107967         }());
107968         function fromString(text) {
107969             return new StringScriptSnapshot(text);
107970         }
107971         ScriptSnapshot.fromString = fromString;
107972     })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {}));
107973     /* @internal */
107974     var PackageJsonDependencyGroup;
107975     (function (PackageJsonDependencyGroup) {
107976         PackageJsonDependencyGroup[PackageJsonDependencyGroup["Dependencies"] = 1] = "Dependencies";
107977         PackageJsonDependencyGroup[PackageJsonDependencyGroup["DevDependencies"] = 2] = "DevDependencies";
107978         PackageJsonDependencyGroup[PackageJsonDependencyGroup["PeerDependencies"] = 4] = "PeerDependencies";
107979         PackageJsonDependencyGroup[PackageJsonDependencyGroup["OptionalDependencies"] = 8] = "OptionalDependencies";
107980         PackageJsonDependencyGroup[PackageJsonDependencyGroup["All"] = 15] = "All";
107981     })(PackageJsonDependencyGroup = ts.PackageJsonDependencyGroup || (ts.PackageJsonDependencyGroup = {}));
107982     /* @internal */
107983     ts.emptyOptions = {};
107984     var HighlightSpanKind;
107985     (function (HighlightSpanKind) {
107986         HighlightSpanKind["none"] = "none";
107987         HighlightSpanKind["definition"] = "definition";
107988         HighlightSpanKind["reference"] = "reference";
107989         HighlightSpanKind["writtenReference"] = "writtenReference";
107990     })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {}));
107991     var IndentStyle;
107992     (function (IndentStyle) {
107993         IndentStyle[IndentStyle["None"] = 0] = "None";
107994         IndentStyle[IndentStyle["Block"] = 1] = "Block";
107995         IndentStyle[IndentStyle["Smart"] = 2] = "Smart";
107996     })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {}));
107997     var SemicolonPreference;
107998     (function (SemicolonPreference) {
107999         SemicolonPreference["Ignore"] = "ignore";
108000         SemicolonPreference["Insert"] = "insert";
108001         SemicolonPreference["Remove"] = "remove";
108002     })(SemicolonPreference = ts.SemicolonPreference || (ts.SemicolonPreference = {}));
108003     function getDefaultFormatCodeSettings(newLineCharacter) {
108004         return {
108005             indentSize: 4,
108006             tabSize: 4,
108007             newLineCharacter: newLineCharacter || "\n",
108008             convertTabsToSpaces: true,
108009             indentStyle: IndentStyle.Smart,
108010             insertSpaceAfterConstructor: false,
108011             insertSpaceAfterCommaDelimiter: true,
108012             insertSpaceAfterSemicolonInForStatements: true,
108013             insertSpaceBeforeAndAfterBinaryOperators: true,
108014             insertSpaceAfterKeywordsInControlFlowStatements: true,
108015             insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
108016             insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
108017             insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
108018             insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
108019             insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
108020             insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
108021             insertSpaceBeforeFunctionParenthesis: false,
108022             placeOpenBraceOnNewLineForFunctions: false,
108023             placeOpenBraceOnNewLineForControlBlocks: false,
108024             semicolons: SemicolonPreference.Ignore,
108025             trimTrailingWhitespace: true
108026         };
108027     }
108028     ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings;
108029     /* @internal */
108030     ts.testFormatSettings = getDefaultFormatCodeSettings("\n");
108031     var SymbolDisplayPartKind;
108032     (function (SymbolDisplayPartKind) {
108033         SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName";
108034         SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className";
108035         SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName";
108036         SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName";
108037         SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName";
108038         SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword";
108039         SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak";
108040         SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral";
108041         SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral";
108042         SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName";
108043         SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName";
108044         SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName";
108045         SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator";
108046         SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName";
108047         SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName";
108048         SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation";
108049         SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space";
108050         SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text";
108051         SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName";
108052         SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName";
108053         SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
108054         SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
108055     })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
108056     var OutliningSpanKind;
108057     (function (OutliningSpanKind) {
108058         /** Single or multi-line comments */
108059         OutliningSpanKind["Comment"] = "comment";
108060         /** Sections marked by '// #region' and '// #endregion' comments */
108061         OutliningSpanKind["Region"] = "region";
108062         /** Declarations and expressions */
108063         OutliningSpanKind["Code"] = "code";
108064         /** Contiguous blocks of import declarations */
108065         OutliningSpanKind["Imports"] = "imports";
108066     })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
108067     var OutputFileType;
108068     (function (OutputFileType) {
108069         OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
108070         OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap";
108071         OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration";
108072     })(OutputFileType = ts.OutputFileType || (ts.OutputFileType = {}));
108073     var EndOfLineState;
108074     (function (EndOfLineState) {
108075         EndOfLineState[EndOfLineState["None"] = 0] = "None";
108076         EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia";
108077         EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral";
108078         EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral";
108079         EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate";
108080         EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail";
108081         EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition";
108082     })(EndOfLineState = ts.EndOfLineState || (ts.EndOfLineState = {}));
108083     var TokenClass;
108084     (function (TokenClass) {
108085         TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation";
108086         TokenClass[TokenClass["Keyword"] = 1] = "Keyword";
108087         TokenClass[TokenClass["Operator"] = 2] = "Operator";
108088         TokenClass[TokenClass["Comment"] = 3] = "Comment";
108089         TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace";
108090         TokenClass[TokenClass["Identifier"] = 5] = "Identifier";
108091         TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral";
108092         TokenClass[TokenClass["BigIntLiteral"] = 7] = "BigIntLiteral";
108093         TokenClass[TokenClass["StringLiteral"] = 8] = "StringLiteral";
108094         TokenClass[TokenClass["RegExpLiteral"] = 9] = "RegExpLiteral";
108095     })(TokenClass = ts.TokenClass || (ts.TokenClass = {}));
108096     var ScriptElementKind;
108097     (function (ScriptElementKind) {
108098         ScriptElementKind["unknown"] = "";
108099         ScriptElementKind["warning"] = "warning";
108100         /** predefined type (void) or keyword (class) */
108101         ScriptElementKind["keyword"] = "keyword";
108102         /** top level script node */
108103         ScriptElementKind["scriptElement"] = "script";
108104         /** module foo {} */
108105         ScriptElementKind["moduleElement"] = "module";
108106         /** class X {} */
108107         ScriptElementKind["classElement"] = "class";
108108         /** var x = class X {} */
108109         ScriptElementKind["localClassElement"] = "local class";
108110         /** interface Y {} */
108111         ScriptElementKind["interfaceElement"] = "interface";
108112         /** type T = ... */
108113         ScriptElementKind["typeElement"] = "type";
108114         /** enum E */
108115         ScriptElementKind["enumElement"] = "enum";
108116         ScriptElementKind["enumMemberElement"] = "enum member";
108117         /**
108118          * Inside module and script only
108119          * const v = ..
108120          */
108121         ScriptElementKind["variableElement"] = "var";
108122         /** Inside function */
108123         ScriptElementKind["localVariableElement"] = "local var";
108124         /**
108125          * Inside module and script only
108126          * function f() { }
108127          */
108128         ScriptElementKind["functionElement"] = "function";
108129         /** Inside function */
108130         ScriptElementKind["localFunctionElement"] = "local function";
108131         /** class X { [public|private]* foo() {} } */
108132         ScriptElementKind["memberFunctionElement"] = "method";
108133         /** class X { [public|private]* [get|set] foo:number; } */
108134         ScriptElementKind["memberGetAccessorElement"] = "getter";
108135         ScriptElementKind["memberSetAccessorElement"] = "setter";
108136         /**
108137          * class X { [public|private]* foo:number; }
108138          * interface Y { foo:number; }
108139          */
108140         ScriptElementKind["memberVariableElement"] = "property";
108141         /** class X { constructor() { } } */
108142         ScriptElementKind["constructorImplementationElement"] = "constructor";
108143         /** interface Y { ():number; } */
108144         ScriptElementKind["callSignatureElement"] = "call";
108145         /** interface Y { []:number; } */
108146         ScriptElementKind["indexSignatureElement"] = "index";
108147         /** interface Y { new():Y; } */
108148         ScriptElementKind["constructSignatureElement"] = "construct";
108149         /** function foo(*Y*: string) */
108150         ScriptElementKind["parameterElement"] = "parameter";
108151         ScriptElementKind["typeParameterElement"] = "type parameter";
108152         ScriptElementKind["primitiveType"] = "primitive type";
108153         ScriptElementKind["label"] = "label";
108154         ScriptElementKind["alias"] = "alias";
108155         ScriptElementKind["constElement"] = "const";
108156         ScriptElementKind["letElement"] = "let";
108157         ScriptElementKind["directory"] = "directory";
108158         ScriptElementKind["externalModuleName"] = "external module name";
108159         /**
108160          * <JsxTagName attribute1 attribute2={0} />
108161          */
108162         ScriptElementKind["jsxAttribute"] = "JSX attribute";
108163         /** String literal */
108164         ScriptElementKind["string"] = "string";
108165     })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
108166     var ScriptElementKindModifier;
108167     (function (ScriptElementKindModifier) {
108168         ScriptElementKindModifier["none"] = "";
108169         ScriptElementKindModifier["publicMemberModifier"] = "public";
108170         ScriptElementKindModifier["privateMemberModifier"] = "private";
108171         ScriptElementKindModifier["protectedMemberModifier"] = "protected";
108172         ScriptElementKindModifier["exportedModifier"] = "export";
108173         ScriptElementKindModifier["ambientModifier"] = "declare";
108174         ScriptElementKindModifier["staticModifier"] = "static";
108175         ScriptElementKindModifier["abstractModifier"] = "abstract";
108176         ScriptElementKindModifier["optionalModifier"] = "optional";
108177         ScriptElementKindModifier["dtsModifier"] = ".d.ts";
108178         ScriptElementKindModifier["tsModifier"] = ".ts";
108179         ScriptElementKindModifier["tsxModifier"] = ".tsx";
108180         ScriptElementKindModifier["jsModifier"] = ".js";
108181         ScriptElementKindModifier["jsxModifier"] = ".jsx";
108182         ScriptElementKindModifier["jsonModifier"] = ".json";
108183     })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {}));
108184     var ClassificationTypeNames;
108185     (function (ClassificationTypeNames) {
108186         ClassificationTypeNames["comment"] = "comment";
108187         ClassificationTypeNames["identifier"] = "identifier";
108188         ClassificationTypeNames["keyword"] = "keyword";
108189         ClassificationTypeNames["numericLiteral"] = "number";
108190         ClassificationTypeNames["bigintLiteral"] = "bigint";
108191         ClassificationTypeNames["operator"] = "operator";
108192         ClassificationTypeNames["stringLiteral"] = "string";
108193         ClassificationTypeNames["whiteSpace"] = "whitespace";
108194         ClassificationTypeNames["text"] = "text";
108195         ClassificationTypeNames["punctuation"] = "punctuation";
108196         ClassificationTypeNames["className"] = "class name";
108197         ClassificationTypeNames["enumName"] = "enum name";
108198         ClassificationTypeNames["interfaceName"] = "interface name";
108199         ClassificationTypeNames["moduleName"] = "module name";
108200         ClassificationTypeNames["typeParameterName"] = "type parameter name";
108201         ClassificationTypeNames["typeAliasName"] = "type alias name";
108202         ClassificationTypeNames["parameterName"] = "parameter name";
108203         ClassificationTypeNames["docCommentTagName"] = "doc comment tag name";
108204         ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name";
108205         ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name";
108206         ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name";
108207         ClassificationTypeNames["jsxAttribute"] = "jsx attribute";
108208         ClassificationTypeNames["jsxText"] = "jsx text";
108209         ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value";
108210     })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {}));
108211     var ClassificationType;
108212     (function (ClassificationType) {
108213         ClassificationType[ClassificationType["comment"] = 1] = "comment";
108214         ClassificationType[ClassificationType["identifier"] = 2] = "identifier";
108215         ClassificationType[ClassificationType["keyword"] = 3] = "keyword";
108216         ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral";
108217         ClassificationType[ClassificationType["operator"] = 5] = "operator";
108218         ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral";
108219         ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral";
108220         ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace";
108221         ClassificationType[ClassificationType["text"] = 9] = "text";
108222         ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation";
108223         ClassificationType[ClassificationType["className"] = 11] = "className";
108224         ClassificationType[ClassificationType["enumName"] = 12] = "enumName";
108225         ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName";
108226         ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName";
108227         ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName";
108228         ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName";
108229         ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName";
108230         ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName";
108231         ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName";
108232         ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName";
108233         ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName";
108234         ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute";
108235         ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText";
108236         ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue";
108237         ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral";
108238     })(ClassificationType = ts.ClassificationType || (ts.ClassificationType = {}));
108239 })(ts || (ts = {}));
108240 /* @internal */
108241 var ts;
108242 (function (ts) {
108243     // These utilities are common to multiple language service features.
108244     //#region
108245     ts.scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
108246     var SemanticMeaning;
108247     (function (SemanticMeaning) {
108248         SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
108249         SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value";
108250         SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type";
108251         SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace";
108252         SemanticMeaning[SemanticMeaning["All"] = 7] = "All";
108253     })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {}));
108254     function getMeaningFromDeclaration(node) {
108255         switch (node.kind) {
108256             case 242 /* VariableDeclaration */:
108257                 return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */;
108258             case 156 /* Parameter */:
108259             case 191 /* BindingElement */:
108260             case 159 /* PropertyDeclaration */:
108261             case 158 /* PropertySignature */:
108262             case 281 /* PropertyAssignment */:
108263             case 282 /* ShorthandPropertyAssignment */:
108264             case 161 /* MethodDeclaration */:
108265             case 160 /* MethodSignature */:
108266             case 162 /* Constructor */:
108267             case 163 /* GetAccessor */:
108268             case 164 /* SetAccessor */:
108269             case 244 /* FunctionDeclaration */:
108270             case 201 /* FunctionExpression */:
108271             case 202 /* ArrowFunction */:
108272             case 280 /* CatchClause */:
108273             case 273 /* JsxAttribute */:
108274                 return 1 /* Value */;
108275             case 155 /* TypeParameter */:
108276             case 246 /* InterfaceDeclaration */:
108277             case 247 /* TypeAliasDeclaration */:
108278             case 173 /* TypeLiteral */:
108279                 return 2 /* Type */;
108280             case 322 /* JSDocTypedefTag */:
108281                 // If it has no name node, it shares the name with the value declaration below it.
108282                 return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
108283             case 284 /* EnumMember */:
108284             case 245 /* ClassDeclaration */:
108285                 return 1 /* Value */ | 2 /* Type */;
108286             case 249 /* ModuleDeclaration */:
108287                 if (ts.isAmbientModule(node)) {
108288                     return 4 /* Namespace */ | 1 /* Value */;
108289                 }
108290                 else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) {
108291                     return 4 /* Namespace */ | 1 /* Value */;
108292                 }
108293                 else {
108294                     return 4 /* Namespace */;
108295                 }
108296             case 248 /* EnumDeclaration */:
108297             case 257 /* NamedImports */:
108298             case 258 /* ImportSpecifier */:
108299             case 253 /* ImportEqualsDeclaration */:
108300             case 254 /* ImportDeclaration */:
108301             case 259 /* ExportAssignment */:
108302             case 260 /* ExportDeclaration */:
108303                 return 7 /* All */;
108304             // An external module can be a Value
108305             case 290 /* SourceFile */:
108306                 return 4 /* Namespace */ | 1 /* Value */;
108307         }
108308         return 7 /* All */;
108309     }
108310     ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
108311     function getMeaningFromLocation(node) {
108312         node = getAdjustedReferenceLocation(node);
108313         if (node.kind === 290 /* SourceFile */) {
108314             return 1 /* Value */;
108315         }
108316         else if (node.parent.kind === 259 /* ExportAssignment */
108317             || node.parent.kind === 265 /* ExternalModuleReference */
108318             || node.parent.kind === 258 /* ImportSpecifier */
108319             || node.parent.kind === 255 /* ImportClause */
108320             || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) {
108321             return 7 /* All */;
108322         }
108323         else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
108324             return getMeaningFromRightHandSideOfImportEquals(node);
108325         }
108326         else if (ts.isDeclarationName(node)) {
108327             return getMeaningFromDeclaration(node.parent);
108328         }
108329         else if (isTypeReference(node)) {
108330             return 2 /* Type */;
108331         }
108332         else if (isNamespaceReference(node)) {
108333             return 4 /* Namespace */;
108334         }
108335         else if (ts.isTypeParameterDeclaration(node.parent)) {
108336             ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName
108337             return 2 /* Type */;
108338         }
108339         else if (ts.isLiteralTypeNode(node.parent)) {
108340             // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
108341             return 2 /* Type */ | 1 /* Value */;
108342         }
108343         else {
108344             return 1 /* Value */;
108345         }
108346     }
108347     ts.getMeaningFromLocation = getMeaningFromLocation;
108348     function getMeaningFromRightHandSideOfImportEquals(node) {
108349         //     import a = |b|; // Namespace
108350         //     import a = |b.c|; // Value, type, namespace
108351         //     import a = |b.c|.d; // Namespace
108352         var name = node.kind === 153 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined;
108353         return name && name.parent.kind === 253 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */;
108354     }
108355     function isInRightSideOfInternalImportEqualsDeclaration(node) {
108356         while (node.parent.kind === 153 /* QualifiedName */) {
108357             node = node.parent;
108358         }
108359         return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
108360     }
108361     ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration;
108362     function isNamespaceReference(node) {
108363         return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
108364     }
108365     function isQualifiedNameNamespaceReference(node) {
108366         var root = node;
108367         var isLastClause = true;
108368         if (root.parent.kind === 153 /* QualifiedName */) {
108369             while (root.parent && root.parent.kind === 153 /* QualifiedName */) {
108370                 root = root.parent;
108371             }
108372             isLastClause = root.right === node;
108373         }
108374         return root.parent.kind === 169 /* TypeReference */ && !isLastClause;
108375     }
108376     function isPropertyAccessNamespaceReference(node) {
108377         var root = node;
108378         var isLastClause = true;
108379         if (root.parent.kind === 194 /* PropertyAccessExpression */) {
108380             while (root.parent && root.parent.kind === 194 /* PropertyAccessExpression */) {
108381                 root = root.parent;
108382             }
108383             isLastClause = root.name === node;
108384         }
108385         if (!isLastClause && root.parent.kind === 216 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 279 /* HeritageClause */) {
108386             var decl = root.parent.parent.parent;
108387             return (decl.kind === 245 /* ClassDeclaration */ && root.parent.parent.token === 113 /* ImplementsKeyword */) ||
108388                 (decl.kind === 246 /* InterfaceDeclaration */ && root.parent.parent.token === 90 /* ExtendsKeyword */);
108389         }
108390         return false;
108391     }
108392     function isTypeReference(node) {
108393         if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
108394             node = node.parent;
108395         }
108396         switch (node.kind) {
108397             case 104 /* ThisKeyword */:
108398                 return !ts.isExpressionNode(node);
108399             case 183 /* ThisType */:
108400                 return true;
108401         }
108402         switch (node.parent.kind) {
108403             case 169 /* TypeReference */:
108404                 return true;
108405             case 188 /* ImportType */:
108406                 return !node.parent.isTypeOf;
108407             case 216 /* ExpressionWithTypeArguments */:
108408                 return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
108409         }
108410         return false;
108411     }
108412     function isCallExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
108413         if (includeElementAccess === void 0) { includeElementAccess = false; }
108414         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
108415         return isCalleeWorker(node, ts.isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
108416     }
108417     ts.isCallExpressionTarget = isCallExpressionTarget;
108418     function isNewExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
108419         if (includeElementAccess === void 0) { includeElementAccess = false; }
108420         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
108421         return isCalleeWorker(node, ts.isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
108422     }
108423     ts.isNewExpressionTarget = isNewExpressionTarget;
108424     function isCallOrNewExpressionTarget(node, includeElementAccess, skipPastOuterExpressions) {
108425         if (includeElementAccess === void 0) { includeElementAccess = false; }
108426         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
108427         return isCalleeWorker(node, ts.isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
108428     }
108429     ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget;
108430     function isTaggedTemplateTag(node, includeElementAccess, skipPastOuterExpressions) {
108431         if (includeElementAccess === void 0) { includeElementAccess = false; }
108432         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
108433         return isCalleeWorker(node, ts.isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions);
108434     }
108435     ts.isTaggedTemplateTag = isTaggedTemplateTag;
108436     function isDecoratorTarget(node, includeElementAccess, skipPastOuterExpressions) {
108437         if (includeElementAccess === void 0) { includeElementAccess = false; }
108438         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
108439         return isCalleeWorker(node, ts.isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
108440     }
108441     ts.isDecoratorTarget = isDecoratorTarget;
108442     function isJsxOpeningLikeElementTagName(node, includeElementAccess, skipPastOuterExpressions) {
108443         if (includeElementAccess === void 0) { includeElementAccess = false; }
108444         if (skipPastOuterExpressions === void 0) { skipPastOuterExpressions = false; }
108445         return isCalleeWorker(node, ts.isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions);
108446     }
108447     ts.isJsxOpeningLikeElementTagName = isJsxOpeningLikeElementTagName;
108448     function selectExpressionOfCallOrNewExpressionOrDecorator(node) {
108449         return node.expression;
108450     }
108451     function selectTagOfTaggedTemplateExpression(node) {
108452         return node.tag;
108453     }
108454     function selectTagNameOfJsxOpeningLikeElement(node) {
108455         return node.tagName;
108456     }
108457     function isCalleeWorker(node, pred, calleeSelector, includeElementAccess, skipPastOuterExpressions) {
108458         var target = includeElementAccess ? climbPastPropertyOrElementAccess(node) : climbPastPropertyAccess(node);
108459         if (skipPastOuterExpressions) {
108460             target = ts.skipOuterExpressions(target);
108461         }
108462         return !!target && !!target.parent && pred(target.parent) && calleeSelector(target.parent) === target;
108463     }
108464     function climbPastPropertyAccess(node) {
108465         return isRightSideOfPropertyAccess(node) ? node.parent : node;
108466     }
108467     ts.climbPastPropertyAccess = climbPastPropertyAccess;
108468     function climbPastPropertyOrElementAccess(node) {
108469         return isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node) ? node.parent : node;
108470     }
108471     ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess;
108472     function getTargetLabel(referenceNode, labelName) {
108473         while (referenceNode) {
108474             if (referenceNode.kind === 238 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) {
108475                 return referenceNode.label;
108476             }
108477             referenceNode = referenceNode.parent;
108478         }
108479         return undefined;
108480     }
108481     ts.getTargetLabel = getTargetLabel;
108482     function hasPropertyAccessExpressionWithName(node, funcName) {
108483         if (!ts.isPropertyAccessExpression(node.expression)) {
108484             return false;
108485         }
108486         return node.expression.name.text === funcName;
108487     }
108488     ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName;
108489     function isJumpStatementTarget(node) {
108490         var _a;
108491         return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isBreakOrContinueStatement)) === null || _a === void 0 ? void 0 : _a.label) === node;
108492     }
108493     ts.isJumpStatementTarget = isJumpStatementTarget;
108494     function isLabelOfLabeledStatement(node) {
108495         var _a;
108496         return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isLabeledStatement)) === null || _a === void 0 ? void 0 : _a.label) === node;
108497     }
108498     ts.isLabelOfLabeledStatement = isLabelOfLabeledStatement;
108499     function isLabelName(node) {
108500         return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
108501     }
108502     ts.isLabelName = isLabelName;
108503     function isTagName(node) {
108504         var _a;
108505         return ((_a = ts.tryCast(node.parent, ts.isJSDocTag)) === null || _a === void 0 ? void 0 : _a.tagName) === node;
108506     }
108507     ts.isTagName = isTagName;
108508     function isRightSideOfQualifiedName(node) {
108509         var _a;
108510         return ((_a = ts.tryCast(node.parent, ts.isQualifiedName)) === null || _a === void 0 ? void 0 : _a.right) === node;
108511     }
108512     ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName;
108513     function isRightSideOfPropertyAccess(node) {
108514         var _a;
108515         return ((_a = ts.tryCast(node.parent, ts.isPropertyAccessExpression)) === null || _a === void 0 ? void 0 : _a.name) === node;
108516     }
108517     ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess;
108518     function isArgumentExpressionOfElementAccess(node) {
108519         var _a;
108520         return ((_a = ts.tryCast(node.parent, ts.isElementAccessExpression)) === null || _a === void 0 ? void 0 : _a.argumentExpression) === node;
108521     }
108522     ts.isArgumentExpressionOfElementAccess = isArgumentExpressionOfElementAccess;
108523     function isNameOfModuleDeclaration(node) {
108524         var _a;
108525         return ((_a = ts.tryCast(node.parent, ts.isModuleDeclaration)) === null || _a === void 0 ? void 0 : _a.name) === node;
108526     }
108527     ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration;
108528     function isNameOfFunctionDeclaration(node) {
108529         var _a;
108530         return ts.isIdentifier(node) && ((_a = ts.tryCast(node.parent, ts.isFunctionLike)) === null || _a === void 0 ? void 0 : _a.name) === node;
108531     }
108532     ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration;
108533     function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
108534         switch (node.parent.kind) {
108535             case 159 /* PropertyDeclaration */:
108536             case 158 /* PropertySignature */:
108537             case 281 /* PropertyAssignment */:
108538             case 284 /* EnumMember */:
108539             case 161 /* MethodDeclaration */:
108540             case 160 /* MethodSignature */:
108541             case 163 /* GetAccessor */:
108542             case 164 /* SetAccessor */:
108543             case 249 /* ModuleDeclaration */:
108544                 return ts.getNameOfDeclaration(node.parent) === node;
108545             case 195 /* ElementAccessExpression */:
108546                 return node.parent.argumentExpression === node;
108547             case 154 /* ComputedPropertyName */:
108548                 return true;
108549             case 187 /* LiteralType */:
108550                 return node.parent.parent.kind === 185 /* IndexedAccessType */;
108551             default:
108552                 return false;
108553         }
108554     }
108555     ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess;
108556     function isExpressionOfExternalModuleImportEqualsDeclaration(node) {
108557         return ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
108558             ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
108559     }
108560     ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
108561     function getContainerNode(node) {
108562         if (ts.isJSDocTypeAlias(node)) {
108563             // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
108564             // node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
108565             // Then we get parent again in the loop.
108566             node = node.parent.parent;
108567         }
108568         while (true) {
108569             node = node.parent;
108570             if (!node) {
108571                 return undefined;
108572             }
108573             switch (node.kind) {
108574                 case 290 /* SourceFile */:
108575                 case 161 /* MethodDeclaration */:
108576                 case 160 /* MethodSignature */:
108577                 case 244 /* FunctionDeclaration */:
108578                 case 201 /* FunctionExpression */:
108579                 case 163 /* GetAccessor */:
108580                 case 164 /* SetAccessor */:
108581                 case 245 /* ClassDeclaration */:
108582                 case 246 /* InterfaceDeclaration */:
108583                 case 248 /* EnumDeclaration */:
108584                 case 249 /* ModuleDeclaration */:
108585                     return node;
108586             }
108587         }
108588     }
108589     ts.getContainerNode = getContainerNode;
108590     function getNodeKind(node) {
108591         switch (node.kind) {
108592             case 290 /* SourceFile */:
108593                 return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
108594             case 249 /* ModuleDeclaration */:
108595                 return "module" /* moduleElement */;
108596             case 245 /* ClassDeclaration */:
108597             case 214 /* ClassExpression */:
108598                 return "class" /* classElement */;
108599             case 246 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
108600             case 247 /* TypeAliasDeclaration */:
108601             case 315 /* JSDocCallbackTag */:
108602             case 322 /* JSDocTypedefTag */:
108603                 return "type" /* typeElement */;
108604             case 248 /* EnumDeclaration */: return "enum" /* enumElement */;
108605             case 242 /* VariableDeclaration */:
108606                 return getKindOfVariableDeclaration(node);
108607             case 191 /* BindingElement */:
108608                 return getKindOfVariableDeclaration(ts.getRootDeclaration(node));
108609             case 202 /* ArrowFunction */:
108610             case 244 /* FunctionDeclaration */:
108611             case 201 /* FunctionExpression */:
108612                 return "function" /* functionElement */;
108613             case 163 /* GetAccessor */: return "getter" /* memberGetAccessorElement */;
108614             case 164 /* SetAccessor */: return "setter" /* memberSetAccessorElement */;
108615             case 161 /* MethodDeclaration */:
108616             case 160 /* MethodSignature */:
108617                 return "method" /* memberFunctionElement */;
108618             case 281 /* PropertyAssignment */:
108619                 var initializer = node.initializer;
108620                 return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
108621             case 159 /* PropertyDeclaration */:
108622             case 158 /* PropertySignature */:
108623             case 282 /* ShorthandPropertyAssignment */:
108624             case 283 /* SpreadAssignment */:
108625                 return "property" /* memberVariableElement */;
108626             case 167 /* IndexSignature */: return "index" /* indexSignatureElement */;
108627             case 166 /* ConstructSignature */: return "construct" /* constructSignatureElement */;
108628             case 165 /* CallSignature */: return "call" /* callSignatureElement */;
108629             case 162 /* Constructor */: return "constructor" /* constructorImplementationElement */;
108630             case 155 /* TypeParameter */: return "type parameter" /* typeParameterElement */;
108631             case 284 /* EnumMember */: return "enum member" /* enumMemberElement */;
108632             case 156 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */;
108633             case 253 /* ImportEqualsDeclaration */:
108634             case 258 /* ImportSpecifier */:
108635             case 263 /* ExportSpecifier */:
108636             case 256 /* NamespaceImport */:
108637             case 262 /* NamespaceExport */:
108638                 return "alias" /* alias */;
108639             case 209 /* BinaryExpression */:
108640                 var kind = ts.getAssignmentDeclarationKind(node);
108641                 var right = node.right;
108642                 switch (kind) {
108643                     case 7 /* ObjectDefinePropertyValue */:
108644                     case 8 /* ObjectDefinePropertyExports */:
108645                     case 9 /* ObjectDefinePrototypeProperty */:
108646                     case 0 /* None */:
108647                         return "" /* unknown */;
108648                     case 1 /* ExportsProperty */:
108649                     case 2 /* ModuleExports */:
108650                         var rightKind = getNodeKind(right);
108651                         return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind;
108652                     case 3 /* PrototypeProperty */:
108653                         return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
108654                     case 4 /* ThisProperty */:
108655                         return "property" /* memberVariableElement */; // property
108656                     case 5 /* Property */:
108657                         // static method / property
108658                         return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */;
108659                     case 6 /* Prototype */:
108660                         return "local class" /* localClassElement */;
108661                     default: {
108662                         ts.assertType(kind);
108663                         return "" /* unknown */;
108664                     }
108665                 }
108666             case 75 /* Identifier */:
108667                 return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */;
108668             case 259 /* ExportAssignment */:
108669                 var scriptKind = getNodeKind(node.expression);
108670                 // If the expression didn't come back with something (like it does for an identifiers)
108671                 return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind;
108672             default:
108673                 return "" /* unknown */;
108674         }
108675         function getKindOfVariableDeclaration(v) {
108676             return ts.isVarConst(v)
108677                 ? "const" /* constElement */
108678                 : ts.isLet(v)
108679                     ? "let" /* letElement */
108680                     : "var" /* variableElement */;
108681         }
108682     }
108683     ts.getNodeKind = getNodeKind;
108684     function isThis(node) {
108685         switch (node.kind) {
108686             case 104 /* ThisKeyword */:
108687                 // case SyntaxKind.ThisType: TODO: GH#9267
108688                 return true;
108689             case 75 /* Identifier */:
108690                 // 'this' as a parameter
108691                 return ts.identifierIsThisKeyword(node) && node.parent.kind === 156 /* Parameter */;
108692             default:
108693                 return false;
108694         }
108695     }
108696     ts.isThis = isThis;
108697     // Matches the beginning of a triple slash directive
108698     var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
108699     function getLineStartPositionForPosition(position, sourceFile) {
108700         var lineStarts = ts.getLineStarts(sourceFile);
108701         var line = sourceFile.getLineAndCharacterOfPosition(position).line;
108702         return lineStarts[line];
108703     }
108704     ts.getLineStartPositionForPosition = getLineStartPositionForPosition;
108705     function rangeContainsRange(r1, r2) {
108706         return startEndContainsRange(r1.pos, r1.end, r2);
108707     }
108708     ts.rangeContainsRange = rangeContainsRange;
108709     function rangeContainsRangeExclusive(r1, r2) {
108710         return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
108711     }
108712     ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive;
108713     function rangeContainsPosition(r, pos) {
108714         return r.pos <= pos && pos <= r.end;
108715     }
108716     ts.rangeContainsPosition = rangeContainsPosition;
108717     function rangeContainsPositionExclusive(r, pos) {
108718         return r.pos < pos && pos < r.end;
108719     }
108720     ts.rangeContainsPositionExclusive = rangeContainsPositionExclusive;
108721     function startEndContainsRange(start, end, range) {
108722         return start <= range.pos && end >= range.end;
108723     }
108724     ts.startEndContainsRange = startEndContainsRange;
108725     function rangeContainsStartEnd(range, start, end) {
108726         return range.pos <= start && range.end >= end;
108727     }
108728     ts.rangeContainsStartEnd = rangeContainsStartEnd;
108729     function rangeOverlapsWithStartEnd(r1, start, end) {
108730         return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
108731     }
108732     ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd;
108733     function nodeOverlapsWithStartEnd(node, sourceFile, start, end) {
108734         return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
108735     }
108736     ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd;
108737     function startEndOverlapsWithStartEnd(start1, end1, start2, end2) {
108738         var start = Math.max(start1, start2);
108739         var end = Math.min(end1, end2);
108740         return start < end;
108741     }
108742     ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd;
108743     /**
108744      * Assumes `candidate.start <= position` holds.
108745      */
108746     function positionBelongsToNode(candidate, position, sourceFile) {
108747         ts.Debug.assert(candidate.pos <= position);
108748         return position < candidate.end || !isCompletedNode(candidate, sourceFile);
108749     }
108750     ts.positionBelongsToNode = positionBelongsToNode;
108751     function isCompletedNode(n, sourceFile) {
108752         if (n === undefined || ts.nodeIsMissing(n)) {
108753             return false;
108754         }
108755         switch (n.kind) {
108756             case 245 /* ClassDeclaration */:
108757             case 246 /* InterfaceDeclaration */:
108758             case 248 /* EnumDeclaration */:
108759             case 193 /* ObjectLiteralExpression */:
108760             case 189 /* ObjectBindingPattern */:
108761             case 173 /* TypeLiteral */:
108762             case 223 /* Block */:
108763             case 250 /* ModuleBlock */:
108764             case 251 /* CaseBlock */:
108765             case 257 /* NamedImports */:
108766             case 261 /* NamedExports */:
108767                 return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile);
108768             case 280 /* CatchClause */:
108769                 return isCompletedNode(n.block, sourceFile);
108770             case 197 /* NewExpression */:
108771                 if (!n.arguments) {
108772                     return true;
108773                 }
108774             // falls through
108775             case 196 /* CallExpression */:
108776             case 200 /* ParenthesizedExpression */:
108777             case 182 /* ParenthesizedType */:
108778                 return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile);
108779             case 170 /* FunctionType */:
108780             case 171 /* ConstructorType */:
108781                 return isCompletedNode(n.type, sourceFile);
108782             case 162 /* Constructor */:
108783             case 163 /* GetAccessor */:
108784             case 164 /* SetAccessor */:
108785             case 244 /* FunctionDeclaration */:
108786             case 201 /* FunctionExpression */:
108787             case 161 /* MethodDeclaration */:
108788             case 160 /* MethodSignature */:
108789             case 166 /* ConstructSignature */:
108790             case 165 /* CallSignature */:
108791             case 202 /* ArrowFunction */:
108792                 if (n.body) {
108793                     return isCompletedNode(n.body, sourceFile);
108794                 }
108795                 if (n.type) {
108796                     return isCompletedNode(n.type, sourceFile);
108797                 }
108798                 // Even though type parameters can be unclosed, we can get away with
108799                 // having at least a closing paren.
108800                 return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile);
108801             case 249 /* ModuleDeclaration */:
108802                 return !!n.body && isCompletedNode(n.body, sourceFile);
108803             case 227 /* IfStatement */:
108804                 if (n.elseStatement) {
108805                     return isCompletedNode(n.elseStatement, sourceFile);
108806                 }
108807                 return isCompletedNode(n.thenStatement, sourceFile);
108808             case 226 /* ExpressionStatement */:
108809                 return isCompletedNode(n.expression, sourceFile) ||
108810                     hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile);
108811             case 192 /* ArrayLiteralExpression */:
108812             case 190 /* ArrayBindingPattern */:
108813             case 195 /* ElementAccessExpression */:
108814             case 154 /* ComputedPropertyName */:
108815             case 175 /* TupleType */:
108816                 return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile);
108817             case 167 /* IndexSignature */:
108818                 if (n.type) {
108819                     return isCompletedNode(n.type, sourceFile);
108820                 }
108821                 return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile);
108822             case 277 /* CaseClause */:
108823             case 278 /* DefaultClause */:
108824                 // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed
108825                 return false;
108826             case 230 /* ForStatement */:
108827             case 231 /* ForInStatement */:
108828             case 232 /* ForOfStatement */:
108829             case 229 /* WhileStatement */:
108830                 return isCompletedNode(n.statement, sourceFile);
108831             case 228 /* DoStatement */:
108832                 // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
108833                 return hasChildOfKind(n, 111 /* WhileKeyword */, sourceFile)
108834                     ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile)
108835                     : isCompletedNode(n.statement, sourceFile);
108836             case 172 /* TypeQuery */:
108837                 return isCompletedNode(n.exprName, sourceFile);
108838             case 204 /* TypeOfExpression */:
108839             case 203 /* DeleteExpression */:
108840             case 205 /* VoidExpression */:
108841             case 212 /* YieldExpression */:
108842             case 213 /* SpreadElement */:
108843                 var unaryWordExpression = n;
108844                 return isCompletedNode(unaryWordExpression.expression, sourceFile);
108845             case 198 /* TaggedTemplateExpression */:
108846                 return isCompletedNode(n.template, sourceFile);
108847             case 211 /* TemplateExpression */:
108848                 var lastSpan = ts.lastOrUndefined(n.templateSpans);
108849                 return isCompletedNode(lastSpan, sourceFile);
108850             case 221 /* TemplateSpan */:
108851                 return ts.nodeIsPresent(n.literal);
108852             case 260 /* ExportDeclaration */:
108853             case 254 /* ImportDeclaration */:
108854                 return ts.nodeIsPresent(n.moduleSpecifier);
108855             case 207 /* PrefixUnaryExpression */:
108856                 return isCompletedNode(n.operand, sourceFile);
108857             case 209 /* BinaryExpression */:
108858                 return isCompletedNode(n.right, sourceFile);
108859             case 210 /* ConditionalExpression */:
108860                 return isCompletedNode(n.whenFalse, sourceFile);
108861             default:
108862                 return true;
108863         }
108864     }
108865     /*
108866      * Checks if node ends with 'expectedLastToken'.
108867      * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
108868      */
108869     function nodeEndsWith(n, expectedLastToken, sourceFile) {
108870         var children = n.getChildren(sourceFile);
108871         if (children.length) {
108872             var lastChild = ts.last(children);
108873             if (lastChild.kind === expectedLastToken) {
108874                 return true;
108875             }
108876             else if (lastChild.kind === 26 /* SemicolonToken */ && children.length !== 1) {
108877                 return children[children.length - 2].kind === expectedLastToken;
108878             }
108879         }
108880         return false;
108881     }
108882     function findListItemInfo(node) {
108883         var list = findContainingList(node);
108884         // It is possible at this point for syntaxList to be undefined, either if
108885         // node.parent had no list child, or if none of its list children contained
108886         // the span of node. If this happens, return undefined. The caller should
108887         // handle this case.
108888         if (!list) {
108889             return undefined;
108890         }
108891         var children = list.getChildren();
108892         var listItemIndex = ts.indexOfNode(children, node);
108893         return {
108894             listItemIndex: listItemIndex,
108895             list: list
108896         };
108897     }
108898     ts.findListItemInfo = findListItemInfo;
108899     function hasChildOfKind(n, kind, sourceFile) {
108900         return !!findChildOfKind(n, kind, sourceFile);
108901     }
108902     ts.hasChildOfKind = hasChildOfKind;
108903     function findChildOfKind(n, kind, sourceFile) {
108904         return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; });
108905     }
108906     ts.findChildOfKind = findChildOfKind;
108907     function findContainingList(node) {
108908         // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will
108909         // be parented by the container of the SyntaxList, not the SyntaxList itself.
108910         // In order to find the list item index, we first need to locate SyntaxList itself and then search
108911         // for the position of the relevant node (or comma).
108912         var syntaxList = ts.find(node.parent.getChildren(), function (c) { return ts.isSyntaxList(c) && rangeContainsRange(c, node); });
108913         // Either we didn't find an appropriate list, or the list must contain us.
108914         ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node));
108915         return syntaxList;
108916     }
108917     ts.findContainingList = findContainingList;
108918     function isDefaultModifier(node) {
108919         return node.kind === 84 /* DefaultKeyword */;
108920     }
108921     function isClassKeyword(node) {
108922         return node.kind === 80 /* ClassKeyword */;
108923     }
108924     function isFunctionKeyword(node) {
108925         return node.kind === 94 /* FunctionKeyword */;
108926     }
108927     function getAdjustedLocationForClass(node) {
108928         if (ts.isNamedDeclaration(node)) {
108929             return node.name;
108930         }
108931         if (ts.isClassDeclaration(node)) {
108932             // for class and function declarations, use the `default` modifier
108933             // when the declaration is unnamed.
108934             var defaultModifier = ts.find(node.modifiers, isDefaultModifier);
108935             if (defaultModifier)
108936                 return defaultModifier;
108937         }
108938         if (ts.isClassExpression(node)) {
108939             // for class expressions, use the `class` keyword when the class is unnamed
108940             var classKeyword = ts.find(node.getChildren(), isClassKeyword);
108941             if (classKeyword)
108942                 return classKeyword;
108943         }
108944     }
108945     function getAdjustedLocationForFunction(node) {
108946         if (ts.isNamedDeclaration(node)) {
108947             return node.name;
108948         }
108949         if (ts.isFunctionDeclaration(node)) {
108950             // for class and function declarations, use the `default` modifier
108951             // when the declaration is unnamed.
108952             var defaultModifier = ts.find(node.modifiers, isDefaultModifier);
108953             if (defaultModifier)
108954                 return defaultModifier;
108955         }
108956         if (ts.isFunctionExpression(node)) {
108957             // for function expressions, use the `function` keyword when the function is unnamed
108958             var functionKeyword = ts.find(node.getChildren(), isFunctionKeyword);
108959             if (functionKeyword)
108960                 return functionKeyword;
108961         }
108962     }
108963     function getAdjustedLocationForDeclaration(node, forRename) {
108964         if (!forRename) {
108965             switch (node.kind) {
108966                 case 245 /* ClassDeclaration */:
108967                 case 214 /* ClassExpression */:
108968                     return getAdjustedLocationForClass(node);
108969                 case 244 /* FunctionDeclaration */:
108970                 case 201 /* FunctionExpression */:
108971                     return getAdjustedLocationForFunction(node);
108972             }
108973         }
108974         if (ts.isNamedDeclaration(node)) {
108975             return node.name;
108976         }
108977     }
108978     function getAdjustedLocationForImportDeclaration(node, forRename) {
108979         if (node.importClause) {
108980             if (node.importClause.name && node.importClause.namedBindings) {
108981                 // do not adjust if we have both a name and named bindings
108982                 return;
108983             }
108984             // /**/import [|name|] from ...;
108985             // import /**/type [|name|] from ...;
108986             if (node.importClause.name) {
108987                 return node.importClause.name;
108988             }
108989             // /**/import { [|name|] } from ...;
108990             // /**/import { propertyName as [|name|] } from ...;
108991             // /**/import * as [|name|] from ...;
108992             // import /**/type { [|name|] } from ...;
108993             // import /**/type { propertyName as [|name|] } from ...;
108994             // import /**/type * as [|name|] from ...;
108995             if (node.importClause.namedBindings) {
108996                 if (ts.isNamedImports(node.importClause.namedBindings)) {
108997                     // do nothing if there is more than one binding
108998                     var onlyBinding = ts.singleOrUndefined(node.importClause.namedBindings.elements);
108999                     if (!onlyBinding) {
109000                         return;
109001                     }
109002                     return onlyBinding.name;
109003                 }
109004                 else if (ts.isNamespaceImport(node.importClause.namedBindings)) {
109005                     return node.importClause.namedBindings.name;
109006                 }
109007             }
109008         }
109009         if (!forRename) {
109010             // /**/import "[|module|]";
109011             // /**/import ... from "[|module|]";
109012             // import /**/type ... from "[|module|]";
109013             return node.moduleSpecifier;
109014         }
109015     }
109016     function getAdjustedLocationForExportDeclaration(node, forRename) {
109017         if (node.exportClause) {
109018             // /**/export { [|name|] } ...
109019             // /**/export { propertyName as [|name|] } ...
109020             // /**/export * as [|name|] ...
109021             // export /**/type { [|name|] } from ...
109022             // export /**/type { propertyName as [|name|] } from ...
109023             // export /**/type * as [|name|] ...
109024             if (ts.isNamedExports(node.exportClause)) {
109025                 // do nothing if there is more than one binding
109026                 var onlyBinding = ts.singleOrUndefined(node.exportClause.elements);
109027                 if (!onlyBinding) {
109028                     return;
109029                 }
109030                 return node.exportClause.elements[0].name;
109031             }
109032             else if (ts.isNamespaceExport(node.exportClause)) {
109033                 return node.exportClause.name;
109034             }
109035         }
109036         if (!forRename) {
109037             // /**/export * from "[|module|]";
109038             // export /**/type * from "[|module|]";
109039             return node.moduleSpecifier;
109040         }
109041     }
109042     function getAdjustedLocationForHeritageClause(node) {
109043         // /**/extends [|name|]
109044         // /**/implements [|name|]
109045         if (node.types.length === 1) {
109046             return node.types[0].expression;
109047         }
109048         // /**/extends name1, name2 ...
109049         // /**/implements name1, name2 ...
109050     }
109051     function getAdjustedLocation(node, forRename) {
109052         var parent = node.parent;
109053         // /**/<modifier> [|name|] ...
109054         // /**/<modifier> <class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
109055         // /**/<class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
109056         // /**/import [|name|] = ...
109057         //
109058         // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled
109059         // specially by `getSymbolAtLocation`.
109060         if (ts.isModifier(node) && (forRename || node.kind !== 84 /* DefaultKeyword */) ? ts.contains(parent.modifiers, node) :
109061             node.kind === 80 /* ClassKeyword */ ? ts.isClassDeclaration(parent) || ts.isClassExpression(node) :
109062                 node.kind === 94 /* FunctionKeyword */ ? ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(node) :
109063                     node.kind === 114 /* InterfaceKeyword */ ? ts.isInterfaceDeclaration(parent) :
109064                         node.kind === 88 /* EnumKeyword */ ? ts.isEnumDeclaration(parent) :
109065                             node.kind === 145 /* TypeKeyword */ ? ts.isTypeAliasDeclaration(parent) :
109066                                 node.kind === 136 /* NamespaceKeyword */ || node.kind === 135 /* ModuleKeyword */ ? ts.isModuleDeclaration(parent) :
109067                                     node.kind === 96 /* ImportKeyword */ ? ts.isImportEqualsDeclaration(parent) :
109068                                         node.kind === 131 /* GetKeyword */ ? ts.isGetAccessorDeclaration(parent) :
109069                                             node.kind === 142 /* SetKeyword */ && ts.isSetAccessorDeclaration(parent)) {
109070             var location = getAdjustedLocationForDeclaration(parent, forRename);
109071             if (location) {
109072                 return location;
109073             }
109074         }
109075         // /**/<var|let|const> [|name|] ...
109076         if ((node.kind === 109 /* VarKeyword */ || node.kind === 81 /* ConstKeyword */ || node.kind === 115 /* LetKeyword */) &&
109077             ts.isVariableDeclarationList(parent) && parent.declarations.length === 1) {
109078             var decl = parent.declarations[0];
109079             if (ts.isIdentifier(decl.name)) {
109080                 return decl.name;
109081             }
109082         }
109083         if (node.kind === 145 /* TypeKeyword */) {
109084             // import /**/type [|name|] from ...;
109085             // import /**/type { [|name|] } from ...;
109086             // import /**/type { propertyName as [|name|] } from ...;
109087             // import /**/type ... from "[|module|]";
109088             if (ts.isImportClause(parent) && parent.isTypeOnly) {
109089                 var location = getAdjustedLocationForImportDeclaration(parent.parent, forRename);
109090                 if (location) {
109091                     return location;
109092                 }
109093             }
109094             // export /**/type { [|name|] } from ...;
109095             // export /**/type { propertyName as [|name|] } from ...;
109096             // export /**/type * from "[|module|]";
109097             // export /**/type * as ... from "[|module|]";
109098             if (ts.isExportDeclaration(parent) && parent.isTypeOnly) {
109099                 var location = getAdjustedLocationForExportDeclaration(parent, forRename);
109100                 if (location) {
109101                     return location;
109102                 }
109103             }
109104         }
109105         // import { propertyName /**/as [|name|] } ...
109106         // import * /**/as [|name|] ...
109107         // export { propertyName /**/as [|name|] } ...
109108         // export * /**/as [|name|] ...
109109         if (node.kind === 123 /* AsKeyword */) {
109110             if (ts.isImportSpecifier(parent) && parent.propertyName ||
109111                 ts.isExportSpecifier(parent) && parent.propertyName ||
109112                 ts.isNamespaceImport(parent) ||
109113                 ts.isNamespaceExport(parent)) {
109114                 return parent.name;
109115             }
109116             if (ts.isExportDeclaration(parent) && parent.exportClause && ts.isNamespaceExport(parent.exportClause)) {
109117                 return parent.exportClause.name;
109118             }
109119         }
109120         // /**/import [|name|] from ...;
109121         // /**/import { [|name|] } from ...;
109122         // /**/import { propertyName as [|name|] } from ...;
109123         // /**/import ... from "[|module|]";
109124         // /**/import "[|module|]";
109125         if (node.kind === 96 /* ImportKeyword */ && ts.isImportDeclaration(parent)) {
109126             var location = getAdjustedLocationForImportDeclaration(parent, forRename);
109127             if (location) {
109128                 return location;
109129             }
109130         }
109131         if (node.kind === 89 /* ExportKeyword */) {
109132             // /**/export { [|name|] } ...;
109133             // /**/export { propertyName as [|name|] } ...;
109134             // /**/export * from "[|module|]";
109135             // /**/export * as ... from "[|module|]";
109136             if (ts.isExportDeclaration(parent)) {
109137                 var location = getAdjustedLocationForExportDeclaration(parent, forRename);
109138                 if (location) {
109139                     return location;
109140                 }
109141             }
109142             // NOTE: We don't adjust the location of the `default` keyword as that is handled specially by `getSymbolAtLocation`.
109143             // /**/export default [|name|];
109144             // /**/export = [|name|];
109145             if (ts.isExportAssignment(parent)) {
109146                 return ts.skipOuterExpressions(parent.expression);
109147             }
109148         }
109149         // import name = /**/require("[|module|]");
109150         if (node.kind === 139 /* RequireKeyword */ && ts.isExternalModuleReference(parent)) {
109151             return parent.expression;
109152         }
109153         // import ... /**/from "[|module|]";
109154         // export ... /**/from "[|module|]";
109155         if (node.kind === 149 /* FromKeyword */ && (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) && parent.moduleSpecifier) {
109156             return parent.moduleSpecifier;
109157         }
109158         // class ... /**/extends [|name|] ...
109159         // class ... /**/implements [|name|] ...
109160         // class ... /**/implements name1, name2 ...
109161         // interface ... /**/extends [|name|] ...
109162         // interface ... /**/extends name1, name2 ...
109163         if ((node.kind === 90 /* ExtendsKeyword */ || node.kind === 113 /* ImplementsKeyword */) && ts.isHeritageClause(parent) && parent.token === node.kind) {
109164             var location = getAdjustedLocationForHeritageClause(parent);
109165             if (location) {
109166                 return location;
109167             }
109168         }
109169         if (node.kind === 90 /* ExtendsKeyword */) {
109170             // ... <T /**/extends [|U|]> ...
109171             if (ts.isTypeParameterDeclaration(parent) && parent.constraint && ts.isTypeReferenceNode(parent.constraint)) {
109172                 return parent.constraint.typeName;
109173             }
109174             // ... T /**/extends [|U|] ? ...
109175             if (ts.isConditionalTypeNode(parent) && ts.isTypeReferenceNode(parent.extendsType)) {
109176                 return parent.extendsType.typeName;
109177             }
109178         }
109179         // ... T extends /**/infer [|U|] ? ...
109180         if (node.kind === 132 /* InferKeyword */ && ts.isInferTypeNode(parent)) {
109181             return parent.typeParameter.name;
109182         }
109183         // { [ [|K|] /**/in keyof T]: ... }
109184         if (node.kind === 97 /* InKeyword */ && ts.isTypeParameterDeclaration(parent) && ts.isMappedTypeNode(parent.parent)) {
109185             return parent.name;
109186         }
109187         // /**/keyof [|T|]
109188         if (node.kind === 134 /* KeyOfKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 134 /* KeyOfKeyword */ &&
109189             ts.isTypeReferenceNode(parent.type)) {
109190             return parent.type.typeName;
109191         }
109192         // /**/readonly [|name|][]
109193         if (node.kind === 138 /* ReadonlyKeyword */ && ts.isTypeOperatorNode(parent) && parent.operator === 138 /* ReadonlyKeyword */ &&
109194             ts.isArrayTypeNode(parent.type) && ts.isTypeReferenceNode(parent.type.elementType)) {
109195             return parent.type.elementType.typeName;
109196         }
109197         if (!forRename) {
109198             // /**/new [|name|]
109199             // /**/void [|name|]
109200             // /**/void obj.[|name|]
109201             // /**/typeof [|name|]
109202             // /**/typeof obj.[|name|]
109203             // /**/await [|name|]
109204             // /**/await obj.[|name|]
109205             // /**/yield [|name|]
109206             // /**/yield obj.[|name|]
109207             // /**/delete obj.[|name|]
109208             if (node.kind === 99 /* NewKeyword */ && ts.isNewExpression(parent) ||
109209                 node.kind === 110 /* VoidKeyword */ && ts.isVoidExpression(parent) ||
109210                 node.kind === 108 /* TypeOfKeyword */ && ts.isTypeOfExpression(parent) ||
109211                 node.kind === 127 /* AwaitKeyword */ && ts.isAwaitExpression(parent) ||
109212                 node.kind === 121 /* YieldKeyword */ && ts.isYieldExpression(parent) ||
109213                 node.kind === 85 /* DeleteKeyword */ && ts.isDeleteExpression(parent)) {
109214                 if (parent.expression) {
109215                     return ts.skipOuterExpressions(parent.expression);
109216                 }
109217             }
109218             // left /**/in [|name|]
109219             // left /**/instanceof [|name|]
109220             if ((node.kind === 97 /* InKeyword */ || node.kind === 98 /* InstanceOfKeyword */) && ts.isBinaryExpression(parent) && parent.operatorToken === node) {
109221                 return ts.skipOuterExpressions(parent.right);
109222             }
109223             // left /**/as [|name|]
109224             if (node.kind === 123 /* AsKeyword */ && ts.isAsExpression(parent) && ts.isTypeReferenceNode(parent.type)) {
109225                 return parent.type.typeName;
109226             }
109227             // for (... /**/in [|name|])
109228             // for (... /**/of [|name|])
109229             if (node.kind === 97 /* InKeyword */ && ts.isForInStatement(parent) ||
109230                 node.kind === 152 /* OfKeyword */ && ts.isForOfStatement(parent)) {
109231                 return ts.skipOuterExpressions(parent.expression);
109232             }
109233         }
109234         return node;
109235     }
109236     /**
109237      * Adjusts the location used for "find references" and "go to definition" when the cursor was not
109238      * on a property name.
109239      */
109240     function getAdjustedReferenceLocation(node) {
109241         return getAdjustedLocation(node, /*forRename*/ false);
109242     }
109243     ts.getAdjustedReferenceLocation = getAdjustedReferenceLocation;
109244     /**
109245      * Adjusts the location used for "rename" when the cursor was not on a property name.
109246      */
109247     function getAdjustedRenameLocation(node) {
109248         return getAdjustedLocation(node, /*forRename*/ true);
109249     }
109250     ts.getAdjustedRenameLocation = getAdjustedRenameLocation;
109251     /**
109252      * Gets the token whose text has range [start, end) and
109253      * position >= start and (position < end or (position === end && token is literal or keyword or identifier))
109254      */
109255     function getTouchingPropertyName(sourceFile, position) {
109256         return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind) || ts.isPrivateIdentifier(n); });
109257     }
109258     ts.getTouchingPropertyName = getTouchingPropertyName;
109259     /**
109260      * Returns the token if position is in [start, end).
109261      * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true
109262      */
109263     function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) {
109264         return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false);
109265     }
109266     ts.getTouchingToken = getTouchingToken;
109267     /** Returns a token if position is in [start-of-leading-trivia, end) */
109268     function getTokenAtPosition(sourceFile, position) {
109269         return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false);
109270     }
109271     ts.getTokenAtPosition = getTokenAtPosition;
109272     /** Get the token whose text contains the position */
109273     function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) {
109274         var current = sourceFile;
109275         outer: while (true) {
109276             // find the child that contains 'position'
109277             for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) {
109278                 var child = _a[_i];
109279                 var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true);
109280                 if (start > position) {
109281                     // If this child begins after position, then all subsequent children will as well.
109282                     break;
109283                 }
109284                 var end = child.getEnd();
109285                 if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) {
109286                     current = child;
109287                     continue outer;
109288                 }
109289                 else if (includePrecedingTokenAtEndPosition && end === position) {
109290                     var previousToken = findPrecedingToken(position, sourceFile, child);
109291                     if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) {
109292                         return previousToken;
109293                     }
109294                 }
109295             }
109296             return current;
109297         }
109298     }
109299     /**
109300      * The token on the left of the position is the token that strictly includes the position
109301      * or sits to the left of the cursor if it is on a boundary. For example
109302      *
109303      *   fo|o               -> will return foo
109304      *   foo <comment> |bar -> will return foo
109305      *
109306      */
109307     function findTokenOnLeftOfPosition(file, position) {
109308         // Ideally, getTokenAtPosition should return a token. However, it is currently
109309         // broken, so we do a check to make sure the result was indeed a token.
109310         var tokenAtPosition = getTokenAtPosition(file, position);
109311         if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
109312             return tokenAtPosition;
109313         }
109314         return findPrecedingToken(position, file);
109315     }
109316     ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
109317     function findNextToken(previousToken, parent, sourceFile) {
109318         return find(parent);
109319         function find(n) {
109320             if (ts.isToken(n) && n.pos === previousToken.end) {
109321                 // this is token that starts at the end of previous token - return it
109322                 return n;
109323             }
109324             return ts.firstDefined(n.getChildren(sourceFile), function (child) {
109325                 var shouldDiveInChildNode = 
109326                 // previous token is enclosed somewhere in the child
109327                 (child.pos <= previousToken.pos && child.end > previousToken.end) ||
109328                     // previous token ends exactly at the beginning of child
109329                     (child.pos === previousToken.end);
109330                 return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined;
109331             });
109332         }
109333     }
109334     ts.findNextToken = findNextToken;
109335     /**
109336      * Finds the rightmost token satisfying `token.end <= position`,
109337      * excluding `JsxText` tokens containing only whitespace.
109338      */
109339     function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) {
109340         var result = find(startNode || sourceFile);
109341         ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result)));
109342         return result;
109343         function find(n) {
109344             if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) {
109345                 return n;
109346             }
109347             var children = n.getChildren(sourceFile);
109348             for (var i = 0; i < children.length; i++) {
109349                 var child = children[i];
109350                 // Note that the span of a node's tokens is [node.getStart(...), node.end).
109351                 // Given that `position < child.end` and child has constituent tokens, we distinguish these cases:
109352                 // 1) `position` precedes `child`'s tokens or `child` has no tokens (ie: in a comment or whitespace preceding `child`):
109353                 // we need to find the last token in a previous child.
109354                 // 2) `position` is within the same span: we recurse on `child`.
109355                 if (position < child.end) {
109356                     var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc);
109357                     var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
109358                         !nodeHasTokens(child, sourceFile) ||
109359                         isWhiteSpaceOnlyJsxText(child);
109360                     if (lookInPreviousChild) {
109361                         // actual start of the node is past the position - previous token should be at the end of previous child
109362                         var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
109363                         return candidate_1 && findRightmostToken(candidate_1, sourceFile);
109364                     }
109365                     else {
109366                         // candidate should be in this node
109367                         return find(child);
109368                     }
109369                 }
109370             }
109371             ts.Debug.assert(startNode !== undefined || n.kind === 290 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
109372             // Here we know that none of child token nodes embrace the position,
109373             // the only known case is when position is at the end of the file.
109374             // Try to find the rightmost token in the file without filtering.
109375             // Namely we are skipping the check: 'position < node.end'
109376             var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
109377             return candidate && findRightmostToken(candidate, sourceFile);
109378         }
109379     }
109380     ts.findPrecedingToken = findPrecedingToken;
109381     function isNonWhitespaceToken(n) {
109382         return ts.isToken(n) && !isWhiteSpaceOnlyJsxText(n);
109383     }
109384     function findRightmostToken(n, sourceFile) {
109385         if (isNonWhitespaceToken(n)) {
109386             return n;
109387         }
109388         var children = n.getChildren(sourceFile);
109389         var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
109390         return candidate && findRightmostToken(candidate, sourceFile);
109391     }
109392     /**
109393      * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
109394      */
109395     function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
109396         for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
109397             var child = children[i];
109398             if (isWhiteSpaceOnlyJsxText(child)) {
109399                 ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
109400             }
109401             else if (nodeHasTokens(children[i], sourceFile)) {
109402                 return children[i];
109403             }
109404         }
109405     }
109406     function isInString(sourceFile, position, previousToken) {
109407         if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); }
109408         if (previousToken && ts.isStringTextContainingNode(previousToken)) {
109409             var start = previousToken.getStart(sourceFile);
109410             var end = previousToken.getEnd();
109411             // To be "in" one of these literals, the position has to be:
109412             //   1. entirely within the token text.
109413             //   2. at the end position of an unterminated token.
109414             //   3. at the end of a regular expression (due to trailing flags like '/foo/g').
109415             if (start < position && position < end) {
109416                 return true;
109417             }
109418             if (position === end) {
109419                 return !!previousToken.isUnterminated;
109420             }
109421         }
109422         return false;
109423     }
109424     ts.isInString = isInString;
109425     /**
109426      * returns true if the position is in between the open and close elements of an JSX expression.
109427      */
109428     function isInsideJsxElementOrAttribute(sourceFile, position) {
109429         var token = getTokenAtPosition(sourceFile, position);
109430         if (!token) {
109431             return false;
109432         }
109433         if (token.kind === 11 /* JsxText */) {
109434             return true;
109435         }
109436         // <div>Hello |</div>
109437         if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 11 /* JsxText */) {
109438             return true;
109439         }
109440         // <div> { | </div> or <div a={| </div>
109441         if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxExpression */) {
109442             return true;
109443         }
109444         // <div> {
109445         // |
109446         // } < /div>
109447         if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 276 /* JsxExpression */) {
109448             return true;
109449         }
109450         // <div>|</div>
109451         if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 269 /* JsxClosingElement */) {
109452             return true;
109453         }
109454         return false;
109455     }
109456     ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
109457     function isWhiteSpaceOnlyJsxText(node) {
109458         return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
109459     }
109460     function isInTemplateString(sourceFile, position) {
109461         var token = getTokenAtPosition(sourceFile, position);
109462         return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
109463     }
109464     ts.isInTemplateString = isInTemplateString;
109465     function isInJSXText(sourceFile, position) {
109466         var token = getTokenAtPosition(sourceFile, position);
109467         if (ts.isJsxText(token)) {
109468             return true;
109469         }
109470         if (token.kind === 18 /* OpenBraceToken */ && ts.isJsxExpression(token.parent) && ts.isJsxElement(token.parent.parent)) {
109471             return true;
109472         }
109473         if (token.kind === 29 /* LessThanToken */ && ts.isJsxOpeningLikeElement(token.parent) && ts.isJsxElement(token.parent.parent)) {
109474             return true;
109475         }
109476         return false;
109477     }
109478     ts.isInJSXText = isInJSXText;
109479     function findPrecedingMatchingToken(token, matchingTokenKind, sourceFile) {
109480         var tokenKind = token.kind;
109481         var remainingMatchingTokens = 0;
109482         while (true) {
109483             var preceding = findPrecedingToken(token.getFullStart(), sourceFile);
109484             if (!preceding) {
109485                 return undefined;
109486             }
109487             token = preceding;
109488             if (token.kind === matchingTokenKind) {
109489                 if (remainingMatchingTokens === 0) {
109490                     return token;
109491                 }
109492                 remainingMatchingTokens--;
109493             }
109494             else if (token.kind === tokenKind) {
109495                 remainingMatchingTokens++;
109496             }
109497         }
109498     }
109499     ts.findPrecedingMatchingToken = findPrecedingMatchingToken;
109500     function removeOptionality(type, isOptionalExpression, isOptionalChain) {
109501         return isOptionalExpression ? type.getNonNullableType() :
109502             isOptionalChain ? type.getNonOptionalType() :
109503                 type;
109504     }
109505     ts.removeOptionality = removeOptionality;
109506     function isPossiblyTypeArgumentPosition(token, sourceFile, checker) {
109507         var info = getPossibleTypeArgumentsInfo(token, sourceFile);
109508         return info !== undefined && (ts.isPartOfTypeNode(info.called) ||
109509             getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 ||
109510             isPossiblyTypeArgumentPosition(info.called, sourceFile, checker));
109511     }
109512     ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition;
109513     function getPossibleGenericSignatures(called, typeArgumentCount, checker) {
109514         var type = checker.getTypeAtLocation(called);
109515         if (ts.isOptionalChain(called.parent)) {
109516             type = removeOptionality(type, ts.isOptionalChainRoot(called.parent), /*isOptionalChain*/ true);
109517         }
109518         var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures();
109519         return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; });
109520     }
109521     ts.getPossibleGenericSignatures = getPossibleGenericSignatures;
109522     // Get info for an expression like `f <` that may be the start of type arguments.
109523     function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) {
109524         var token = tokenIn;
109525         // This function determines if the node could be type argument position
109526         // Since during editing, when type argument list is not complete,
109527         // the tree could be of any shape depending on the tokens parsed before current node,
109528         // scanning of the previous identifier followed by "<" before current node would give us better result
109529         // Note that we also balance out the already provided type arguments, arrays, object literals while doing so
109530         var remainingLessThanTokens = 0;
109531         var nTypeArguments = 0;
109532         while (token) {
109533             switch (token.kind) {
109534                 case 29 /* LessThanToken */:
109535                     // Found the beginning of the generic argument expression
109536                     token = findPrecedingToken(token.getFullStart(), sourceFile);
109537                     if (token && token.kind === 28 /* QuestionDotToken */) {
109538                         token = findPrecedingToken(token.getFullStart(), sourceFile);
109539                     }
109540                     if (!token || !ts.isIdentifier(token))
109541                         return undefined;
109542                     if (!remainingLessThanTokens) {
109543                         return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments };
109544                     }
109545                     remainingLessThanTokens--;
109546                     break;
109547                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
109548                     remainingLessThanTokens = +3;
109549                     break;
109550                 case 48 /* GreaterThanGreaterThanToken */:
109551                     remainingLessThanTokens = +2;
109552                     break;
109553                 case 31 /* GreaterThanToken */:
109554                     remainingLessThanTokens++;
109555                     break;
109556                 case 19 /* CloseBraceToken */:
109557                     // This can be object type, skip until we find the matching open brace token
109558                     // Skip until the matching open brace token
109559                     token = findPrecedingMatchingToken(token, 18 /* OpenBraceToken */, sourceFile);
109560                     if (!token)
109561                         return undefined;
109562                     break;
109563                 case 21 /* CloseParenToken */:
109564                     // This can be object type, skip until we find the matching open brace token
109565                     // Skip until the matching open brace token
109566                     token = findPrecedingMatchingToken(token, 20 /* OpenParenToken */, sourceFile);
109567                     if (!token)
109568                         return undefined;
109569                     break;
109570                 case 23 /* CloseBracketToken */:
109571                     // This can be object type, skip until we find the matching open brace token
109572                     // Skip until the matching open brace token
109573                     token = findPrecedingMatchingToken(token, 22 /* OpenBracketToken */, sourceFile);
109574                     if (!token)
109575                         return undefined;
109576                     break;
109577                 // Valid tokens in a type name. Skip.
109578                 case 27 /* CommaToken */:
109579                     nTypeArguments++;
109580                     break;
109581                 case 38 /* EqualsGreaterThanToken */:
109582                 // falls through
109583                 case 75 /* Identifier */:
109584                 case 10 /* StringLiteral */:
109585                 case 8 /* NumericLiteral */:
109586                 case 9 /* BigIntLiteral */:
109587                 case 106 /* TrueKeyword */:
109588                 case 91 /* FalseKeyword */:
109589                 // falls through
109590                 case 108 /* TypeOfKeyword */:
109591                 case 90 /* ExtendsKeyword */:
109592                 case 134 /* KeyOfKeyword */:
109593                 case 24 /* DotToken */:
109594                 case 51 /* BarToken */:
109595                 case 57 /* QuestionToken */:
109596                 case 58 /* ColonToken */:
109597                     break;
109598                 default:
109599                     if (ts.isTypeNode(token)) {
109600                         break;
109601                     }
109602                     // Invalid token in type
109603                     return undefined;
109604             }
109605             token = findPrecedingToken(token.getFullStart(), sourceFile);
109606         }
109607         return undefined;
109608     }
109609     ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo;
109610     /**
109611      * Returns true if the cursor at position in sourceFile is within a comment.
109612      *
109613      * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
109614      * @param predicate Additional predicate to test on the comment range.
109615      */
109616     function isInComment(sourceFile, position, tokenAtPosition) {
109617         return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition);
109618     }
109619     ts.isInComment = isInComment;
109620     function hasDocComment(sourceFile, position) {
109621         var token = getTokenAtPosition(sourceFile, position);
109622         return !!ts.findAncestor(token, ts.isJSDoc);
109623     }
109624     ts.hasDocComment = hasDocComment;
109625     function nodeHasTokens(n, sourceFile) {
109626         // If we have a token or node that has a non-zero width, it must have tokens.
109627         // Note: getWidth() does not take trivia into account.
109628         return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0;
109629     }
109630     function getNodeModifiers(node) {
109631         var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */;
109632         var result = [];
109633         if (flags & 8 /* Private */)
109634             result.push("private" /* privateMemberModifier */);
109635         if (flags & 16 /* Protected */)
109636             result.push("protected" /* protectedMemberModifier */);
109637         if (flags & 4 /* Public */)
109638             result.push("public" /* publicMemberModifier */);
109639         if (flags & 32 /* Static */)
109640             result.push("static" /* staticModifier */);
109641         if (flags & 128 /* Abstract */)
109642             result.push("abstract" /* abstractModifier */);
109643         if (flags & 1 /* Export */)
109644             result.push("export" /* exportedModifier */);
109645         if (node.flags & 8388608 /* Ambient */)
109646             result.push("declare" /* ambientModifier */);
109647         if (node.kind === 259 /* ExportAssignment */)
109648             result.push("export" /* exportedModifier */);
109649         return result.length > 0 ? result.join(",") : "" /* none */;
109650     }
109651     ts.getNodeModifiers = getNodeModifiers;
109652     function getTypeArgumentOrTypeParameterList(node) {
109653         if (node.kind === 169 /* TypeReference */ || node.kind === 196 /* CallExpression */) {
109654             return node.typeArguments;
109655         }
109656         if (ts.isFunctionLike(node) || node.kind === 245 /* ClassDeclaration */ || node.kind === 246 /* InterfaceDeclaration */) {
109657             return node.typeParameters;
109658         }
109659         return undefined;
109660     }
109661     ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList;
109662     function isComment(kind) {
109663         return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */;
109664     }
109665     ts.isComment = isComment;
109666     function isStringOrRegularExpressionOrTemplateLiteral(kind) {
109667         if (kind === 10 /* StringLiteral */
109668             || kind === 13 /* RegularExpressionLiteral */
109669             || ts.isTemplateLiteralKind(kind)) {
109670             return true;
109671         }
109672         return false;
109673     }
109674     ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral;
109675     function isPunctuation(kind) {
109676         return 18 /* FirstPunctuation */ <= kind && kind <= 74 /* LastPunctuation */;
109677     }
109678     ts.isPunctuation = isPunctuation;
109679     function isInsideTemplateLiteral(node, position, sourceFile) {
109680         return ts.isTemplateLiteralKind(node.kind)
109681             && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end);
109682     }
109683     ts.isInsideTemplateLiteral = isInsideTemplateLiteral;
109684     function isAccessibilityModifier(kind) {
109685         switch (kind) {
109686             case 119 /* PublicKeyword */:
109687             case 117 /* PrivateKeyword */:
109688             case 118 /* ProtectedKeyword */:
109689                 return true;
109690         }
109691         return false;
109692     }
109693     ts.isAccessibilityModifier = isAccessibilityModifier;
109694     function cloneCompilerOptions(options) {
109695         var result = ts.clone(options);
109696         ts.setConfigFileInOptions(result, options && options.configFile);
109697         return result;
109698     }
109699     ts.cloneCompilerOptions = cloneCompilerOptions;
109700     function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
109701         if (node.kind === 192 /* ArrayLiteralExpression */ ||
109702             node.kind === 193 /* ObjectLiteralExpression */) {
109703             // [a,b,c] from:
109704             // [a, b, c] = someExpression;
109705             if (node.parent.kind === 209 /* BinaryExpression */ &&
109706                 node.parent.left === node &&
109707                 node.parent.operatorToken.kind === 62 /* EqualsToken */) {
109708                 return true;
109709             }
109710             // [a, b, c] from:
109711             // for([a, b, c] of expression)
109712             if (node.parent.kind === 232 /* ForOfStatement */ &&
109713                 node.parent.initializer === node) {
109714                 return true;
109715             }
109716             // [a, b, c] of
109717             // [x, [a, b, c] ] = someExpression
109718             // or
109719             // {x, a: {a, b, c} } = someExpression
109720             if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 281 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
109721                 return true;
109722             }
109723         }
109724         return false;
109725     }
109726     ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
109727     function isInReferenceComment(sourceFile, position) {
109728         return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true);
109729     }
109730     ts.isInReferenceComment = isInReferenceComment;
109731     function isInNonReferenceComment(sourceFile, position) {
109732         return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false);
109733     }
109734     ts.isInNonReferenceComment = isInNonReferenceComment;
109735     function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
109736         var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined);
109737         return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
109738     }
109739     function getReplacementSpanForContextToken(contextToken) {
109740         if (!contextToken)
109741             return undefined;
109742         switch (contextToken.kind) {
109743             case 10 /* StringLiteral */:
109744             case 14 /* NoSubstitutionTemplateLiteral */:
109745                 return createTextSpanFromStringLiteralLikeContent(contextToken);
109746             default:
109747                 return createTextSpanFromNode(contextToken);
109748         }
109749     }
109750     ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken;
109751     function createTextSpanFromNode(node, sourceFile, endNode) {
109752         return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd());
109753     }
109754     ts.createTextSpanFromNode = createTextSpanFromNode;
109755     function createTextSpanFromStringLiteralLikeContent(node) {
109756         if (node.isUnterminated)
109757             return undefined;
109758         return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1);
109759     }
109760     ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent;
109761     function createTextRangeFromNode(node, sourceFile) {
109762         return ts.createRange(node.getStart(sourceFile), node.end);
109763     }
109764     ts.createTextRangeFromNode = createTextRangeFromNode;
109765     function createTextSpanFromRange(range) {
109766         return ts.createTextSpanFromBounds(range.pos, range.end);
109767     }
109768     ts.createTextSpanFromRange = createTextSpanFromRange;
109769     function createTextRangeFromSpan(span) {
109770         return ts.createRange(span.start, span.start + span.length);
109771     }
109772     ts.createTextRangeFromSpan = createTextRangeFromSpan;
109773     function createTextChangeFromStartLength(start, length, newText) {
109774         return createTextChange(ts.createTextSpan(start, length), newText);
109775     }
109776     ts.createTextChangeFromStartLength = createTextChangeFromStartLength;
109777     function createTextChange(span, newText) {
109778         return { span: span, newText: newText };
109779     }
109780     ts.createTextChange = createTextChange;
109781     ts.typeKeywords = [
109782         125 /* AnyKeyword */,
109783         124 /* AssertsKeyword */,
109784         151 /* BigIntKeyword */,
109785         128 /* BooleanKeyword */,
109786         91 /* FalseKeyword */,
109787         134 /* KeyOfKeyword */,
109788         137 /* NeverKeyword */,
109789         100 /* NullKeyword */,
109790         140 /* NumberKeyword */,
109791         141 /* ObjectKeyword */,
109792         138 /* ReadonlyKeyword */,
109793         143 /* StringKeyword */,
109794         144 /* SymbolKeyword */,
109795         106 /* TrueKeyword */,
109796         110 /* VoidKeyword */,
109797         146 /* UndefinedKeyword */,
109798         147 /* UniqueKeyword */,
109799         148 /* UnknownKeyword */,
109800     ];
109801     function isTypeKeyword(kind) {
109802         return ts.contains(ts.typeKeywords, kind);
109803     }
109804     ts.isTypeKeyword = isTypeKeyword;
109805     function isTypeKeywordToken(node) {
109806         return node.kind === 145 /* TypeKeyword */;
109807     }
109808     ts.isTypeKeywordToken = isTypeKeywordToken;
109809     /** True if the symbol is for an external module, as opposed to a namespace. */
109810     function isExternalModuleSymbol(moduleSymbol) {
109811         return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
109812     }
109813     ts.isExternalModuleSymbol = isExternalModuleSymbol;
109814     function nodeSeenTracker() {
109815         var seen = [];
109816         return function (node) {
109817             var id = ts.getNodeId(node);
109818             return !seen[id] && (seen[id] = true);
109819         };
109820     }
109821     ts.nodeSeenTracker = nodeSeenTracker;
109822     function getSnapshotText(snap) {
109823         return snap.getText(0, snap.getLength());
109824     }
109825     ts.getSnapshotText = getSnapshotText;
109826     function repeatString(str, count) {
109827         var result = "";
109828         for (var i = 0; i < count; i++) {
109829             result += str;
109830         }
109831         return result;
109832     }
109833     ts.repeatString = repeatString;
109834     function skipConstraint(type) {
109835         return type.isTypeParameter() ? type.getConstraint() || type : type;
109836     }
109837     ts.skipConstraint = skipConstraint;
109838     function getNameFromPropertyName(name) {
109839         return name.kind === 154 /* ComputedPropertyName */
109840             // treat computed property names where expression is string/numeric literal as just string/numeric literal
109841             ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined
109842             : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name);
109843     }
109844     ts.getNameFromPropertyName = getNameFromPropertyName;
109845     function programContainsModules(program) {
109846         return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); });
109847     }
109848     ts.programContainsModules = programContainsModules;
109849     function programContainsEs6Modules(program) {
109850         return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; });
109851     }
109852     ts.programContainsEs6Modules = programContainsEs6Modules;
109853     function compilerOptionsIndicateEs6Modules(compilerOptions) {
109854         return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit;
109855     }
109856     ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules;
109857     function createModuleSpecifierResolutionHost(program, host) {
109858         // Mix in `getProbableSymlinks` from Program when host doesn't have it
109859         // in order for non-Project hosts to have a symlinks cache.
109860         return {
109861             fileExists: function (fileName) { return program.fileExists(fileName); },
109862             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
109863             readFile: ts.maybeBind(host, host.readFile),
109864             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
109865             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || (function () { return program.getProbableSymlinks(); }),
109866             getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation),
109867             getSourceFiles: function () { return program.getSourceFiles(); },
109868             redirectTargetsMap: program.redirectTargetsMap,
109869             getProjectReferenceRedirect: function (fileName) { return program.getProjectReferenceRedirect(fileName); },
109870             isSourceOfProjectReferenceRedirect: function (fileName) { return program.isSourceOfProjectReferenceRedirect(fileName); },
109871         };
109872     }
109873     ts.createModuleSpecifierResolutionHost = createModuleSpecifierResolutionHost;
109874     function getModuleSpecifierResolverHost(program, host) {
109875         return __assign(__assign({}, createModuleSpecifierResolutionHost(program, host)), { getCommonSourceDirectory: function () { return program.getCommonSourceDirectory(); } });
109876     }
109877     ts.getModuleSpecifierResolverHost = getModuleSpecifierResolverHost;
109878     function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) {
109879         return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined;
109880     }
109881     ts.makeImportIfNecessary = makeImportIfNecessary;
109882     function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) {
109883         return ts.createImportDeclaration(
109884         /*decorators*/ undefined, 
109885         /*modifiers*/ undefined, defaultImport || namedImports
109886             ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined, isTypeOnly)
109887             : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier);
109888     }
109889     ts.makeImport = makeImport;
109890     function makeStringLiteral(text, quotePreference) {
109891         return ts.createLiteral(text, quotePreference === 0 /* Single */);
109892     }
109893     ts.makeStringLiteral = makeStringLiteral;
109894     var QuotePreference;
109895     (function (QuotePreference) {
109896         QuotePreference[QuotePreference["Single"] = 0] = "Single";
109897         QuotePreference[QuotePreference["Double"] = 1] = "Double";
109898     })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {}));
109899     function quotePreferenceFromString(str, sourceFile) {
109900         return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
109901     }
109902     ts.quotePreferenceFromString = quotePreferenceFromString;
109903     function getQuotePreference(sourceFile, preferences) {
109904         if (preferences.quotePreference && preferences.quotePreference !== "auto") {
109905             return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
109906         }
109907         else {
109908             var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral);
109909             return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
109910         }
109911     }
109912     ts.getQuotePreference = getQuotePreference;
109913     function getQuoteFromPreference(qp) {
109914         switch (qp) {
109915             case 0 /* Single */: return "'";
109916             case 1 /* Double */: return '"';
109917             default: return ts.Debug.assertNever(qp);
109918         }
109919     }
109920     ts.getQuoteFromPreference = getQuoteFromPreference;
109921     function symbolNameNoDefault(symbol) {
109922         var escaped = symbolEscapedNameNoDefault(symbol);
109923         return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
109924     }
109925     ts.symbolNameNoDefault = symbolNameNoDefault;
109926     function symbolEscapedNameNoDefault(symbol) {
109927         if (symbol.escapedName !== "default" /* Default */) {
109928             return symbol.escapedName;
109929         }
109930         return ts.firstDefined(symbol.declarations, function (decl) {
109931             var name = ts.getNameOfDeclaration(decl);
109932             return name && name.kind === 75 /* Identifier */ ? name.escapedText : undefined;
109933         });
109934     }
109935     ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
109936     function isObjectBindingElementWithoutPropertyName(bindingElement) {
109937         return ts.isBindingElement(bindingElement) &&
109938             ts.isObjectBindingPattern(bindingElement.parent) &&
109939             ts.isIdentifier(bindingElement.name) &&
109940             !bindingElement.propertyName;
109941     }
109942     ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName;
109943     function getPropertySymbolFromBindingElement(checker, bindingElement) {
109944         var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
109945         return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
109946     }
109947     ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
109948     /**
109949      * Find symbol of the given property-name and add the symbol to the given result array
109950      * @param symbol a symbol to start searching for the given propertyName
109951      * @param propertyName a name of property to search for
109952      * @param result an array of symbol of found property symbols
109953      * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
109954      *                                The value of previousIterationSymbol is undefined when the function is first called.
109955      */
109956     function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) {
109957         var seen = ts.createMap();
109958         return recur(symbol);
109959         function recur(symbol) {
109960             // Use `addToSeen` to ensure we don't infinitely recurse in this situation:
109961             //      interface C extends C {
109962             //          /*findRef*/propName: string;
109963             //      }
109964             if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol)))
109965                 return;
109966             return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) {
109967                 var type = checker.getTypeAtLocation(typeReference);
109968                 var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName);
109969                 // Visit the typeReference as well to see if it directly or indirectly uses that property
109970                 return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol));
109971             }); });
109972         }
109973     }
109974     ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes;
109975     function isMemberSymbolInBaseType(memberSymbol, checker) {
109976         return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false;
109977     }
109978     ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType;
109979     function getParentNodeInSpan(node, file, span) {
109980         if (!node)
109981             return undefined;
109982         while (node.parent) {
109983             if (ts.isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) {
109984                 return node;
109985             }
109986             node = node.parent;
109987         }
109988     }
109989     ts.getParentNodeInSpan = getParentNodeInSpan;
109990     function spanContainsNode(span, node, file) {
109991         return ts.textSpanContainsPosition(span, node.getStart(file)) &&
109992             node.getEnd() <= ts.textSpanEnd(span);
109993     }
109994     function findModifier(node, kind) {
109995         return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; });
109996     }
109997     ts.findModifier = findModifier;
109998     function insertImports(changes, sourceFile, imports, blankLineBetween) {
109999         var decl = ts.isArray(imports) ? imports[0] : imports;
110000         var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax;
110001         var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); });
110002         if (lastImportDeclaration) {
110003             if (ts.isArray(imports)) {
110004                 changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports);
110005             }
110006             else {
110007                 changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports);
110008             }
110009         }
110010         else if (ts.isArray(imports)) {
110011             changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween);
110012         }
110013         else {
110014             changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween);
110015         }
110016     }
110017     ts.insertImports = insertImports;
110018     function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) {
110019         ts.Debug.assert(importClause.isTypeOnly);
110020         return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken);
110021     }
110022     ts.getTypeKeywordOfTypeOnlyImport = getTypeKeywordOfTypeOnlyImport;
110023     function textSpansEqual(a, b) {
110024         return !!a && !!b && a.start === b.start && a.length === b.length;
110025     }
110026     ts.textSpansEqual = textSpansEqual;
110027     function documentSpansEqual(a, b) {
110028         return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan);
110029     }
110030     ts.documentSpansEqual = documentSpansEqual;
110031     /**
110032      * Iterates through 'array' by index and performs the callback on each element of array until the callback
110033      * returns a truthy value, then returns that value.
110034      * If no such value is found, the callback is applied to each element of array and undefined is returned.
110035      */
110036     function forEachUnique(array, callback) {
110037         if (array) {
110038             for (var i = 0; i < array.length; i++) {
110039                 if (array.indexOf(array[i]) === i) {
110040                     var result = callback(array[i], i);
110041                     if (result) {
110042                         return result;
110043                     }
110044                 }
110045             }
110046         }
110047         return undefined;
110048     }
110049     ts.forEachUnique = forEachUnique;
110050     // #endregion
110051     // Display-part writer helpers
110052     // #region
110053     function isFirstDeclarationOfSymbolParameter(symbol) {
110054         return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 156 /* Parameter */;
110055     }
110056     ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter;
110057     var displayPartWriter = getDisplayPartWriter();
110058     function getDisplayPartWriter() {
110059         var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios
110060         var displayParts;
110061         var lineStart;
110062         var indent;
110063         var length;
110064         resetWriter();
110065         var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); };
110066         return {
110067             displayParts: function () {
110068                 var finalText = displayParts.length && displayParts[displayParts.length - 1].text;
110069                 if (length > absoluteMaximumLength && finalText && finalText !== "...") {
110070                     if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) {
110071                         displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space));
110072                     }
110073                     displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation));
110074                 }
110075                 return displayParts;
110076             },
110077             writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); },
110078             writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); },
110079             writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
110080             writeTrailingSemicolon: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); },
110081             writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); },
110082             writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
110083             writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); },
110084             writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); },
110085             writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
110086             writeSymbol: writeSymbol,
110087             writeLine: writeLine,
110088             write: unknownWrite,
110089             writeComment: unknownWrite,
110090             getText: function () { return ""; },
110091             getTextPos: function () { return 0; },
110092             getColumn: function () { return 0; },
110093             getLine: function () { return 0; },
110094             isAtStartOfLine: function () { return false; },
110095             hasTrailingWhitespace: function () { return false; },
110096             hasTrailingComment: function () { return false; },
110097             rawWrite: ts.notImplemented,
110098             getIndent: function () { return indent; },
110099             increaseIndent: function () { indent++; },
110100             decreaseIndent: function () { indent--; },
110101             clear: resetWriter,
110102             trackSymbol: ts.noop,
110103             reportInaccessibleThisError: ts.noop,
110104             reportInaccessibleUniqueSymbolError: ts.noop,
110105             reportPrivateInBaseOfClassExpression: ts.noop,
110106         };
110107         function writeIndent() {
110108             if (length > absoluteMaximumLength)
110109                 return;
110110             if (lineStart) {
110111                 var indentString = ts.getIndentString(indent);
110112                 if (indentString) {
110113                     length += indentString.length;
110114                     displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space));
110115                 }
110116                 lineStart = false;
110117             }
110118         }
110119         function writeKind(text, kind) {
110120             if (length > absoluteMaximumLength)
110121                 return;
110122             writeIndent();
110123             length += text.length;
110124             displayParts.push(displayPart(text, kind));
110125         }
110126         function writeSymbol(text, symbol) {
110127             if (length > absoluteMaximumLength)
110128                 return;
110129             writeIndent();
110130             length += text.length;
110131             displayParts.push(symbolPart(text, symbol));
110132         }
110133         function writeLine() {
110134             if (length > absoluteMaximumLength)
110135                 return;
110136             length += 1;
110137             displayParts.push(lineBreakPart());
110138             lineStart = true;
110139         }
110140         function resetWriter() {
110141             displayParts = [];
110142             lineStart = true;
110143             indent = 0;
110144             length = 0;
110145         }
110146     }
110147     function symbolPart(text, symbol) {
110148         return displayPart(text, displayPartKind(symbol));
110149         function displayPartKind(symbol) {
110150             var flags = symbol.flags;
110151             if (flags & 3 /* Variable */) {
110152                 return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName;
110153             }
110154             else if (flags & 4 /* Property */) {
110155                 return ts.SymbolDisplayPartKind.propertyName;
110156             }
110157             else if (flags & 32768 /* GetAccessor */) {
110158                 return ts.SymbolDisplayPartKind.propertyName;
110159             }
110160             else if (flags & 65536 /* SetAccessor */) {
110161                 return ts.SymbolDisplayPartKind.propertyName;
110162             }
110163             else if (flags & 8 /* EnumMember */) {
110164                 return ts.SymbolDisplayPartKind.enumMemberName;
110165             }
110166             else if (flags & 16 /* Function */) {
110167                 return ts.SymbolDisplayPartKind.functionName;
110168             }
110169             else if (flags & 32 /* Class */) {
110170                 return ts.SymbolDisplayPartKind.className;
110171             }
110172             else if (flags & 64 /* Interface */) {
110173                 return ts.SymbolDisplayPartKind.interfaceName;
110174             }
110175             else if (flags & 384 /* Enum */) {
110176                 return ts.SymbolDisplayPartKind.enumName;
110177             }
110178             else if (flags & 1536 /* Module */) {
110179                 return ts.SymbolDisplayPartKind.moduleName;
110180             }
110181             else if (flags & 8192 /* Method */) {
110182                 return ts.SymbolDisplayPartKind.methodName;
110183             }
110184             else if (flags & 262144 /* TypeParameter */) {
110185                 return ts.SymbolDisplayPartKind.typeParameterName;
110186             }
110187             else if (flags & 524288 /* TypeAlias */) {
110188                 return ts.SymbolDisplayPartKind.aliasName;
110189             }
110190             else if (flags & 2097152 /* Alias */) {
110191                 return ts.SymbolDisplayPartKind.aliasName;
110192             }
110193             return ts.SymbolDisplayPartKind.text;
110194         }
110195     }
110196     ts.symbolPart = symbolPart;
110197     function displayPart(text, kind) {
110198         return { text: text, kind: ts.SymbolDisplayPartKind[kind] };
110199     }
110200     ts.displayPart = displayPart;
110201     function spacePart() {
110202         return displayPart(" ", ts.SymbolDisplayPartKind.space);
110203     }
110204     ts.spacePart = spacePart;
110205     function keywordPart(kind) {
110206         return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword);
110207     }
110208     ts.keywordPart = keywordPart;
110209     function punctuationPart(kind) {
110210         return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation);
110211     }
110212     ts.punctuationPart = punctuationPart;
110213     function operatorPart(kind) {
110214         return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator);
110215     }
110216     ts.operatorPart = operatorPart;
110217     function textOrKeywordPart(text) {
110218         var kind = ts.stringToToken(text);
110219         return kind === undefined
110220             ? textPart(text)
110221             : keywordPart(kind);
110222     }
110223     ts.textOrKeywordPart = textOrKeywordPart;
110224     function textPart(text) {
110225         return displayPart(text, ts.SymbolDisplayPartKind.text);
110226     }
110227     ts.textPart = textPart;
110228     var carriageReturnLineFeed = "\r\n";
110229     /**
110230      * The default is CRLF.
110231      */
110232     function getNewLineOrDefaultFromHost(host, formatSettings) {
110233         var _a;
110234         return (formatSettings === null || formatSettings === void 0 ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) === null || _a === void 0 ? void 0 : _a.call(host)) ||
110235             carriageReturnLineFeed;
110236     }
110237     ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost;
110238     function lineBreakPart() {
110239         return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak);
110240     }
110241     ts.lineBreakPart = lineBreakPart;
110242     function mapToDisplayParts(writeDisplayParts) {
110243         try {
110244             writeDisplayParts(displayPartWriter);
110245             return displayPartWriter.displayParts();
110246         }
110247         finally {
110248             displayPartWriter.clear();
110249         }
110250     }
110251     ts.mapToDisplayParts = mapToDisplayParts;
110252     function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) {
110253         if (flags === void 0) { flags = 0 /* None */; }
110254         return mapToDisplayParts(function (writer) {
110255             typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer);
110256         });
110257     }
110258     ts.typeToDisplayParts = typeToDisplayParts;
110259     function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) {
110260         if (flags === void 0) { flags = 0 /* None */; }
110261         return mapToDisplayParts(function (writer) {
110262             typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer);
110263         });
110264     }
110265     ts.symbolToDisplayParts = symbolToDisplayParts;
110266     function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) {
110267         if (flags === void 0) { flags = 0 /* None */; }
110268         flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */;
110269         return mapToDisplayParts(function (writer) {
110270             typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer);
110271         });
110272     }
110273     ts.signatureToDisplayParts = signatureToDisplayParts;
110274     function isImportOrExportSpecifierName(location) {
110275         return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location;
110276     }
110277     ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
110278     function scriptKindIs(fileName, host) {
110279         var scriptKinds = [];
110280         for (var _i = 2; _i < arguments.length; _i++) {
110281             scriptKinds[_i - 2] = arguments[_i];
110282         }
110283         var scriptKind = getScriptKind(fileName, host);
110284         return ts.some(scriptKinds, function (k) { return k === scriptKind; });
110285     }
110286     ts.scriptKindIs = scriptKindIs;
110287     function getScriptKind(fileName, host) {
110288         // First check to see if the script kind was specified by the host. Chances are the host
110289         // may override the default script kind for the file extension.
110290         return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
110291     }
110292     ts.getScriptKind = getScriptKind;
110293     function getSymbolTarget(symbol, checker) {
110294         var next = symbol;
110295         while (isAliasSymbol(next) || (isTransientSymbol(next) && next.target)) {
110296             if (isTransientSymbol(next) && next.target) {
110297                 next = next.target;
110298             }
110299             else {
110300                 next = ts.skipAlias(next, checker);
110301             }
110302         }
110303         return next;
110304     }
110305     ts.getSymbolTarget = getSymbolTarget;
110306     function isTransientSymbol(symbol) {
110307         return (symbol.flags & 33554432 /* Transient */) !== 0;
110308     }
110309     function isAliasSymbol(symbol) {
110310         return (symbol.flags & 2097152 /* Alias */) !== 0;
110311     }
110312     function getUniqueSymbolId(symbol, checker) {
110313         return ts.getSymbolId(ts.skipAlias(symbol, checker));
110314     }
110315     ts.getUniqueSymbolId = getUniqueSymbolId;
110316     function getFirstNonSpaceCharacterPosition(text, position) {
110317         while (ts.isWhiteSpaceLike(text.charCodeAt(position))) {
110318             position += 1;
110319         }
110320         return position;
110321     }
110322     ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition;
110323     function getPrecedingNonSpaceCharacterPosition(text, position) {
110324         while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) {
110325             position -= 1;
110326         }
110327         return position + 1;
110328     }
110329     ts.getPrecedingNonSpaceCharacterPosition = getPrecedingNonSpaceCharacterPosition;
110330     /**
110331      * Creates a deep, memberwise clone of a node with no source map location.
110332      *
110333      * WARNING: This is an expensive operation and is only intended to be used in refactorings
110334      * and code fixes (because those are triggered by explicit user actions).
110335      */
110336     function getSynthesizedDeepClone(node, includeTrivia) {
110337         if (includeTrivia === void 0) { includeTrivia = true; }
110338         var clone = node && getSynthesizedDeepCloneWorker(node);
110339         if (clone && !includeTrivia)
110340             suppressLeadingAndTrailingTrivia(clone);
110341         return clone;
110342     }
110343     ts.getSynthesizedDeepClone = getSynthesizedDeepClone;
110344     function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) {
110345         if (includeTrivia === void 0) { includeTrivia = true; }
110346         var clone;
110347         if (renameMap && checker && ts.isBindingElement(node) && ts.isIdentifier(node.name) && ts.isObjectBindingPattern(node.parent)) {
110348             var symbol = checker.getSymbolAtLocation(node.name);
110349             var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
110350             if (renameInfo && renameInfo.text !== (node.name || node.propertyName).getText()) {
110351                 clone = ts.setOriginalNode(ts.createBindingElement(node.dotDotDotToken, node.propertyName || node.name, renameInfo, node.initializer), node);
110352             }
110353         }
110354         else if (renameMap && checker && ts.isIdentifier(node)) {
110355             var symbol = checker.getSymbolAtLocation(node);
110356             var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol)));
110357             if (renameInfo) {
110358                 clone = ts.setOriginalNode(ts.createIdentifier(renameInfo.text), node);
110359             }
110360         }
110361         if (!clone) {
110362             clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback);
110363         }
110364         if (clone && !includeTrivia)
110365             suppressLeadingAndTrailingTrivia(clone);
110366         if (callback && clone)
110367             callback(node, clone);
110368         return clone;
110369     }
110370     ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames;
110371     function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) {
110372         var visited = (renameMap || checker || callback) ?
110373             ts.visitEachChild(node, wrapper, ts.nullTransformationContext) :
110374             ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
110375         if (visited === node) {
110376             // This only happens for leaf nodes - internal nodes always see their children change.
110377             var clone_1 = ts.getSynthesizedClone(node);
110378             if (ts.isStringLiteral(clone_1)) {
110379                 clone_1.textSourceNode = node;
110380             }
110381             else if (ts.isNumericLiteral(clone_1)) {
110382                 clone_1.numericLiteralFlags = node.numericLiteralFlags;
110383             }
110384             return ts.setTextRange(clone_1, node);
110385         }
110386         // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
110387         // the new node created by visitEachChild with the extra changes getSynthesizedClone
110388         // would have made.
110389         visited.parent = undefined;
110390         return visited;
110391         function wrapper(node) {
110392             return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback);
110393         }
110394     }
110395     function getSynthesizedDeepClones(nodes, includeTrivia) {
110396         if (includeTrivia === void 0) { includeTrivia = true; }
110397         return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma);
110398     }
110399     ts.getSynthesizedDeepClones = getSynthesizedDeepClones;
110400     /**
110401      * Sets EmitFlags to suppress leading and trailing trivia on the node.
110402      */
110403     function suppressLeadingAndTrailingTrivia(node) {
110404         suppressLeadingTrivia(node);
110405         suppressTrailingTrivia(node);
110406     }
110407     ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia;
110408     /**
110409      * Sets EmitFlags to suppress leading trivia on the node.
110410      */
110411     function suppressLeadingTrivia(node) {
110412         addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild);
110413     }
110414     ts.suppressLeadingTrivia = suppressLeadingTrivia;
110415     /**
110416      * Sets EmitFlags to suppress trailing trivia on the node.
110417      */
110418     function suppressTrailingTrivia(node) {
110419         addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild);
110420     }
110421     ts.suppressTrailingTrivia = suppressTrailingTrivia;
110422     function copyComments(sourceNode, targetNode) {
110423         var sourceFile = sourceNode.getSourceFile();
110424         var text = sourceFile.text;
110425         if (hasLeadingLineBreak(sourceNode, text)) {
110426             copyLeadingComments(sourceNode, targetNode, sourceFile);
110427         }
110428         else {
110429             copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
110430         }
110431         copyTrailingComments(sourceNode, targetNode, sourceFile);
110432     }
110433     ts.copyComments = copyComments;
110434     function hasLeadingLineBreak(node, text) {
110435         var start = node.getFullStart();
110436         var end = node.getStart();
110437         for (var i = start; i < end; i++) {
110438             if (text.charCodeAt(i) === 10 /* lineFeed */)
110439                 return true;
110440         }
110441         return false;
110442     }
110443     function addEmitFlagsRecursively(node, flag, getChild) {
110444         ts.addEmitFlags(node, flag);
110445         var child = getChild(node);
110446         if (child)
110447             addEmitFlagsRecursively(child, flag, getChild);
110448     }
110449     function getFirstChild(node) {
110450         return node.forEachChild(function (child) { return child; });
110451     }
110452     function getUniqueName(baseName, sourceFile) {
110453         var nameText = baseName;
110454         for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) {
110455             nameText = baseName + "_" + i;
110456         }
110457         return nameText;
110458     }
110459     ts.getUniqueName = getUniqueName;
110460     /**
110461      * @return The index of the (only) reference to the extracted symbol.  We want the cursor
110462      * to be on the reference, rather than the declaration, because it's closer to where the
110463      * user was before extracting it.
110464      */
110465     function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
110466         var delta = 0;
110467         var lastPos = -1;
110468         for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
110469             var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
110470             ts.Debug.assert(fileName === renameFilename);
110471             for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
110472                 var change = textChanges_1[_b];
110473                 var span = change.span, newText = change.newText;
110474                 var index = indexInTextChange(newText, name);
110475                 if (index !== -1) {
110476                     lastPos = span.start + delta + index;
110477                     // If the reference comes first, return immediately.
110478                     if (!preferLastLocation) {
110479                         return lastPos;
110480                     }
110481                 }
110482                 delta += newText.length - span.length;
110483             }
110484         }
110485         // If the declaration comes first, return the position of the last occurrence.
110486         ts.Debug.assert(preferLastLocation);
110487         ts.Debug.assert(lastPos >= 0);
110488         return lastPos;
110489     }
110490     ts.getRenameLocation = getRenameLocation;
110491     function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
110492         ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
110493     }
110494     ts.copyLeadingComments = copyLeadingComments;
110495     function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
110496         ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
110497     }
110498     ts.copyTrailingComments = copyTrailingComments;
110499     /**
110500      * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
110501      * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
110502      * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
110503      * `function foo(\* not leading comment for a *\ a: string) {}`
110504      * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
110505      */
110506     function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
110507         ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
110508     }
110509     ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
110510     function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
110511         return function (pos, end, kind, htnl) {
110512             if (kind === 3 /* MultiLineCommentTrivia */) {
110513                 // Remove leading /*
110514                 pos += 2;
110515                 // Remove trailing */
110516                 end -= 2;
110517             }
110518             else {
110519                 // Remove leading //
110520                 pos += 2;
110521             }
110522             cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
110523         };
110524     }
110525     function indexInTextChange(change, name) {
110526         if (ts.startsWith(change, name))
110527             return 0;
110528         // Add a " " to avoid references inside words
110529         var idx = change.indexOf(" " + name);
110530         if (idx === -1)
110531             idx = change.indexOf("." + name);
110532         if (idx === -1)
110533             idx = change.indexOf('"' + name);
110534         return idx === -1 ? -1 : idx + 1;
110535     }
110536     /* @internal */
110537     function needsParentheses(expression) {
110538         return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression);
110539     }
110540     ts.needsParentheses = needsParentheses;
110541     function getContextualTypeFromParent(node, checker) {
110542         var parent = node.parent;
110543         switch (parent.kind) {
110544             case 197 /* NewExpression */:
110545                 return checker.getContextualType(parent);
110546             case 209 /* BinaryExpression */: {
110547                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
110548                 return isEqualityOperatorKind(operatorToken.kind)
110549                     ? checker.getTypeAtLocation(node === right ? left : right)
110550                     : checker.getContextualType(node);
110551             }
110552             case 277 /* CaseClause */:
110553                 return parent.expression === node ? getSwitchedType(parent, checker) : undefined;
110554             default:
110555                 return checker.getContextualType(node);
110556         }
110557     }
110558     ts.getContextualTypeFromParent = getContextualTypeFromParent;
110559     function quote(text, preferences) {
110560         // Editors can pass in undefined or empty string - we want to infer the preference in those cases.
110561         var quotePreference = preferences.quotePreference || "auto";
110562         var quoted = JSON.stringify(text);
110563         switch (quotePreference) {
110564             // TODO use getQuotePreference to infer the actual quote style.
110565             case "auto":
110566             case "double":
110567                 return quoted;
110568             case "single":
110569                 return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'";
110570             default:
110571                 return ts.Debug.assertNever(quotePreference);
110572         }
110573     }
110574     ts.quote = quote;
110575     function isEqualityOperatorKind(kind) {
110576         switch (kind) {
110577             case 36 /* EqualsEqualsEqualsToken */:
110578             case 34 /* EqualsEqualsToken */:
110579             case 37 /* ExclamationEqualsEqualsToken */:
110580             case 35 /* ExclamationEqualsToken */:
110581                 return true;
110582             default:
110583                 return false;
110584         }
110585     }
110586     ts.isEqualityOperatorKind = isEqualityOperatorKind;
110587     function isStringLiteralOrTemplate(node) {
110588         switch (node.kind) {
110589             case 10 /* StringLiteral */:
110590             case 14 /* NoSubstitutionTemplateLiteral */:
110591             case 211 /* TemplateExpression */:
110592             case 198 /* TaggedTemplateExpression */:
110593                 return true;
110594             default:
110595                 return false;
110596         }
110597     }
110598     ts.isStringLiteralOrTemplate = isStringLiteralOrTemplate;
110599     function hasIndexSignature(type) {
110600         return !!type.getStringIndexType() || !!type.getNumberIndexType();
110601     }
110602     ts.hasIndexSignature = hasIndexSignature;
110603     function getSwitchedType(caseClause, checker) {
110604         return checker.getTypeAtLocation(caseClause.parent.parent.expression);
110605     }
110606     ts.getSwitchedType = getSwitchedType;
110607     ts.ANONYMOUS = "anonymous function";
110608     function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
110609         var checker = program.getTypeChecker();
110610         var typeIsAccessible = true;
110611         var notAccessible = function () { typeIsAccessible = false; };
110612         var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
110613             trackSymbol: function (symbol, declaration, meaning) {
110614                 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
110615             },
110616             reportInaccessibleThisError: notAccessible,
110617             reportPrivateInBaseOfClassExpression: notAccessible,
110618             reportInaccessibleUniqueSymbolError: notAccessible,
110619             moduleResolverHost: getModuleSpecifierResolverHost(program, host)
110620         });
110621         return typeIsAccessible ? res : undefined;
110622     }
110623     ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
110624     function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) {
110625         return kind === 165 /* CallSignature */
110626             || kind === 166 /* ConstructSignature */
110627             || kind === 167 /* IndexSignature */
110628             || kind === 158 /* PropertySignature */
110629             || kind === 160 /* MethodSignature */;
110630     }
110631     ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI;
110632     function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) {
110633         return kind === 244 /* FunctionDeclaration */
110634             || kind === 162 /* Constructor */
110635             || kind === 161 /* MethodDeclaration */
110636             || kind === 163 /* GetAccessor */
110637             || kind === 164 /* SetAccessor */;
110638     }
110639     ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI;
110640     function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) {
110641         return kind === 249 /* ModuleDeclaration */;
110642     }
110643     ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI;
110644     function syntaxRequiresTrailingSemicolonOrASI(kind) {
110645         return kind === 225 /* VariableStatement */
110646             || kind === 226 /* ExpressionStatement */
110647             || kind === 228 /* DoStatement */
110648             || kind === 233 /* ContinueStatement */
110649             || kind === 234 /* BreakStatement */
110650             || kind === 235 /* ReturnStatement */
110651             || kind === 239 /* ThrowStatement */
110652             || kind === 241 /* DebuggerStatement */
110653             || kind === 159 /* PropertyDeclaration */
110654             || kind === 247 /* TypeAliasDeclaration */
110655             || kind === 254 /* ImportDeclaration */
110656             || kind === 253 /* ImportEqualsDeclaration */
110657             || kind === 260 /* ExportDeclaration */
110658             || kind === 252 /* NamespaceExportDeclaration */
110659             || kind === 259 /* ExportAssignment */;
110660     }
110661     ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI;
110662     ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI);
110663     function nodeIsASICandidate(node, sourceFile) {
110664         var lastToken = node.getLastToken(sourceFile);
110665         if (lastToken && lastToken.kind === 26 /* SemicolonToken */) {
110666             return false;
110667         }
110668         if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) {
110669             if (lastToken && lastToken.kind === 27 /* CommaToken */) {
110670                 return false;
110671             }
110672         }
110673         else if (syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(node.kind)) {
110674             var lastChild = ts.last(node.getChildren(sourceFile));
110675             if (lastChild && ts.isModuleBlock(lastChild)) {
110676                 return false;
110677             }
110678         }
110679         else if (syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(node.kind)) {
110680             var lastChild = ts.last(node.getChildren(sourceFile));
110681             if (lastChild && ts.isFunctionBlock(lastChild)) {
110682                 return false;
110683             }
110684         }
110685         else if (!syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
110686             return false;
110687         }
110688         // See comment in parser’s `parseDoStatement`
110689         if (node.kind === 228 /* DoStatement */) {
110690             return true;
110691         }
110692         var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; });
110693         var nextToken = findNextToken(node, topNode, sourceFile);
110694         if (!nextToken || nextToken.kind === 19 /* CloseBraceToken */) {
110695             return true;
110696         }
110697         var startLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
110698         var endLine = sourceFile.getLineAndCharacterOfPosition(nextToken.getStart(sourceFile)).line;
110699         return startLine !== endLine;
110700     }
110701     function positionIsASICandidate(pos, context, sourceFile) {
110702         var contextAncestor = ts.findAncestor(context, function (ancestor) {
110703             if (ancestor.end !== pos) {
110704                 return "quit";
110705             }
110706             return ts.syntaxMayBeASICandidate(ancestor.kind);
110707         });
110708         return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile);
110709     }
110710     ts.positionIsASICandidate = positionIsASICandidate;
110711     function probablyUsesSemicolons(sourceFile) {
110712         var withSemicolon = 0;
110713         var withoutSemicolon = 0;
110714         var nStatementsToObserve = 5;
110715         ts.forEachChild(sourceFile, function visit(node) {
110716             if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) {
110717                 var lastToken = node.getLastToken(sourceFile);
110718                 if (lastToken && lastToken.kind === 26 /* SemicolonToken */) {
110719                     withSemicolon++;
110720                 }
110721                 else {
110722                     withoutSemicolon++;
110723                 }
110724             }
110725             if (withSemicolon + withoutSemicolon >= nStatementsToObserve) {
110726                 return true;
110727             }
110728             return ts.forEachChild(node, visit);
110729         });
110730         // One statement missing a semicolon isn’t sufficient evidence to say the user
110731         // doesn’t want semicolons, because they may not even be done writing that statement.
110732         if (withSemicolon === 0 && withoutSemicolon <= 1) {
110733             return true;
110734         }
110735         // If even 2/5 places have a semicolon, the user probably wants semicolons
110736         return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve;
110737     }
110738     ts.probablyUsesSemicolons = probablyUsesSemicolons;
110739     function tryGetDirectories(host, directoryName) {
110740         return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || [];
110741     }
110742     ts.tryGetDirectories = tryGetDirectories;
110743     function tryReadDirectory(host, path, extensions, exclude, include) {
110744         return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray;
110745     }
110746     ts.tryReadDirectory = tryReadDirectory;
110747     function tryFileExists(host, path) {
110748         return tryIOAndConsumeErrors(host, host.fileExists, path);
110749     }
110750     ts.tryFileExists = tryFileExists;
110751     function tryDirectoryExists(host, path) {
110752         return tryAndIgnoreErrors(function () { return ts.directoryProbablyExists(path, host); }) || false;
110753     }
110754     ts.tryDirectoryExists = tryDirectoryExists;
110755     function tryAndIgnoreErrors(cb) {
110756         try {
110757             return cb();
110758         }
110759         catch (_a) {
110760             return undefined;
110761         }
110762     }
110763     ts.tryAndIgnoreErrors = tryAndIgnoreErrors;
110764     function tryIOAndConsumeErrors(host, toApply) {
110765         var args = [];
110766         for (var _i = 2; _i < arguments.length; _i++) {
110767             args[_i - 2] = arguments[_i];
110768         }
110769         return tryAndIgnoreErrors(function () { return toApply && toApply.apply(host, args); });
110770     }
110771     ts.tryIOAndConsumeErrors = tryIOAndConsumeErrors;
110772     function findPackageJsons(startDirectory, host, stopDirectory) {
110773         var paths = [];
110774         ts.forEachAncestorDirectory(startDirectory, function (ancestor) {
110775             if (ancestor === stopDirectory) {
110776                 return true;
110777             }
110778             var currentConfigPath = ts.combinePaths(ancestor, "package.json");
110779             if (tryFileExists(host, currentConfigPath)) {
110780                 paths.push(currentConfigPath);
110781             }
110782         });
110783         return paths;
110784     }
110785     ts.findPackageJsons = findPackageJsons;
110786     function findPackageJson(directory, host) {
110787         var packageJson;
110788         ts.forEachAncestorDirectory(directory, function (ancestor) {
110789             if (ancestor === "node_modules")
110790                 return true;
110791             packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json");
110792             if (packageJson) {
110793                 return true; // break out
110794             }
110795         });
110796         return packageJson;
110797     }
110798     ts.findPackageJson = findPackageJson;
110799     function getPackageJsonsVisibleToFile(fileName, host) {
110800         if (!host.fileExists) {
110801             return [];
110802         }
110803         var packageJsons = [];
110804         ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (ancestor) {
110805             var packageJsonFileName = ts.combinePaths(ancestor, "package.json");
110806             if (host.fileExists(packageJsonFileName)) {
110807                 var info = createPackageJsonInfo(packageJsonFileName, host);
110808                 if (info) {
110809                     packageJsons.push(info);
110810                 }
110811             }
110812         });
110813         return packageJsons;
110814     }
110815     ts.getPackageJsonsVisibleToFile = getPackageJsonsVisibleToFile;
110816     function createPackageJsonInfo(fileName, host) {
110817         if (!host.readFile) {
110818             return undefined;
110819         }
110820         var dependencyKeys = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
110821         var stringContent = host.readFile(fileName);
110822         if (!stringContent)
110823             return undefined;
110824         var content = tryParseJson(stringContent);
110825         if (!content)
110826             return false;
110827         var info = {};
110828         for (var _i = 0, dependencyKeys_1 = dependencyKeys; _i < dependencyKeys_1.length; _i++) {
110829             var key = dependencyKeys_1[_i];
110830             var dependencies = content[key];
110831             if (!dependencies) {
110832                 continue;
110833             }
110834             var dependencyMap = ts.createMap();
110835             for (var packageName in dependencies) {
110836                 dependencyMap.set(packageName, dependencies[packageName]);
110837             }
110838             info[key] = dependencyMap;
110839         }
110840         var dependencyGroups = [
110841             [1 /* Dependencies */, info.dependencies],
110842             [2 /* DevDependencies */, info.devDependencies],
110843             [8 /* OptionalDependencies */, info.optionalDependencies],
110844             [4 /* PeerDependencies */, info.peerDependencies],
110845         ];
110846         return __assign(__assign({}, info), { fileName: fileName,
110847             get: get,
110848             has: function (dependencyName, inGroups) {
110849                 return !!get(dependencyName, inGroups);
110850             } });
110851         function get(dependencyName, inGroups) {
110852             if (inGroups === void 0) { inGroups = 15 /* All */; }
110853             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
110854                 var _a = dependencyGroups_1[_i], group_1 = _a[0], deps = _a[1];
110855                 if (deps && (inGroups & group_1)) {
110856                     var dep = deps.get(dependencyName);
110857                     if (dep !== undefined) {
110858                         return dep;
110859                     }
110860                 }
110861             }
110862         }
110863     }
110864     ts.createPackageJsonInfo = createPackageJsonInfo;
110865     function tryParseJson(text) {
110866         try {
110867             return JSON.parse(text);
110868         }
110869         catch (_a) {
110870             return undefined;
110871         }
110872     }
110873     function consumesNodeCoreModules(sourceFile) {
110874         return ts.some(sourceFile.imports, function (_a) {
110875             var text = _a.text;
110876             return ts.JsTyping.nodeCoreModules.has(text);
110877         });
110878     }
110879     ts.consumesNodeCoreModules = consumesNodeCoreModules;
110880     function isInsideNodeModules(fileOrDirectory) {
110881         return ts.contains(ts.getPathComponents(fileOrDirectory), "node_modules");
110882     }
110883     ts.isInsideNodeModules = isInsideNodeModules;
110884     function isDiagnosticWithLocation(diagnostic) {
110885         return diagnostic.file !== undefined && diagnostic.start !== undefined && diagnostic.length !== undefined;
110886     }
110887     ts.isDiagnosticWithLocation = isDiagnosticWithLocation;
110888     function findDiagnosticForNode(node, sortedFileDiagnostics) {
110889         var span = createTextSpanFromNode(node);
110890         var index = ts.binarySearchKey(sortedFileDiagnostics, span, ts.identity, ts.compareTextSpans);
110891         if (index >= 0) {
110892             var diagnostic = sortedFileDiagnostics[index];
110893             ts.Debug.assertEqual(diagnostic.file, node.getSourceFile(), "Diagnostics proided to 'findDiagnosticForNode' must be from a single SourceFile");
110894             return ts.cast(diagnostic, isDiagnosticWithLocation);
110895         }
110896     }
110897     ts.findDiagnosticForNode = findDiagnosticForNode;
110898     function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) {
110899         var _a;
110900         var index = ts.binarySearchKey(sortedFileDiagnostics, span.start, function (diag) { return diag.start; }, ts.compareValues);
110901         if (index < 0) {
110902             index = ~index;
110903         }
110904         while (((_a = sortedFileDiagnostics[index - 1]) === null || _a === void 0 ? void 0 : _a.start) === span.start) {
110905             index--;
110906         }
110907         var result = [];
110908         var end = ts.textSpanEnd(span);
110909         while (true) {
110910             var diagnostic = ts.tryCast(sortedFileDiagnostics[index], isDiagnosticWithLocation);
110911             if (!diagnostic || diagnostic.start > end) {
110912                 break;
110913             }
110914             if (ts.textSpanContainsTextSpan(span, diagnostic)) {
110915                 result.push(diagnostic);
110916             }
110917             index++;
110918         }
110919         return result;
110920     }
110921     ts.getDiagnosticsWithinSpan = getDiagnosticsWithinSpan;
110922     /* @internal */
110923     function getRefactorContextSpan(_a) {
110924         var startPosition = _a.startPosition, endPosition = _a.endPosition;
110925         return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
110926     }
110927     ts.getRefactorContextSpan = getRefactorContextSpan;
110928     function mapOneOrMany(valueOrArray, f, resultSelector) {
110929         if (resultSelector === void 0) { resultSelector = ts.identity; }
110930         return valueOrArray ? ts.isArray(valueOrArray) ? resultSelector(ts.map(valueOrArray, f)) : f(valueOrArray, 0) : undefined;
110931     }
110932     ts.mapOneOrMany = mapOneOrMany;
110933     /**
110934      * If the provided value is an array, the first element of the array is returned; otherwise, the provided value is returned instead.
110935      */
110936     function firstOrOnly(valueOrArray) {
110937         return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray;
110938     }
110939     ts.firstOrOnly = firstOrOnly;
110940     function getNameForExportedSymbol(symbol, scriptTarget) {
110941         if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) {
110942             // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
110943             return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; })
110944                 || ts.codefix.moduleSymbolToValidIdentifier(ts.Debug.checkDefined(symbol.parent), scriptTarget);
110945         }
110946         return symbol.name;
110947     }
110948     ts.getNameForExportedSymbol = getNameForExportedSymbol;
110949     /**
110950      * Useful to check whether a string contains another string at a specific index
110951      * without allocating another string or traversing the entire contents of the outer string.
110952      *
110953      * This function is useful in place of either of the following:
110954      *
110955      * ```ts
110956      * // Allocates
110957      * haystack.substr(startIndex, needle.length) === needle
110958      *
110959      * // Full traversal
110960      * haystack.indexOf(needle, startIndex) === startIndex
110961      * ```
110962      *
110963      * @param haystack The string that potentially contains `needle`.
110964      * @param needle The string whose content might sit within `haystack`.
110965      * @param startIndex The index within `haystack` to start searching for `needle`.
110966      */
110967     function stringContainsAt(haystack, needle, startIndex) {
110968         var needleLength = needle.length;
110969         if (needleLength + startIndex > haystack.length) {
110970             return false;
110971         }
110972         for (var i = 0; i < needleLength; i++) {
110973             if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex))
110974                 return false;
110975         }
110976         return true;
110977     }
110978     ts.stringContainsAt = stringContainsAt;
110979     function startsWithUnderscore(name) {
110980         return name.charCodeAt(0) === 95 /* _ */;
110981     }
110982     ts.startsWithUnderscore = startsWithUnderscore;
110983     function isGlobalDeclaration(declaration) {
110984         return !isNonGlobalDeclaration(declaration);
110985     }
110986     ts.isGlobalDeclaration = isGlobalDeclaration;
110987     function isNonGlobalDeclaration(declaration) {
110988         var sourceFile = declaration.getSourceFile();
110989         // If the file is not a module, the declaration is global
110990         if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) {
110991             return false;
110992         }
110993         // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation
110994         return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation);
110995     }
110996     ts.isNonGlobalDeclaration = isNonGlobalDeclaration;
110997     // #endregion
110998 })(ts || (ts = {}));
110999 var ts;
111000 (function (ts) {
111001     /** The classifier is used for syntactic highlighting in editors via the TSServer */
111002     function createClassifier() {
111003         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false);
111004         function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
111005             return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
111006         }
111007         // If there is a syntactic classifier ('syntacticClassifierAbsent' is false),
111008         // we will be more conservative in order to avoid conflicting with the syntactic classifier.
111009         function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) {
111010             var token = 0 /* Unknown */;
111011             var lastNonTriviaToken = 0 /* Unknown */;
111012             // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact)
111013             // classification on template strings. Because of the context free nature of templates,
111014             // the only precise way to classify a template portion would be by propagating the stack across
111015             // lines, just as we do with the end-of-line state. However, this is a burden for implementers,
111016             // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead
111017             // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state.
111018             // Situations in which this fails are
111019             //  1) When template strings are nested across different lines:
111020             //          `hello ${ `world
111021             //          ` }`
111022             //
111023             //     Where on the second line, you will get the closing of a template,
111024             //     a closing curly, and a new template.
111025             //
111026             //  2) When substitution expressions have curly braces and the curly brace falls on the next line:
111027             //          `hello ${ () => {
111028             //          return "world" } } `
111029             //
111030             //     Where on the second line, you will get the 'return' keyword,
111031             //     a string literal, and a template end consisting of '} } `'.
111032             var templateStack = [];
111033             var _a = getPrefixFromLexState(lexState), prefix = _a.prefix, pushTemplate = _a.pushTemplate;
111034             text = prefix + text;
111035             var offset = prefix.length;
111036             if (pushTemplate) {
111037                 templateStack.push(15 /* TemplateHead */);
111038             }
111039             scanner.setText(text);
111040             var endOfLineState = 0 /* None */;
111041             var spans = [];
111042             // We can run into an unfortunate interaction between the lexical and syntactic classifier
111043             // when the user is typing something generic.  Consider the case where the user types:
111044             //
111045             //      Foo<number
111046             //
111047             // From the lexical classifier's perspective, 'number' is a keyword, and so the word will
111048             // be classified as such.  However, from the syntactic classifier's tree-based perspective
111049             // this is simply an expression with the identifier 'number' on the RHS of the less than
111050             // token.  So the classification will go back to being an identifier.  The moment the user
111051             // types again, number will become a keyword, then an identifier, etc. etc.
111052             //
111053             // To try to avoid this problem, we avoid classifying contextual keywords as keywords
111054             // when the user is potentially typing something generic.  We just can't do a good enough
111055             // job at the lexical level, and so well leave it up to the syntactic classifier to make
111056             // the determination.
111057             //
111058             // In order to determine if the user is potentially typing something generic, we use a
111059             // weak heuristic where we track < and > tokens.  It's a weak heuristic, but should
111060             // work well enough in practice.
111061             var angleBracketStack = 0;
111062             do {
111063                 token = scanner.scan();
111064                 if (!ts.isTrivia(token)) {
111065                     handleToken();
111066                     lastNonTriviaToken = token;
111067                 }
111068                 var end = scanner.getTextPos();
111069                 pushEncodedClassification(scanner.getTokenPos(), end, offset, classFromKind(token), spans);
111070                 if (end >= text.length) {
111071                     var end_1 = getNewEndOfLineState(scanner, token, ts.lastOrUndefined(templateStack));
111072                     if (end_1 !== undefined) {
111073                         endOfLineState = end_1;
111074                     }
111075                 }
111076             } while (token !== 1 /* EndOfFileToken */);
111077             function handleToken() {
111078                 switch (token) {
111079                     case 43 /* SlashToken */:
111080                     case 67 /* SlashEqualsToken */:
111081                         if (!noRegexTable[lastNonTriviaToken] && scanner.reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
111082                             token = 13 /* RegularExpressionLiteral */;
111083                         }
111084                         break;
111085                     case 29 /* LessThanToken */:
111086                         if (lastNonTriviaToken === 75 /* Identifier */) {
111087                             // Could be the start of something generic.  Keep track of that by bumping
111088                             // up the current count of generic contexts we may be in.
111089                             angleBracketStack++;
111090                         }
111091                         break;
111092                     case 31 /* GreaterThanToken */:
111093                         if (angleBracketStack > 0) {
111094                             // If we think we're currently in something generic, then mark that that
111095                             // generic entity is complete.
111096                             angleBracketStack--;
111097                         }
111098                         break;
111099                     case 125 /* AnyKeyword */:
111100                     case 143 /* StringKeyword */:
111101                     case 140 /* NumberKeyword */:
111102                     case 128 /* BooleanKeyword */:
111103                     case 144 /* SymbolKeyword */:
111104                         if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
111105                             // If it looks like we're could be in something generic, don't classify this
111106                             // as a keyword.  We may just get overwritten by the syntactic classifier,
111107                             // causing a noisy experience for the user.
111108                             token = 75 /* Identifier */;
111109                         }
111110                         break;
111111                     case 15 /* TemplateHead */:
111112                         templateStack.push(token);
111113                         break;
111114                     case 18 /* OpenBraceToken */:
111115                         // If we don't have anything on the template stack,
111116                         // then we aren't trying to keep track of a previously scanned template head.
111117                         if (templateStack.length > 0) {
111118                             templateStack.push(token);
111119                         }
111120                         break;
111121                     case 19 /* CloseBraceToken */:
111122                         // If we don't have anything on the template stack,
111123                         // then we aren't trying to keep track of a previously scanned template head.
111124                         if (templateStack.length > 0) {
111125                             var lastTemplateStackToken = ts.lastOrUndefined(templateStack);
111126                             if (lastTemplateStackToken === 15 /* TemplateHead */) {
111127                                 token = scanner.reScanTemplateToken(/* isTaggedTemplate */ false);
111128                                 // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us.
111129                                 if (token === 17 /* TemplateTail */) {
111130                                     templateStack.pop();
111131                                 }
111132                                 else {
111133                                     ts.Debug.assertEqual(token, 16 /* TemplateMiddle */, "Should have been a template middle.");
111134                                 }
111135                             }
111136                             else {
111137                                 ts.Debug.assertEqual(lastTemplateStackToken, 18 /* OpenBraceToken */, "Should have been an open brace");
111138                                 templateStack.pop();
111139                             }
111140                         }
111141                         break;
111142                     default:
111143                         if (!ts.isKeyword(token)) {
111144                             break;
111145                         }
111146                         if (lastNonTriviaToken === 24 /* DotToken */) {
111147                             token = 75 /* Identifier */;
111148                         }
111149                         else if (ts.isKeyword(lastNonTriviaToken) && ts.isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
111150                             // We have two keywords in a row.  Only treat the second as a keyword if
111151                             // it's a sequence that could legally occur in the language.  Otherwise
111152                             // treat it as an identifier.  This way, if someone writes "private var"
111153                             // we recognize that 'var' is actually an identifier here.
111154                             token = 75 /* Identifier */;
111155                         }
111156                 }
111157             }
111158             return { endOfLineState: endOfLineState, spans: spans };
111159         }
111160         return { getClassificationsForLine: getClassificationsForLine, getEncodedLexicalClassifications: getEncodedLexicalClassifications };
111161     }
111162     ts.createClassifier = createClassifier;
111163     /// We do not have a full parser support to know when we should parse a regex or not
111164     /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
111165     /// we have a series of divide operator. this list allows us to be more accurate by ruling out
111166     /// locations where a regexp cannot exist.
111167     var noRegexTable = ts.arrayToNumericMap([
111168         75 /* Identifier */,
111169         10 /* StringLiteral */,
111170         8 /* NumericLiteral */,
111171         9 /* BigIntLiteral */,
111172         13 /* RegularExpressionLiteral */,
111173         104 /* ThisKeyword */,
111174         45 /* PlusPlusToken */,
111175         46 /* MinusMinusToken */,
111176         21 /* CloseParenToken */,
111177         23 /* CloseBracketToken */,
111178         19 /* CloseBraceToken */,
111179         106 /* TrueKeyword */,
111180         91 /* FalseKeyword */,
111181     ], function (token) { return token; }, function () { return true; });
111182     function getNewEndOfLineState(scanner, token, lastOnTemplateStack) {
111183         switch (token) {
111184             case 10 /* StringLiteral */: {
111185                 // Check to see if we finished up on a multiline string literal.
111186                 if (!scanner.isUnterminated())
111187                     return undefined;
111188                 var tokenText = scanner.getTokenText();
111189                 var lastCharIndex = tokenText.length - 1;
111190                 var numBackslashes = 0;
111191                 while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) {
111192                     numBackslashes++;
111193                 }
111194                 // If we have an odd number of backslashes, then the multiline string is unclosed
111195                 if ((numBackslashes & 1) === 0)
111196                     return undefined;
111197                 return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */;
111198             }
111199             case 3 /* MultiLineCommentTrivia */:
111200                 // Check to see if the multiline comment was unclosed.
111201                 return scanner.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : undefined;
111202             default:
111203                 if (ts.isTemplateLiteralKind(token)) {
111204                     if (!scanner.isUnterminated()) {
111205                         return undefined;
111206                     }
111207                     switch (token) {
111208                         case 17 /* TemplateTail */:
111209                             return 5 /* InTemplateMiddleOrTail */;
111210                         case 14 /* NoSubstitutionTemplateLiteral */:
111211                             return 4 /* InTemplateHeadOrNoSubstitutionTemplate */;
111212                         default:
111213                             return ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
111214                     }
111215                 }
111216                 return lastOnTemplateStack === 15 /* TemplateHead */ ? 6 /* InTemplateSubstitutionPosition */ : undefined;
111217         }
111218     }
111219     function pushEncodedClassification(start, end, offset, classification, result) {
111220         if (classification === 8 /* whiteSpace */) {
111221             // Don't bother with whitespace classifications.  They're not needed.
111222             return;
111223         }
111224         if (start === 0 && offset > 0) {
111225             // We're classifying the first token, and this was a case where we prepended text.
111226             // We should consider the start of this token to be at the start of the original text.
111227             start += offset;
111228         }
111229         var length = end - start;
111230         if (length > 0) {
111231             // All our tokens are in relation to the augmented text.  Move them back to be
111232             // relative to the original text.
111233             result.push(start - offset, length, classification);
111234         }
111235     }
111236     function convertClassificationsToResult(classifications, text) {
111237         var entries = [];
111238         var dense = classifications.spans;
111239         var lastEnd = 0;
111240         for (var i = 0; i < dense.length; i += 3) {
111241             var start = dense[i];
111242             var length_1 = dense[i + 1];
111243             var type = dense[i + 2];
111244             // Make a whitespace entry between the last item and this one.
111245             if (lastEnd >= 0) {
111246                 var whitespaceLength_1 = start - lastEnd;
111247                 if (whitespaceLength_1 > 0) {
111248                     entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
111249                 }
111250             }
111251             entries.push({ length: length_1, classification: convertClassification(type) });
111252             lastEnd = start + length_1;
111253         }
111254         var whitespaceLength = text.length - lastEnd;
111255         if (whitespaceLength > 0) {
111256             entries.push({ length: whitespaceLength, classification: ts.TokenClass.Whitespace });
111257         }
111258         return { entries: entries, finalLexState: classifications.endOfLineState };
111259     }
111260     function convertClassification(type) {
111261         switch (type) {
111262             case 1 /* comment */: return ts.TokenClass.Comment;
111263             case 3 /* keyword */: return ts.TokenClass.Keyword;
111264             case 4 /* numericLiteral */: return ts.TokenClass.NumberLiteral;
111265             case 25 /* bigintLiteral */: return ts.TokenClass.BigIntLiteral;
111266             case 5 /* operator */: return ts.TokenClass.Operator;
111267             case 6 /* stringLiteral */: return ts.TokenClass.StringLiteral;
111268             case 8 /* whiteSpace */: return ts.TokenClass.Whitespace;
111269             case 10 /* punctuation */: return ts.TokenClass.Punctuation;
111270             case 2 /* identifier */:
111271             case 11 /* className */:
111272             case 12 /* enumName */:
111273             case 13 /* interfaceName */:
111274             case 14 /* moduleName */:
111275             case 15 /* typeParameterName */:
111276             case 16 /* typeAliasName */:
111277             case 9 /* text */:
111278             case 17 /* parameterName */:
111279                 return ts.TokenClass.Identifier;
111280             default:
111281                 return undefined; // TODO: GH#18217 Debug.assertNever(type);
111282         }
111283     }
111284     /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
111285     function canFollow(keyword1, keyword2) {
111286         if (!ts.isAccessibilityModifier(keyword1)) {
111287             // Assume any other keyword combination is legal.
111288             // This can be refined in the future if there are more cases we want the classifier to be better at.
111289             return true;
111290         }
111291         switch (keyword2) {
111292             case 131 /* GetKeyword */:
111293             case 142 /* SetKeyword */:
111294             case 129 /* ConstructorKeyword */:
111295             case 120 /* StaticKeyword */:
111296                 return true; // Allow things like "public get", "public constructor" and "public static".
111297             default:
111298                 return false; // Any other keyword following "public" is actually an identifier, not a real keyword.
111299         }
111300     }
111301     function getPrefixFromLexState(lexState) {
111302         // If we're in a string literal, then prepend: "\
111303         // (and a newline).  That way when we lex we'll think we're still in a string literal.
111304         //
111305         // If we're in a multiline comment, then prepend: /*
111306         // (and a newline).  That way when we lex we'll think we're still in a multiline comment.
111307         switch (lexState) {
111308             case 3 /* InDoubleQuoteStringLiteral */:
111309                 return { prefix: "\"\\\n" };
111310             case 2 /* InSingleQuoteStringLiteral */:
111311                 return { prefix: "'\\\n" };
111312             case 1 /* InMultiLineCommentTrivia */:
111313                 return { prefix: "/*\n" };
111314             case 4 /* InTemplateHeadOrNoSubstitutionTemplate */:
111315                 return { prefix: "`\n" };
111316             case 5 /* InTemplateMiddleOrTail */:
111317                 return { prefix: "}\n", pushTemplate: true };
111318             case 6 /* InTemplateSubstitutionPosition */:
111319                 return { prefix: "", pushTemplate: true };
111320             case 0 /* None */:
111321                 return { prefix: "" };
111322             default:
111323                 return ts.Debug.assertNever(lexState);
111324         }
111325     }
111326     function isBinaryExpressionOperatorToken(token) {
111327         switch (token) {
111328             case 41 /* AsteriskToken */:
111329             case 43 /* SlashToken */:
111330             case 44 /* PercentToken */:
111331             case 39 /* PlusToken */:
111332             case 40 /* MinusToken */:
111333             case 47 /* LessThanLessThanToken */:
111334             case 48 /* GreaterThanGreaterThanToken */:
111335             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
111336             case 29 /* LessThanToken */:
111337             case 31 /* GreaterThanToken */:
111338             case 32 /* LessThanEqualsToken */:
111339             case 33 /* GreaterThanEqualsToken */:
111340             case 98 /* InstanceOfKeyword */:
111341             case 97 /* InKeyword */:
111342             case 123 /* AsKeyword */:
111343             case 34 /* EqualsEqualsToken */:
111344             case 35 /* ExclamationEqualsToken */:
111345             case 36 /* EqualsEqualsEqualsToken */:
111346             case 37 /* ExclamationEqualsEqualsToken */:
111347             case 50 /* AmpersandToken */:
111348             case 52 /* CaretToken */:
111349             case 51 /* BarToken */:
111350             case 55 /* AmpersandAmpersandToken */:
111351             case 56 /* BarBarToken */:
111352             case 73 /* BarEqualsToken */:
111353             case 72 /* AmpersandEqualsToken */:
111354             case 74 /* CaretEqualsToken */:
111355             case 69 /* LessThanLessThanEqualsToken */:
111356             case 70 /* GreaterThanGreaterThanEqualsToken */:
111357             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
111358             case 63 /* PlusEqualsToken */:
111359             case 64 /* MinusEqualsToken */:
111360             case 65 /* AsteriskEqualsToken */:
111361             case 67 /* SlashEqualsToken */:
111362             case 68 /* PercentEqualsToken */:
111363             case 62 /* EqualsToken */:
111364             case 27 /* CommaToken */:
111365             case 60 /* QuestionQuestionToken */:
111366                 return true;
111367             default:
111368                 return false;
111369         }
111370     }
111371     function isPrefixUnaryExpressionOperatorToken(token) {
111372         switch (token) {
111373             case 39 /* PlusToken */:
111374             case 40 /* MinusToken */:
111375             case 54 /* TildeToken */:
111376             case 53 /* ExclamationToken */:
111377             case 45 /* PlusPlusToken */:
111378             case 46 /* MinusMinusToken */:
111379                 return true;
111380             default:
111381                 return false;
111382         }
111383     }
111384     function classFromKind(token) {
111385         if (ts.isKeyword(token)) {
111386             return 3 /* keyword */;
111387         }
111388         else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
111389             return 5 /* operator */;
111390         }
111391         else if (token >= 18 /* FirstPunctuation */ && token <= 74 /* LastPunctuation */) {
111392             return 10 /* punctuation */;
111393         }
111394         switch (token) {
111395             case 8 /* NumericLiteral */:
111396                 return 4 /* numericLiteral */;
111397             case 9 /* BigIntLiteral */:
111398                 return 25 /* bigintLiteral */;
111399             case 10 /* StringLiteral */:
111400                 return 6 /* stringLiteral */;
111401             case 13 /* RegularExpressionLiteral */:
111402                 return 7 /* regularExpressionLiteral */;
111403             case 7 /* ConflictMarkerTrivia */:
111404             case 3 /* MultiLineCommentTrivia */:
111405             case 2 /* SingleLineCommentTrivia */:
111406                 return 1 /* comment */;
111407             case 5 /* WhitespaceTrivia */:
111408             case 4 /* NewLineTrivia */:
111409                 return 8 /* whiteSpace */;
111410             case 75 /* Identifier */:
111411             default:
111412                 if (ts.isTemplateLiteralKind(token)) {
111413                     return 6 /* stringLiteral */;
111414                 }
111415                 return 2 /* identifier */;
111416         }
111417     }
111418     /* @internal */
111419     function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
111420         return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span));
111421     }
111422     ts.getSemanticClassifications = getSemanticClassifications;
111423     function checkForClassificationCancellation(cancellationToken, kind) {
111424         // We don't want to actually call back into our host on every node to find out if we've
111425         // been canceled.  That would be an enormous amount of chattyness, along with the all
111426         // the overhead of marshalling the data to/from the host.  So instead we pick a few
111427         // reasonable node kinds to bother checking on.  These node kinds represent high level
111428         // constructs that we would expect to see commonly, but just at a far less frequent
111429         // interval.
111430         //
111431         // For example, in checker.ts (around 750k) we only have around 600 of these constructs.
111432         // That means we're calling back into the host around every 1.2k of the file we process.
111433         // Lib.d.ts has similar numbers.
111434         switch (kind) {
111435             case 249 /* ModuleDeclaration */:
111436             case 245 /* ClassDeclaration */:
111437             case 246 /* InterfaceDeclaration */:
111438             case 244 /* FunctionDeclaration */:
111439                 cancellationToken.throwIfCancellationRequested();
111440         }
111441     }
111442     /* @internal */
111443     function getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) {
111444         var spans = [];
111445         sourceFile.forEachChild(function cb(node) {
111446             // Only walk into nodes that intersect the requested span.
111447             if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth())) {
111448                 return;
111449             }
111450             checkForClassificationCancellation(cancellationToken, node.kind);
111451             // Only bother calling into the typechecker if this is an identifier that
111452             // could possibly resolve to a type name.  This makes classification run
111453             // in a third of the time it would normally take.
111454             if (ts.isIdentifier(node) && !ts.nodeIsMissing(node) && classifiableNames.has(node.escapedText)) {
111455                 var symbol = typeChecker.getSymbolAtLocation(node);
111456                 var type = symbol && classifySymbol(symbol, ts.getMeaningFromLocation(node), typeChecker);
111457                 if (type) {
111458                     pushClassification(node.getStart(sourceFile), node.getEnd(), type);
111459                 }
111460             }
111461             node.forEachChild(cb);
111462         });
111463         return { spans: spans, endOfLineState: 0 /* None */ };
111464         function pushClassification(start, end, type) {
111465             var length = end - start;
111466             ts.Debug.assert(length > 0, "Classification had non-positive length of " + length);
111467             spans.push(start);
111468             spans.push(length);
111469             spans.push(type);
111470         }
111471     }
111472     ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications;
111473     function classifySymbol(symbol, meaningAtPosition, checker) {
111474         var flags = symbol.getFlags();
111475         if ((flags & 2885600 /* Classifiable */) === 0 /* None */) {
111476             return undefined;
111477         }
111478         else if (flags & 32 /* Class */) {
111479             return 11 /* className */;
111480         }
111481         else if (flags & 384 /* Enum */) {
111482             return 12 /* enumName */;
111483         }
111484         else if (flags & 524288 /* TypeAlias */) {
111485             return 16 /* typeAliasName */;
111486         }
111487         else if (flags & 1536 /* Module */) {
111488             // Only classify a module as such if
111489             //  - It appears in a namespace context.
111490             //  - There exists a module declaration which actually impacts the value side.
111491             return meaningAtPosition & 4 /* Namespace */ || meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol) ? 14 /* moduleName */ : undefined;
111492         }
111493         else if (flags & 2097152 /* Alias */) {
111494             return classifySymbol(checker.getAliasedSymbol(symbol), meaningAtPosition, checker);
111495         }
111496         else if (meaningAtPosition & 2 /* Type */) {
111497             return flags & 64 /* Interface */ ? 13 /* interfaceName */ : flags & 262144 /* TypeParameter */ ? 15 /* typeParameterName */ : undefined;
111498         }
111499         else {
111500             return undefined;
111501         }
111502     }
111503     /** Returns true if there exists a module that introduces entities on the value side. */
111504     function hasValueSideModule(symbol) {
111505         return ts.some(symbol.declarations, function (declaration) {
111506             return ts.isModuleDeclaration(declaration) && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;
111507         });
111508     }
111509     function getClassificationTypeName(type) {
111510         switch (type) {
111511             case 1 /* comment */: return "comment" /* comment */;
111512             case 2 /* identifier */: return "identifier" /* identifier */;
111513             case 3 /* keyword */: return "keyword" /* keyword */;
111514             case 4 /* numericLiteral */: return "number" /* numericLiteral */;
111515             case 25 /* bigintLiteral */: return "bigint" /* bigintLiteral */;
111516             case 5 /* operator */: return "operator" /* operator */;
111517             case 6 /* stringLiteral */: return "string" /* stringLiteral */;
111518             case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */;
111519             case 9 /* text */: return "text" /* text */;
111520             case 10 /* punctuation */: return "punctuation" /* punctuation */;
111521             case 11 /* className */: return "class name" /* className */;
111522             case 12 /* enumName */: return "enum name" /* enumName */;
111523             case 13 /* interfaceName */: return "interface name" /* interfaceName */;
111524             case 14 /* moduleName */: return "module name" /* moduleName */;
111525             case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */;
111526             case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */;
111527             case 17 /* parameterName */: return "parameter name" /* parameterName */;
111528             case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */;
111529             case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */;
111530             case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */;
111531             case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */;
111532             case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */;
111533             case 23 /* jsxText */: return "jsx text" /* jsxText */;
111534             case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */;
111535             default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type);
111536         }
111537     }
111538     function convertClassificationsToSpans(classifications) {
111539         ts.Debug.assert(classifications.spans.length % 3 === 0);
111540         var dense = classifications.spans;
111541         var result = [];
111542         for (var i = 0; i < dense.length; i += 3) {
111543             result.push({
111544                 textSpan: ts.createTextSpan(dense[i], dense[i + 1]),
111545                 classificationType: getClassificationTypeName(dense[i + 2])
111546             });
111547         }
111548         return result;
111549     }
111550     /* @internal */
111551     function getSyntacticClassifications(cancellationToken, sourceFile, span) {
111552         return convertClassificationsToSpans(getEncodedSyntacticClassifications(cancellationToken, sourceFile, span));
111553     }
111554     ts.getSyntacticClassifications = getSyntacticClassifications;
111555     /* @internal */
111556     function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) {
111557         var spanStart = span.start;
111558         var spanLength = span.length;
111559         // Make a scanner we can get trivia from.
111560         var triviaScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
111561         var mergeConflictScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
111562         var result = [];
111563         processElement(sourceFile);
111564         return { spans: result, endOfLineState: 0 /* None */ };
111565         function pushClassification(start, length, type) {
111566             result.push(start);
111567             result.push(length);
111568             result.push(type);
111569         }
111570         function classifyLeadingTriviaAndGetTokenStart(token) {
111571             triviaScanner.setTextPos(token.pos);
111572             while (true) {
111573                 var start = triviaScanner.getTextPos();
111574                 // only bother scanning if we have something that could be trivia.
111575                 if (!ts.couldStartTrivia(sourceFile.text, start)) {
111576                     return start;
111577                 }
111578                 var kind = triviaScanner.scan();
111579                 var end = triviaScanner.getTextPos();
111580                 var width = end - start;
111581                 // The moment we get something that isn't trivia, then stop processing.
111582                 if (!ts.isTrivia(kind)) {
111583                     return start;
111584                 }
111585                 switch (kind) {
111586                     case 4 /* NewLineTrivia */:
111587                     case 5 /* WhitespaceTrivia */:
111588                         // Don't bother with newlines/whitespace.
111589                         continue;
111590                     case 2 /* SingleLineCommentTrivia */:
111591                     case 3 /* MultiLineCommentTrivia */:
111592                         // Only bother with the trivia if it at least intersects the span of interest.
111593                         classifyComment(token, kind, start, width);
111594                         // Classifying a comment might cause us to reuse the trivia scanner
111595                         // (because of jsdoc comments).  So after we classify the comment make
111596                         // sure we set the scanner position back to where it needs to be.
111597                         triviaScanner.setTextPos(end);
111598                         continue;
111599                     case 7 /* ConflictMarkerTrivia */:
111600                         var text = sourceFile.text;
111601                         var ch = text.charCodeAt(start);
111602                         // for the <<<<<<< and >>>>>>> markers, we just add them in as comments
111603                         // in the classification stream.
111604                         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
111605                             pushClassification(start, width, 1 /* comment */);
111606                             continue;
111607                         }
111608                         // for the ||||||| and ======== markers, add a comment for the first line,
111609                         // and then lex all subsequent lines up until the end of the conflict marker.
111610                         ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
111611                         classifyDisabledMergeCode(text, start, end);
111612                         break;
111613                     case 6 /* ShebangTrivia */:
111614                         // TODO: Maybe we should classify these.
111615                         break;
111616                     default:
111617                         ts.Debug.assertNever(kind);
111618                 }
111619             }
111620         }
111621         function classifyComment(token, kind, start, width) {
111622             if (kind === 3 /* MultiLineCommentTrivia */) {
111623                 // See if this is a doc comment.  If so, we'll classify certain portions of it
111624                 // specially.
111625                 var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width);
111626                 if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) {
111627                     // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]`
111628                     docCommentAndDiagnostics.jsDoc.parent = token;
111629                     classifyJSDocComment(docCommentAndDiagnostics.jsDoc);
111630                     return;
111631                 }
111632             }
111633             else if (kind === 2 /* SingleLineCommentTrivia */) {
111634                 if (tryClassifyTripleSlashComment(start, width)) {
111635                     return;
111636                 }
111637             }
111638             // Simple comment.  Just add as is.
111639             pushCommentRange(start, width);
111640         }
111641         function pushCommentRange(start, width) {
111642             pushClassification(start, width, 1 /* comment */);
111643         }
111644         function classifyJSDocComment(docComment) {
111645             var pos = docComment.pos;
111646             if (docComment.tags) {
111647                 for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) {
111648                     var tag = _a[_i];
111649                     // As we walk through each tag, classify the portion of text from the end of
111650                     // the last tag (or the start of the entire doc comment) as 'comment'.
111651                     if (tag.pos !== pos) {
111652                         pushCommentRange(pos, tag.pos - pos);
111653                     }
111654                     pushClassification(tag.pos, 1, 10 /* punctuation */); // "@"
111655                     pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
111656                     pos = tag.tagName.end;
111657                     switch (tag.kind) {
111658                         case 317 /* JSDocParameterTag */:
111659                             processJSDocParameterTag(tag);
111660                             break;
111661                         case 321 /* JSDocTemplateTag */:
111662                             processJSDocTemplateTag(tag);
111663                             pos = tag.end;
111664                             break;
111665                         case 320 /* JSDocTypeTag */:
111666                             processElement(tag.typeExpression);
111667                             pos = tag.end;
111668                             break;
111669                         case 318 /* JSDocReturnTag */:
111670                             processElement(tag.typeExpression);
111671                             pos = tag.end;
111672                             break;
111673                     }
111674                 }
111675             }
111676             if (pos !== docComment.end) {
111677                 pushCommentRange(pos, docComment.end - pos);
111678             }
111679             return;
111680             function processJSDocParameterTag(tag) {
111681                 if (tag.isNameFirst) {
111682                     pushCommentRange(pos, tag.name.pos - pos);
111683                     pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
111684                     pos = tag.name.end;
111685                 }
111686                 if (tag.typeExpression) {
111687                     pushCommentRange(pos, tag.typeExpression.pos - pos);
111688                     processElement(tag.typeExpression);
111689                     pos = tag.typeExpression.end;
111690                 }
111691                 if (!tag.isNameFirst) {
111692                     pushCommentRange(pos, tag.name.pos - pos);
111693                     pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */);
111694                     pos = tag.name.end;
111695                 }
111696             }
111697         }
111698         function tryClassifyTripleSlashComment(start, width) {
111699             var tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im;
111700             var attributeRegex = /(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img;
111701             var text = sourceFile.text.substr(start, width);
111702             var match = tripleSlashXMLCommentRegEx.exec(text);
111703             if (!match) {
111704                 return false;
111705             }
111706             // Limiting classification to exactly the elements and attributes
111707             // defined in `ts.commentPragmas` would be excessive, but we can avoid
111708             // some obvious false positives (e.g. in XML-like doc comments) by
111709             // checking the element name.
111710             // eslint-disable-next-line no-in-operator
111711             if (!match[3] || !(match[3] in ts.commentPragmas)) {
111712                 return false;
111713             }
111714             var pos = start;
111715             pushCommentRange(pos, match[1].length); // ///
111716             pos += match[1].length;
111717             pushClassification(pos, match[2].length, 10 /* punctuation */); // <
111718             pos += match[2].length;
111719             pushClassification(pos, match[3].length, 21 /* jsxSelfClosingTagName */); // element name
111720             pos += match[3].length;
111721             var attrText = match[4];
111722             var attrPos = pos;
111723             while (true) {
111724                 var attrMatch = attributeRegex.exec(attrText);
111725                 if (!attrMatch) {
111726                     break;
111727                 }
111728                 var newAttrPos = pos + attrMatch.index;
111729                 if (newAttrPos > attrPos) {
111730                     pushCommentRange(attrPos, newAttrPos - attrPos);
111731                     attrPos = newAttrPos;
111732                 }
111733                 pushClassification(attrPos, attrMatch[1].length, 22 /* jsxAttribute */); // attribute name
111734                 attrPos += attrMatch[1].length;
111735                 if (attrMatch[2].length) {
111736                     pushCommentRange(attrPos, attrMatch[2].length); // whitespace
111737                     attrPos += attrMatch[2].length;
111738                 }
111739                 pushClassification(attrPos, attrMatch[3].length, 5 /* operator */); // =
111740                 attrPos += attrMatch[3].length;
111741                 if (attrMatch[4].length) {
111742                     pushCommentRange(attrPos, attrMatch[4].length); // whitespace
111743                     attrPos += attrMatch[4].length;
111744                 }
111745                 pushClassification(attrPos, attrMatch[5].length, 24 /* jsxAttributeStringLiteralValue */); // attribute value
111746                 attrPos += attrMatch[5].length;
111747             }
111748             pos += match[4].length;
111749             if (pos > attrPos) {
111750                 pushCommentRange(attrPos, pos - attrPos);
111751             }
111752             if (match[5]) {
111753                 pushClassification(pos, match[5].length, 10 /* punctuation */); // />
111754                 pos += match[5].length;
111755             }
111756             var end = start + width;
111757             if (pos < end) {
111758                 pushCommentRange(pos, end - pos);
111759             }
111760             return true;
111761         }
111762         function processJSDocTemplateTag(tag) {
111763             for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) {
111764                 var child = _a[_i];
111765                 processElement(child);
111766             }
111767         }
111768         function classifyDisabledMergeCode(text, start, end) {
111769             // Classify the line that the ||||||| or ======= marker is on as a comment.
111770             // Then just lex all further tokens and add them to the result.
111771             var i;
111772             for (i = start; i < end; i++) {
111773                 if (ts.isLineBreak(text.charCodeAt(i))) {
111774                     break;
111775                 }
111776             }
111777             pushClassification(start, i - start, 1 /* comment */);
111778             mergeConflictScanner.setTextPos(i);
111779             while (mergeConflictScanner.getTextPos() < end) {
111780                 classifyDisabledCodeToken();
111781             }
111782         }
111783         function classifyDisabledCodeToken() {
111784             var start = mergeConflictScanner.getTextPos();
111785             var tokenKind = mergeConflictScanner.scan();
111786             var end = mergeConflictScanner.getTextPos();
111787             var type = classifyTokenType(tokenKind);
111788             if (type) {
111789                 pushClassification(start, end - start, type);
111790             }
111791         }
111792         /**
111793          * Returns true if node should be treated as classified and no further processing is required.
111794          * False will mean that node is not classified and traverse routine should recurse into node contents.
111795          */
111796         function tryClassifyNode(node) {
111797             if (ts.isJSDoc(node)) {
111798                 return true;
111799             }
111800             if (ts.nodeIsMissing(node)) {
111801                 return true;
111802             }
111803             var classifiedElementName = tryClassifyJsxElementName(node);
111804             if (!ts.isToken(node) && node.kind !== 11 /* JsxText */ && classifiedElementName === undefined) {
111805                 return false;
111806             }
111807             var tokenStart = node.kind === 11 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node);
111808             var tokenWidth = node.end - tokenStart;
111809             ts.Debug.assert(tokenWidth >= 0);
111810             if (tokenWidth > 0) {
111811                 var type = classifiedElementName || classifyTokenType(node.kind, node);
111812                 if (type) {
111813                     pushClassification(tokenStart, tokenWidth, type);
111814                 }
111815             }
111816             return true;
111817         }
111818         function tryClassifyJsxElementName(token) {
111819             switch (token.parent && token.parent.kind) {
111820                 case 268 /* JsxOpeningElement */:
111821                     if (token.parent.tagName === token) {
111822                         return 19 /* jsxOpenTagName */;
111823                     }
111824                     break;
111825                 case 269 /* JsxClosingElement */:
111826                     if (token.parent.tagName === token) {
111827                         return 20 /* jsxCloseTagName */;
111828                     }
111829                     break;
111830                 case 267 /* JsxSelfClosingElement */:
111831                     if (token.parent.tagName === token) {
111832                         return 21 /* jsxSelfClosingTagName */;
111833                     }
111834                     break;
111835                 case 273 /* JsxAttribute */:
111836                     if (token.parent.name === token) {
111837                         return 22 /* jsxAttribute */;
111838                     }
111839                     break;
111840             }
111841             return undefined;
111842         }
111843         // for accurate classification, the actual token should be passed in.  however, for
111844         // cases like 'disabled merge code' classification, we just get the token kind and
111845         // classify based on that instead.
111846         function classifyTokenType(tokenKind, token) {
111847             if (ts.isKeyword(tokenKind)) {
111848                 return 3 /* keyword */;
111849             }
111850             // Special case `<` and `>`: If they appear in a generic context they are punctuation,
111851             // not operators.
111852             if (tokenKind === 29 /* LessThanToken */ || tokenKind === 31 /* GreaterThanToken */) {
111853                 // If the node owning the token has a type argument list or type parameter list, then
111854                 // we can effectively assume that a '<' and '>' belong to those lists.
111855                 if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) {
111856                     return 10 /* punctuation */;
111857                 }
111858             }
111859             if (ts.isPunctuation(tokenKind)) {
111860                 if (token) {
111861                     var parent = token.parent;
111862                     if (tokenKind === 62 /* EqualsToken */) {
111863                         // the '=' in a variable declaration is special cased here.
111864                         if (parent.kind === 242 /* VariableDeclaration */ ||
111865                             parent.kind === 159 /* PropertyDeclaration */ ||
111866                             parent.kind === 156 /* Parameter */ ||
111867                             parent.kind === 273 /* JsxAttribute */) {
111868                             return 5 /* operator */;
111869                         }
111870                     }
111871                     if (parent.kind === 209 /* BinaryExpression */ ||
111872                         parent.kind === 207 /* PrefixUnaryExpression */ ||
111873                         parent.kind === 208 /* PostfixUnaryExpression */ ||
111874                         parent.kind === 210 /* ConditionalExpression */) {
111875                         return 5 /* operator */;
111876                     }
111877                 }
111878                 return 10 /* punctuation */;
111879             }
111880             else if (tokenKind === 8 /* NumericLiteral */) {
111881                 return 4 /* numericLiteral */;
111882             }
111883             else if (tokenKind === 9 /* BigIntLiteral */) {
111884                 return 25 /* bigintLiteral */;
111885             }
111886             else if (tokenKind === 10 /* StringLiteral */) {
111887                 return token && token.parent.kind === 273 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
111888             }
111889             else if (tokenKind === 13 /* RegularExpressionLiteral */) {
111890                 // TODO: we should get another classification type for these literals.
111891                 return 6 /* stringLiteral */;
111892             }
111893             else if (ts.isTemplateLiteralKind(tokenKind)) {
111894                 // TODO (drosen): we should *also* get another classification type for these literals.
111895                 return 6 /* stringLiteral */;
111896             }
111897             else if (tokenKind === 11 /* JsxText */) {
111898                 return 23 /* jsxText */;
111899             }
111900             else if (tokenKind === 75 /* Identifier */) {
111901                 if (token) {
111902                     switch (token.parent.kind) {
111903                         case 245 /* ClassDeclaration */:
111904                             if (token.parent.name === token) {
111905                                 return 11 /* className */;
111906                             }
111907                             return;
111908                         case 155 /* TypeParameter */:
111909                             if (token.parent.name === token) {
111910                                 return 15 /* typeParameterName */;
111911                             }
111912                             return;
111913                         case 246 /* InterfaceDeclaration */:
111914                             if (token.parent.name === token) {
111915                                 return 13 /* interfaceName */;
111916                             }
111917                             return;
111918                         case 248 /* EnumDeclaration */:
111919                             if (token.parent.name === token) {
111920                                 return 12 /* enumName */;
111921                             }
111922                             return;
111923                         case 249 /* ModuleDeclaration */:
111924                             if (token.parent.name === token) {
111925                                 return 14 /* moduleName */;
111926                             }
111927                             return;
111928                         case 156 /* Parameter */:
111929                             if (token.parent.name === token) {
111930                                 return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
111931                             }
111932                             return;
111933                     }
111934                 }
111935                 return 2 /* identifier */;
111936             }
111937         }
111938         function processElement(element) {
111939             if (!element) {
111940                 return;
111941             }
111942             // Ignore nodes that don't intersect the original span to classify.
111943             if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
111944                 checkForClassificationCancellation(cancellationToken, element.kind);
111945                 for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) {
111946                     var child = _a[_i];
111947                     if (!tryClassifyNode(child)) {
111948                         // Recurse into our child nodes.
111949                         processElement(child);
111950                     }
111951                 }
111952             }
111953         }
111954     }
111955     ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications;
111956 })(ts || (ts = {}));
111957 /* @internal */
111958 var ts;
111959 (function (ts) {
111960     var Completions;
111961     (function (Completions) {
111962         var StringCompletions;
111963         (function (StringCompletions) {
111964             function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) {
111965                 if (ts.isInReferenceComment(sourceFile, position)) {
111966                     var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host);
111967                     return entries && convertPathCompletions(entries);
111968                 }
111969                 if (ts.isInString(sourceFile, position, contextToken)) {
111970                     if (!contextToken || !ts.isStringLiteralLike(contextToken))
111971                         return undefined;
111972                     var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host);
111973                     return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences);
111974                 }
111975             }
111976             StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions;
111977             function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) {
111978                 if (completion === undefined) {
111979                     return undefined;
111980                 }
111981                 switch (completion.kind) {
111982                     case 0 /* Paths */:
111983                         return convertPathCompletions(completion.paths);
111984                     case 1 /* Properties */: {
111985                         var entries = [];
111986                         Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
111987                         return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
111988                     }
111989                     case 2 /* Types */: {
111990                         var entries = completion.types.map(function (type) { return ({
111991                             name: type.value,
111992                             kindModifiers: "" /* none */,
111993                             kind: "string" /* string */,
111994                             sortText: "0",
111995                             replacementSpan: ts.getReplacementSpanForContextToken(contextToken)
111996                         }); });
111997                         return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
111998                     }
111999                     default:
112000                         return ts.Debug.assertNever(completion);
112001                 }
112002             }
112003             function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) {
112004                 if (!contextToken || !ts.isStringLiteralLike(contextToken))
112005                     return undefined;
112006                 var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host);
112007                 return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken);
112008             }
112009             StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails;
112010             function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
112011                 switch (completion.kind) {
112012                     case 0 /* Paths */: {
112013                         var match = ts.find(completion.paths, function (p) { return p.name === name; });
112014                         return match && Completions.createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [ts.textPart(name)]);
112015                     }
112016                     case 1 /* Properties */: {
112017                         var match = ts.find(completion.symbols, function (s) { return s.name === name; });
112018                         return match && Completions.createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
112019                     }
112020                     case 2 /* Types */:
112021                         return ts.find(completion.types, function (t) { return t.value === name; }) ? Completions.createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined;
112022                     default:
112023                         return ts.Debug.assertNever(completion);
112024                 }
112025             }
112026             function convertPathCompletions(pathCompletions) {
112027                 var isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
112028                 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.
112029                 var entries = pathCompletions.map(function (_a) {
112030                     var name = _a.name, kind = _a.kind, span = _a.span, extension = _a.extension;
112031                     return ({ name: name, kind: kind, kindModifiers: kindModifiersFromExtension(extension), sortText: Completions.SortText.LocationPriority, replacementSpan: span });
112032                 });
112033                 return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
112034             }
112035             function kindModifiersFromExtension(extension) {
112036                 switch (extension) {
112037                     case ".d.ts" /* Dts */: return ".d.ts" /* dtsModifier */;
112038                     case ".js" /* Js */: return ".js" /* jsModifier */;
112039                     case ".json" /* Json */: return ".json" /* jsonModifier */;
112040                     case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
112041                     case ".ts" /* Ts */: return ".ts" /* tsModifier */;
112042                     case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
112043                     case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
112044                     case undefined: return "" /* none */;
112045                     default:
112046                         return ts.Debug.assertNever(extension);
112047                 }
112048             }
112049             var StringLiteralCompletionKind;
112050             (function (StringLiteralCompletionKind) {
112051                 StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths";
112052                 StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties";
112053                 StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types";
112054             })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {}));
112055             function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) {
112056                 var parent = node.parent;
112057                 switch (parent.kind) {
112058                     case 187 /* LiteralType */:
112059                         switch (parent.parent.kind) {
112060                             case 169 /* TypeReference */:
112061                                 return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false };
112062                             case 185 /* IndexedAccessType */:
112063                                 // Get all apparent property names
112064                                 // i.e. interface Foo {
112065                                 //          foo: string;
112066                                 //          bar: string;
112067                                 //      }
112068                                 //      let x: Foo["/*completion position*/"]
112069                                 return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType));
112070                             case 188 /* ImportType */:
112071                                 return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
112072                             case 178 /* UnionType */: {
112073                                 if (!ts.isTypeReferenceNode(parent.parent.parent))
112074                                     return undefined;
112075                                 var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent);
112076                                 var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); });
112077                                 return { kind: 2 /* Types */, types: types, isNewIdentifier: false };
112078                             }
112079                             default:
112080                                 return undefined;
112081                         }
112082                     case 281 /* PropertyAssignment */:
112083                         if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) {
112084                             // Get quoted name of properties of the object literal expression
112085                             // i.e. interface ConfigFiles {
112086                             //          'jspm:dev': string
112087                             //      }
112088                             //      let files: ConfigFiles = {
112089                             //          '/*completion position*/'
112090                             //      }
112091                             //
112092                             //      function foo(c: ConfigFiles) {}
112093                             //      foo({
112094                             //          '/*completion position*/'
112095                             //      });
112096                             return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
112097                         }
112098                         return fromContextualType();
112099                     case 195 /* ElementAccessExpression */: {
112100                         var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression;
112101                         if (node === argumentExpression) {
112102                             // Get all names of properties on the expression
112103                             // i.e. interface A {
112104                             //      'prop1': string
112105                             // }
112106                             // let a: A;
112107                             // a['/*completion position*/']
112108                             return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
112109                         }
112110                         return undefined;
112111                     }
112112                     case 196 /* CallExpression */:
112113                     case 197 /* NewExpression */:
112114                         if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) {
112115                             var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
112116                             // Get string literal completions from specialized signatures of the target
112117                             // i.e. declare function f(a: 'A');
112118                             // f("/*completion position*/")
112119                             return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType();
112120                         }
112121                     // falls through (is `require("")` or `import("")`)
112122                     case 254 /* ImportDeclaration */:
112123                     case 260 /* ExportDeclaration */:
112124                     case 265 /* ExternalModuleReference */:
112125                         // Get all known external module names or complete a path to a module
112126                         // i.e. import * as ns from "/*completion position*/";
112127                         //      var y = import("/*completion position*/");
112128                         //      import x = require("/*completion position*/");
112129                         //      var y = require("/*completion position*/");
112130                         //      export * from "/*completion position*/";
112131                         return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
112132                     default:
112133                         return fromContextualType();
112134                 }
112135                 function fromContextualType() {
112136                     // Get completion for string literal from string literal type
112137                     // i.e. var x: "hi" | "hello" = "/*completion position*/"
112138                     return { kind: 2 /* Types */, types: getStringLiteralTypes(ts.getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false };
112139                 }
112140             }
112141             function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
112142                 return ts.mapDefined(union.types, function (type) {
112143                     return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined;
112144                 });
112145             }
112146             function getStringLiteralCompletionsFromSignature(argumentInfo, checker) {
112147                 var isNewIdentifier = false;
112148                 var uniques = ts.createMap();
112149                 var candidates = [];
112150                 checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount);
112151                 var types = ts.flatMap(candidates, function (candidate) {
112152                     if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length)
112153                         return;
112154                     var type = checker.getParameterType(candidate, argumentInfo.argumentIndex);
112155                     isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */);
112156                     return getStringLiteralTypes(type, uniques);
112157                 });
112158                 return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier };
112159             }
112160             function stringLiteralCompletionsFromProperties(type) {
112161                 return type && {
112162                     kind: 1 /* Properties */,
112163                     symbols: type.getApparentProperties().filter(function (prop) {
112164                         return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration);
112165                     }),
112166                     hasIndexSignature: ts.hasIndexSignature(type)
112167                 };
112168             }
112169             function getStringLiteralTypes(type, uniques) {
112170                 if (uniques === void 0) { uniques = ts.createMap(); }
112171                 if (!type)
112172                     return ts.emptyArray;
112173                 type = ts.skipConstraint(type);
112174                 return type.isUnion() ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) :
112175                     type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) ? [type] : ts.emptyArray;
112176             }
112177             function nameAndKind(name, kind, extension) {
112178                 return { name: name, kind: kind, extension: extension };
112179             }
112180             function directoryResult(name) {
112181                 return nameAndKind(name, "directory" /* directory */, /*extension*/ undefined);
112182             }
112183             function addReplacementSpans(text, textStart, names) {
112184                 var span = getDirectoryFragmentTextSpan(text, textStart);
112185                 return names.map(function (_a) {
112186                     var name = _a.name, kind = _a.kind, extension = _a.extension;
112187                     return ({ name: name, kind: kind, extension: extension, span: span });
112188                 });
112189             }
112190             function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) {
112191                 return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker));
112192             }
112193             function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) {
112194                 var literalValue = ts.normalizeSlashes(node.text);
112195                 var scriptPath = sourceFile.path;
112196                 var scriptDirectory = ts.getDirectoryPath(scriptPath);
112197                 return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue))
112198                     ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath)
112199                     : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
112200             }
112201             function getExtensionOptions(compilerOptions, includeExtensions) {
112202                 if (includeExtensions === void 0) { includeExtensions = false; }
112203                 return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions };
112204             }
112205             function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) {
112206                 var extensionOptions = getExtensionOptions(compilerOptions);
112207                 if (compilerOptions.rootDirs) {
112208                     return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath);
112209                 }
112210                 else {
112211                     return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath);
112212                 }
112213             }
112214             function getSupportedExtensionsForModuleResolution(compilerOptions) {
112215                 var extensions = ts.getSupportedExtensions(compilerOptions);
112216                 return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
112217                     extensions.concat(".json" /* Json */) :
112218                     extensions;
112219             }
112220             /**
112221              * Takes a script path and returns paths for all potential folders that could be merged with its
112222              * containing folder via the "rootDirs" compiler option
112223              */
112224             function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) {
112225                 // Make all paths absolute/normalized if they are not already
112226                 rootDirs = rootDirs.map(function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
112227                 // Determine the path to the directory containing the script relative to the root directory it is contained within
112228                 var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) {
112229                     return ts.containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined;
112230                 }); // TODO: GH#18217
112231                 // Now find a path for each potential directory that is to be merged with the one containing the script
112232                 return ts.deduplicate(__spreadArrays(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), [scriptDirectory]), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
112233             }
112234             function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) {
112235                 var basePath = compilerOptions.project || host.getCurrentDirectory();
112236                 var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
112237                 var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
112238                 return ts.flatMap(baseDirectories, function (baseDirectory) { return getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude); });
112239             }
112240             /**
112241              * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
112242              */
112243             function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, _a, host, exclude, result) {
112244                 var extensions = _a.extensions, includeExtensions = _a.includeExtensions;
112245                 if (result === void 0) { result = []; }
112246                 if (fragment === undefined) {
112247                     fragment = "";
112248                 }
112249                 fragment = ts.normalizeSlashes(fragment);
112250                 /**
112251                  * Remove the basename from the path. Note that we don't use the basename to filter completions;
112252                  * the client is responsible for refining completions.
112253                  */
112254                 if (!ts.hasTrailingDirectorySeparator(fragment)) {
112255                     fragment = ts.getDirectoryPath(fragment);
112256                 }
112257                 if (fragment === "") {
112258                     fragment = "." + ts.directorySeparator;
112259                 }
112260                 fragment = ts.ensureTrailingDirectorySeparator(fragment);
112261                 // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
112262                 var absolutePath = ts.resolvePath(scriptPath, fragment);
112263                 var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
112264                 var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
112265                 if (!ts.tryDirectoryExists(host, baseDirectory))
112266                     return result;
112267                 // Enumerate the available files if possible
112268                 var files = ts.tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]);
112269                 if (files) {
112270                     /**
112271                      * Multiple file entries might map to the same truncated name once we remove extensions
112272                      * (happens iff includeExtensions === false)so we use a set-like data structure. Eg:
112273                      *
112274                      * both foo.ts and foo.tsx become foo
112275                      */
112276                     var foundFiles = ts.createMap(); // maps file to its extension
112277                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
112278                         var filePath = files_1[_i];
112279                         filePath = ts.normalizePath(filePath);
112280                         if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
112281                             continue;
112282                         }
112283                         var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
112284                         foundFiles.set(foundFileName, ts.tryGetExtensionFromPath(filePath));
112285                     }
112286                     foundFiles.forEach(function (ext, foundFile) {
112287                         result.push(nameAndKind(foundFile, "script" /* scriptElement */, ext));
112288                     });
112289                 }
112290                 // If possible, get folder completion as well
112291                 var directories = ts.tryGetDirectories(host, baseDirectory);
112292                 if (directories) {
112293                     for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) {
112294                         var directory = directories_1[_b];
112295                         var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
112296                         if (directoryName !== "@types") {
112297                             result.push(directoryResult(directoryName));
112298                         }
112299                     }
112300                 }
112301                 // check for a version redirect
112302                 var packageJsonPath = ts.findPackageJson(baseDirectory, host);
112303                 if (packageJsonPath) {
112304                     var packageJson = ts.readJson(packageJsonPath, host);
112305                     var typesVersions = packageJson.typesVersions;
112306                     if (typeof typesVersions === "object") {
112307                         var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions);
112308                         var versionPaths = versionResult && versionResult.paths;
112309                         var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length);
112310                         if (versionPaths) {
112311                             addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host);
112312                         }
112313                     }
112314                 }
112315                 return result;
112316             }
112317             function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) {
112318                 for (var path in paths) {
112319                     if (!ts.hasProperty(paths, path))
112320                         continue;
112321                     var patterns = paths[path];
112322                     if (patterns) {
112323                         var _loop_1 = function (name, kind, extension) {
112324                             // Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
112325                             if (!result.some(function (entry) { return entry.name === name; })) {
112326                                 result.push(nameAndKind(name, kind, extension));
112327                             }
112328                         };
112329                         for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
112330                             var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
112331                             _loop_1(name, kind, extension);
112332                         }
112333                     }
112334                 }
112335             }
112336             /**
112337              * Check all of the declared modules and those in node modules. Possible sources of modules:
112338              *      Modules that are found by the type checker
112339              *      Modules found relative to "baseUrl" compliler options (including patterns from "paths" compiler option)
112340              *      Modules from node_modules (i.e. those listed in package.json)
112341              *          This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
112342              */
112343             function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
112344                 var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
112345                 var result = [];
112346                 var extensionOptions = getExtensionOptions(compilerOptions);
112347                 if (baseUrl) {
112348                     var projectDir = compilerOptions.project || host.getCurrentDirectory();
112349                     var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl));
112350                     getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result);
112351                     if (paths) {
112352                         addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host);
112353                     }
112354                 }
112355                 var fragmentDirectory = getFragmentDirectory(fragment);
112356                 for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) {
112357                     var ambientName = _a[_i];
112358                     result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ undefined));
112359                 }
112360                 getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result);
112361                 if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) {
112362                     // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies.
112363                     // (But do if we didn't find anything, e.g. 'package.json' missing.)
112364                     var foundGlobal = false;
112365                     if (fragmentDirectory === undefined) {
112366                         var _loop_2 = function (moduleName) {
112367                             if (!result.some(function (entry) { return entry.name === moduleName; })) {
112368                                 foundGlobal = true;
112369                                 result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
112370                             }
112371                         };
112372                         for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
112373                             var moduleName = _c[_b];
112374                             _loop_2(moduleName);
112375                         }
112376                     }
112377                     if (!foundGlobal) {
112378                         ts.forEachAncestorDirectory(scriptPath, function (ancestor) {
112379                             var nodeModules = ts.combinePaths(ancestor, "node_modules");
112380                             if (ts.tryDirectoryExists(host, nodeModules)) {
112381                                 getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result);
112382                             }
112383                         });
112384                     }
112385                 }
112386                 return result;
112387             }
112388             function getFragmentDirectory(fragment) {
112389                 return containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
112390             }
112391             function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) {
112392                 if (!ts.endsWith(path, "*")) {
112393                     // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
112394                     return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray;
112395                 }
112396                 var pathPrefix = path.slice(0, path.length - 1);
112397                 var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix);
112398                 return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) {
112399                     return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host);
112400                 });
112401                 function justPathMappingName(name) {
112402                     return ts.startsWith(name, fragment) ? [directoryResult(name)] : ts.emptyArray;
112403                 }
112404             }
112405             function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) {
112406                 if (!host.readDirectory) {
112407                     return undefined;
112408                 }
112409                 var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined;
112410                 if (!parsed) {
112411                     return undefined;
112412                 }
112413                 // The prefix has two effective parts: the directory path and the base component after the filepath that is not a
112414                 // full directory component. For example: directory/path/of/prefix/base*
112415                 var normalizedPrefix = ts.resolvePath(parsed.prefix);
112416                 var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
112417                 var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
112418                 var fragmentHasPath = containsSlash(fragment);
112419                 var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
112420                 // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
112421                 var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
112422                 var normalizedSuffix = ts.normalizePath(parsed.suffix);
112423                 // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
112424                 var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
112425                 var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase;
112426                 // If we have a suffix, then we need to read the directory all the way down. We could create a glob
112427                 // that encodes the suffix, but we would have to escape the character "?" which readDirectory
112428                 // doesn't support. For now, this is safer but slower
112429                 var includeGlob = normalizedSuffix ? "**/*" : "./*";
112430                 var matches = ts.mapDefined(ts.tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), function (match) {
112431                     var extension = ts.tryGetExtensionFromPath(match);
112432                     var name = trimPrefixAndSuffix(match);
112433                     return name === undefined ? undefined : nameAndKind(ts.removeFileExtension(name), "script" /* scriptElement */, extension);
112434                 });
112435                 var directories = ts.mapDefined(ts.tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }), function (dir) {
112436                     var name = trimPrefixAndSuffix(dir);
112437                     return name === undefined ? undefined : directoryResult(name);
112438                 });
112439                 return __spreadArrays(matches, directories);
112440                 function trimPrefixAndSuffix(path) {
112441                     var inner = withoutStartAndEnd(ts.normalizePath(path), completePrefix, normalizedSuffix);
112442                     return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner);
112443                 }
112444             }
112445             function withoutStartAndEnd(s, start, end) {
112446                 return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined;
112447             }
112448             function removeLeadingDirectorySeparator(path) {
112449                 return path[0] === ts.directorySeparator ? path.slice(1) : path;
112450             }
112451             function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) {
112452                 // Get modules that the type checker picked up
112453                 var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); });
112454                 var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); });
112455                 // Nested modules of the form "module-name/sub" need to be adjusted to only return the string
112456                 // after the last '/' that appears in the fragment because that's where the replacement span
112457                 // starts
112458                 if (fragmentDirectory !== undefined) {
112459                     var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory);
112460                     return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); });
112461                 }
112462                 return nonRelativeModuleNames;
112463             }
112464             function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
112465                 var token = ts.getTokenAtPosition(sourceFile, position);
112466                 var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
112467                 var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; });
112468                 if (!range) {
112469                     return undefined;
112470                 }
112471                 var text = sourceFile.text.slice(range.pos, position);
112472                 var match = tripleSlashDirectiveFragmentRegex.exec(text);
112473                 if (!match) {
112474                     return undefined;
112475                 }
112476                 var prefix = match[1], kind = match[2], toComplete = match[3];
112477                 var scriptPath = ts.getDirectoryPath(sourceFile.path);
112478                 var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path)
112479                     : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions))
112480                         : ts.Debug.fail();
112481                 return addReplacementSpans(toComplete, range.pos + prefix.length, names);
112482             }
112483             function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result) {
112484                 if (result === void 0) { result = []; }
112485                 // Check for typings specified in compiler options
112486                 var seen = ts.createMap();
112487                 var typeRoots = ts.tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
112488                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
112489                     var root = typeRoots_1[_i];
112490                     getCompletionEntriesFromDirectories(root);
112491                 }
112492                 // Also get all @types typings installed in visible node_modules directories
112493                 for (var _a = 0, _b = ts.findPackageJsons(scriptPath, host); _a < _b.length; _a++) {
112494                     var packageJson = _b[_a];
112495                     var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types");
112496                     getCompletionEntriesFromDirectories(typesDir);
112497                 }
112498                 return result;
112499                 function getCompletionEntriesFromDirectories(directory) {
112500                     if (!ts.tryDirectoryExists(host, directory))
112501                         return;
112502                     for (var _i = 0, _a = ts.tryGetDirectories(host, directory); _i < _a.length; _i++) {
112503                         var typeDirectoryName = _a[_i];
112504                         var packageName = ts.unmangleScopedPackageName(typeDirectoryName);
112505                         if (options.types && !ts.contains(options.types, packageName))
112506                             continue;
112507                         if (fragmentDirectory === undefined) {
112508                             if (!seen.has(packageName)) {
112509                                 result.push(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ undefined));
112510                                 seen.set(packageName, true);
112511                             }
112512                         }
112513                         else {
112514                             var baseDirectory = ts.combinePaths(directory, typeDirectoryName);
112515                             var remainingFragment = ts.tryRemoveDirectoryPrefix(fragmentDirectory, packageName, ts.hostGetCanonicalFileName(host));
112516                             if (remainingFragment !== undefined) {
112517                                 getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result);
112518                             }
112519                         }
112520                     }
112521                 }
112522             }
112523             function enumerateNodeModulesVisibleToScript(host, scriptPath) {
112524                 if (!host.readFile || !host.fileExists)
112525                     return ts.emptyArray;
112526                 var result = [];
112527                 for (var _i = 0, _a = ts.findPackageJsons(scriptPath, host); _i < _a.length; _i++) {
112528                     var packageJson = _a[_i];
112529                     var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined
112530                     // Provide completions for all non @types dependencies
112531                     for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) {
112532                         var key = nodeModulesDependencyKeys_1[_b];
112533                         var dependencies = contents[key];
112534                         if (!dependencies)
112535                             continue;
112536                         for (var dep in dependencies) {
112537                             if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) {
112538                                 result.push(dep);
112539                             }
112540                         }
112541                     }
112542                 }
112543                 return result;
112544             }
112545             // Replace everything after the last directory separator that appears
112546             function getDirectoryFragmentTextSpan(text, textStart) {
112547                 var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\"));
112548                 var offset = index !== -1 ? index + 1 : 0;
112549                 // If the range is an identifier, span is unnecessary.
112550                 var length = text.length - offset;
112551                 return length === 0 || ts.isIdentifierText(text.substr(offset, length), 99 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
112552             }
112553             // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
112554             function isPathRelativeToScript(path) {
112555                 if (path && path.length >= 2 && path.charCodeAt(0) === 46 /* dot */) {
112556                     var slashIndex = path.length >= 3 && path.charCodeAt(1) === 46 /* dot */ ? 2 : 1;
112557                     var slashCharCode = path.charCodeAt(slashIndex);
112558                     return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */;
112559                 }
112560                 return false;
112561             }
112562             /**
112563              * Matches a triple slash reference directive with an incomplete string literal for its path. Used
112564              * to determine if the caret is currently within the string literal and capture the literal fragment
112565              * for completions.
112566              * For example, this matches
112567              *
112568              * /// <reference path="fragment
112569              *
112570              * but not
112571              *
112572              * /// <reference path="fragment"
112573              */
112574             var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
112575             var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
112576             function containsSlash(fragment) {
112577                 return ts.stringContains(fragment, ts.directorySeparator);
112578             }
112579         })(StringCompletions = Completions.StringCompletions || (Completions.StringCompletions = {}));
112580     })(Completions = ts.Completions || (ts.Completions = {}));
112581 })(ts || (ts = {}));
112582 /* @internal */
112583 var ts;
112584 (function (ts) {
112585     var Completions;
112586     (function (Completions) {
112587         var SortText;
112588         (function (SortText) {
112589             SortText["LocationPriority"] = "0";
112590             SortText["OptionalMember"] = "1";
112591             SortText["MemberDeclaredBySpreadAssignment"] = "2";
112592             SortText["SuggestedClassMembers"] = "3";
112593             SortText["GlobalsOrKeywords"] = "4";
112594             SortText["AutoImportSuggestions"] = "5";
112595             SortText["JavascriptIdentifiers"] = "6";
112596         })(SortText = Completions.SortText || (Completions.SortText = {}));
112597         /**
112598          * Special values for `CompletionInfo['source']` used to disambiguate
112599          * completion items with the same `name`. (Each completion item must
112600          * have a unique name/source combination, because those two fields
112601          * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`.
112602          *
112603          * When the completion item is an auto-import suggestion, the source
112604          * is the module specifier of the suggestion. To avoid collisions,
112605          * the values here should not be a module specifier we would ever
112606          * generate for an auto-import.
112607          */
112608         var CompletionSource;
112609         (function (CompletionSource) {
112610             /** Completions that require `this.` insertion text */
112611             CompletionSource["ThisProperty"] = "ThisProperty/";
112612         })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {}));
112613         var SymbolOriginInfoKind;
112614         (function (SymbolOriginInfoKind) {
112615             SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType";
112616             SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMember"] = 2] = "SymbolMember";
112617             SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export";
112618             SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise";
112619             SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable";
112620             SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport";
112621             SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport";
112622         })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {}));
112623         function originIsThisType(origin) {
112624             return !!(origin.kind & 1 /* ThisType */);
112625         }
112626         function originIsSymbolMember(origin) {
112627             return !!(origin.kind & 2 /* SymbolMember */);
112628         }
112629         function originIsExport(origin) {
112630             return !!(origin && origin.kind & 4 /* Export */);
112631         }
112632         function originIsPromise(origin) {
112633             return !!(origin.kind & 8 /* Promise */);
112634         }
112635         function originIsNullableMember(origin) {
112636             return !!(origin.kind & 16 /* Nullable */);
112637         }
112638         var KeywordCompletionFilters;
112639         (function (KeywordCompletionFilters) {
112640             KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None";
112641             KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All";
112642             KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords";
112643             KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords";
112644             KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
112645             KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
112646             KeywordCompletionFilters[KeywordCompletionFilters["TypeAssertionKeywords"] = 6] = "TypeAssertionKeywords";
112647             KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 7] = "TypeKeywords";
112648             KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 7] = "Last";
112649         })(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
112650         var GlobalsSearch;
112651         (function (GlobalsSearch) {
112652             GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue";
112653             GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success";
112654             GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail";
112655         })(GlobalsSearch || (GlobalsSearch = {}));
112656         function createImportSuggestionsForFileCache() {
112657             var cache;
112658             var projectVersion;
112659             var fileName;
112660             return {
112661                 isEmpty: function () {
112662                     return !cache;
112663                 },
112664                 clear: function () {
112665                     cache = undefined;
112666                     fileName = undefined;
112667                     projectVersion = undefined;
112668                 },
112669                 set: function (file, suggestions, version) {
112670                     cache = suggestions;
112671                     fileName = file;
112672                     if (version) {
112673                         projectVersion = version;
112674                     }
112675                 },
112676                 get: function (file, checker, version) {
112677                     if (file !== fileName) {
112678                         return undefined;
112679                     }
112680                     if (version) {
112681                         return projectVersion === version ? cache : undefined;
112682                     }
112683                     ts.forEach(cache, function (suggestion) {
112684                         var _a, _b, _c;
112685                         // If the symbol/moduleSymbol was a merged symbol, it will have a new identity
112686                         // in the checker, even though the symbols to merge are the same (guaranteed by
112687                         // cache invalidation in synchronizeHostData).
112688                         if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) {
112689                             suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport
112690                                 ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol : suggestion.symbol.declarations[0].symbol);
112691                         }
112692                         if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) {
112693                             suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol);
112694                         }
112695                     });
112696                     return cache;
112697                 },
112698             };
112699         }
112700         Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache;
112701         function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) {
112702             var typeChecker = program.getTypeChecker();
112703             var compilerOptions = program.getCompilerOptions();
112704             var contextToken = ts.findPrecedingToken(position, sourceFile);
112705             if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) {
112706                 return undefined;
112707             }
112708             var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences);
112709             if (stringCompletions) {
112710                 return stringCompletions;
112711             }
112712             if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent)
112713                 && (contextToken.kind === 77 /* BreakKeyword */ || contextToken.kind === 82 /* ContinueKeyword */ || contextToken.kind === 75 /* Identifier */)) {
112714                 return getLabelCompletionAtPosition(contextToken.parent);
112715             }
112716             var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined, host);
112717             if (!completionData) {
112718                 return undefined;
112719             }
112720             switch (completionData.kind) {
112721                 case 0 /* Data */:
112722                     return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences);
112723                 case 1 /* JsDocTagName */:
112724                     // If the current position is a jsDoc tag name, only tag names should be provided for completion
112725                     return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions());
112726                 case 2 /* JsDocTag */:
112727                     // If the current position is a jsDoc tag, only tags should be provided for completion
112728                     return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions());
112729                 case 3 /* JsDocParameterName */:
112730                     return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag));
112731                 default:
112732                     return ts.Debug.assertNever(completionData);
112733             }
112734         }
112735         Completions.getCompletionsAtPosition = getCompletionsAtPosition;
112736         function jsdocCompletionInfo(entries) {
112737             return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
112738         }
112739         function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) {
112740             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;
112741             if (location && location.parent && ts.isJsxClosingElement(location.parent)) {
112742                 // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
112743                 // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
112744                 // For example:
112745                 //     var x = <div> </ /*1*/
112746                 // The completion list at "1" will contain "div>" with type any
112747                 // And at `<div> </ /*1*/ >` (with a closing `>`), the completion list will contain "div".
112748                 var tagName = location.parent.parent.openingElement.tagName;
112749                 var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile);
112750                 var entry = {
112751                     name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"),
112752                     kind: "class" /* classElement */,
112753                     kindModifiers: undefined,
112754                     sortText: SortText.LocationPriority,
112755                 };
112756                 return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] };
112757             }
112758             var entries = [];
112759             if (isUncheckedFile(sourceFile, compilerOptions)) {
112760                 var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, 
112761                 /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap);
112762                 getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217
112763             }
112764             else {
112765                 if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) {
112766                     return undefined;
112767                 }
112768                 getCompletionEntriesFromSymbols(symbols, entries, 
112769                 /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap);
112770             }
112771             if (keywordFilters !== 0 /* None */) {
112772                 var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
112773                 for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
112774                     var keywordEntry = _a[_i];
112775                     if (!entryNames.has(keywordEntry.name)) {
112776                         entries.push(keywordEntry);
112777                     }
112778                 }
112779             }
112780             for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) {
112781                 var literal = literals_1[_b];
112782                 entries.push(createCompletionEntryForLiteral(literal, preferences));
112783             }
112784             return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
112785         }
112786         function isUncheckedFile(sourceFile, compilerOptions) {
112787             return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions);
112788         }
112789         function isMemberCompletionKind(kind) {
112790             switch (kind) {
112791                 case 0 /* ObjectPropertyDeclaration */:
112792                 case 3 /* MemberLike */:
112793                 case 2 /* PropertyAccess */:
112794                     return true;
112795                 default:
112796                     return false;
112797             }
112798         }
112799         function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) {
112800             ts.getNameTable(sourceFile).forEach(function (pos, name) {
112801                 // Skip identifiers produced only from the current location
112802                 if (pos === position) {
112803                     return;
112804                 }
112805                 var realName = ts.unescapeLeadingUnderscores(name);
112806                 if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) {
112807                     uniqueNames.add(realName);
112808                     entries.push({
112809                         name: realName,
112810                         kind: "warning" /* warning */,
112811                         kindModifiers: "",
112812                         sortText: SortText.JavascriptIdentifiers,
112813                         isFromUncheckedFile: true
112814                     });
112815                 }
112816             });
112817         }
112818         function completionNameForLiteral(literal, preferences) {
112819             return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" :
112820                 ts.isString(literal) ? ts.quote(literal, preferences) : JSON.stringify(literal);
112821         }
112822         function createCompletionEntryForLiteral(literal, preferences) {
112823             return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority };
112824         }
112825         function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) {
112826             var insertText;
112827             var replacementSpan = ts.getReplacementSpanForContextToken(contextToken);
112828             var insertQuestionDot = origin && originIsNullableMember(origin);
112829             var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
112830             if (origin && originIsThisType(origin)) {
112831                 insertText = needsConvertPropertyAccess
112832                     ? "this" + (insertQuestionDot ? "?." : "") + "[" + quotePropertyName(name, preferences) + "]"
112833                     : "this" + (insertQuestionDot ? "?." : ".") + name;
112834             }
112835             // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790.
112836             // 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.
112837             else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) {
112838                 insertText = useBraces ? needsConvertPropertyAccess ? "[" + quotePropertyName(name, preferences) + "]" : "[" + name + "]" : name;
112839                 if (insertQuestionDot || propertyAccessToConvert.questionDotToken) {
112840                     insertText = "?." + insertText;
112841                 }
112842                 var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile) ||
112843                     ts.findChildOfKind(propertyAccessToConvert, 28 /* QuestionDotToken */, sourceFile);
112844                 if (!dot) {
112845                     return undefined;
112846                 }
112847                 // If the text after the '.' starts with this name, write over it. Else, add new text.
112848                 var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end;
112849                 replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end);
112850             }
112851             if (isJsxInitializer) {
112852                 if (insertText === undefined)
112853                     insertText = name;
112854                 insertText = "{" + insertText + "}";
112855                 if (typeof isJsxInitializer !== "boolean") {
112856                     replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile);
112857                 }
112858             }
112859             if (origin && originIsPromise(origin) && propertyAccessToConvert) {
112860                 if (insertText === undefined)
112861                     insertText = name;
112862                 var precedingToken = ts.findPrecedingToken(propertyAccessToConvert.pos, sourceFile);
112863                 var awaitText = "";
112864                 if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
112865                     awaitText = ";";
112866                 }
112867                 awaitText += "(await " + propertyAccessToConvert.expression.getText() + ")";
112868                 insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText;
112869                 replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end);
112870             }
112871             if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) {
112872                 return undefined;
112873             }
112874             // TODO(drosen): Right now we just permit *all* semantic meanings when calling
112875             // 'getSymbolKind' which is permissible given that it is backwards compatible; but
112876             // really we should consider passing the meaning for the node so that we don't report
112877             // that a suggestion for a value is an interface.  We COULD also just do what
112878             // 'getSymbolModifiers' does, which is to use the first declaration.
112879             // Use a 'sortText' of 0' so that all symbol completion entries come before any other
112880             // entries (like JavaScript identifier entries).
112881             return {
112882                 name: name,
112883                 kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
112884                 kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
112885                 sortText: sortText,
112886                 source: getSourceFromOrigin(origin),
112887                 hasAction: origin && originIsExport(origin) || undefined,
112888                 isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined,
112889                 insertText: insertText,
112890                 replacementSpan: replacementSpan,
112891             };
112892         }
112893         function quotePropertyName(name, preferences) {
112894             if (/^\d+$/.test(name)) {
112895                 return name;
112896             }
112897             return ts.quote(name, preferences);
112898         }
112899         function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) {
112900             return localSymbol === recommendedCompletion ||
112901                 !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion;
112902         }
112903         function getSourceFromOrigin(origin) {
112904             if (originIsExport(origin)) {
112905                 return ts.stripQuotes(origin.moduleSymbol.name);
112906             }
112907             if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) {
112908                 return CompletionSource.ThisProperty;
112909             }
112910         }
112911         function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) {
112912             var start = ts.timestamp();
112913             // Tracks unique names.
112914             // Value is set to false for global variables or completions from external module exports, because we can have multiple of those;
112915             // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports.
112916             // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
112917             var uniques = ts.createMap();
112918             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
112919                 var symbol = symbols_1[_i];
112920                 var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
112921                 var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected);
112922                 if (!info) {
112923                     continue;
112924                 }
112925                 var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess;
112926                 if (uniques.get(name)) {
112927                     continue;
112928                 }
112929                 var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
112930                 if (!entry) {
112931                     continue;
112932                 }
112933                 /** True for locals; false for globals, module exports from other files, `this.` completions. */
112934                 var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }));
112935                 uniques.set(name, shouldShadowLaterSymbols);
112936                 entries.push(entry);
112937             }
112938             log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start));
112939             // Prevent consumers of this map from having to worry about
112940             // the boolean value. Externally, it should be seen as the
112941             // set of all names.
112942             return {
112943                 has: function (name) { return uniques.has(name); },
112944                 add: function (name) { return uniques.set(name, true); },
112945             };
112946         }
112947         Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols;
112948         function getLabelCompletionAtPosition(node) {
112949             var entries = getLabelStatementCompletions(node);
112950             if (entries.length) {
112951                 return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
112952             }
112953         }
112954         function getLabelStatementCompletions(node) {
112955             var entries = [];
112956             var uniques = ts.createMap();
112957             var current = node;
112958             while (current) {
112959                 if (ts.isFunctionLike(current)) {
112960                     break;
112961                 }
112962                 if (ts.isLabeledStatement(current)) {
112963                     var name = current.label.text;
112964                     if (!uniques.has(name)) {
112965                         uniques.set(name, true);
112966                         entries.push({
112967                             name: name,
112968                             kindModifiers: "" /* none */,
112969                             kind: "label" /* label */,
112970                             sortText: SortText.LocationPriority
112971                         });
112972                     }
112973                 }
112974                 current = current.parent;
112975             }
112976             return entries;
112977         }
112978         function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) {
112979             var compilerOptions = program.getCompilerOptions();
112980             var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host);
112981             if (!completionData) {
112982                 return { type: "none" };
112983             }
112984             if (completionData.kind !== 0 /* Data */) {
112985                 return { type: "request", request: completionData };
112986             }
112987             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;
112988             var literal = ts.find(literals, function (l) { return completionNameForLiteral(l, preferences) === entryId.name; });
112989             if (literal !== undefined)
112990                 return { type: "literal", literal: literal };
112991             // Find the symbol with the matching entry name.
112992             // We don't need to perform character checks here because we're only comparing the
112993             // name against 'entryName' (which is known to be good), not building a new
112994             // completion entry.
112995             return ts.firstDefined(symbols, function (symbol) {
112996                 var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
112997                 var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected);
112998                 return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source
112999                     ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation }
113000                     : undefined;
113001             }) || { type: "none" };
113002         }
113003         function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
113004             var typeChecker = program.getTypeChecker();
113005             var compilerOptions = program.getCompilerOptions();
113006             var name = entryId.name;
113007             var contextToken = ts.findPrecedingToken(position, sourceFile);
113008             if (ts.isInString(sourceFile, position, contextToken)) {
113009                 return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken);
113010             }
113011             // Compute all the completion symbols again.
113012             var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
113013             switch (symbolCompletion.type) {
113014                 case "request": {
113015                     var request = symbolCompletion.request;
113016                     switch (request.kind) {
113017                         case 1 /* JsDocTagName */:
113018                             return ts.JsDoc.getJSDocTagNameCompletionDetails(name);
113019                         case 2 /* JsDocTag */:
113020                             return ts.JsDoc.getJSDocTagCompletionDetails(name);
113021                         case 3 /* JsDocParameterName */:
113022                             return ts.JsDoc.getJSDocParameterNameCompletionDetails(name);
113023                         default:
113024                             return ts.Debug.assertNever(request);
113025                     }
113026                 }
113027                 case "symbol": {
113028                     var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken;
113029                     var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay;
113030                     return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
113031                 }
113032                 case "literal": {
113033                     var literal = symbolCompletion.literal;
113034                     return createSimpleDetails(completionNameForLiteral(literal, preferences), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral);
113035                 }
113036                 case "none":
113037                     // Didn't find a symbol with this name.  See if we can find a keyword instead.
113038                     return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined;
113039                 default:
113040                     ts.Debug.assertNever(symbolCompletion);
113041             }
113042         }
113043         Completions.getCompletionEntryDetails = getCompletionEntryDetails;
113044         function createSimpleDetails(name, kind, kind2) {
113045             return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]);
113046         }
113047         function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) {
113048             var _a = checker.runWithCancellationToken(cancellationToken, function (checker) {
113049                 return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */);
113050             }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags;
113051             return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
113052         }
113053         Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol;
113054         function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
113055             return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source };
113056         }
113057         Completions.createCompletionDetails = createCompletionDetails;
113058         function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) {
113059             var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
113060             if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) {
113061                 return { codeActions: undefined, sourceDisplay: undefined };
113062             }
113063             var moduleSymbol = symbolOriginInfo.moduleSymbol;
113064             var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker));
113065             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;
113066             return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] };
113067         }
113068         function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) {
113069             var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences);
113070             return completion.type === "symbol" ? completion.symbol : undefined;
113071         }
113072         Completions.getCompletionEntrySymbol = getCompletionEntrySymbol;
113073         var CompletionDataKind;
113074         (function (CompletionDataKind) {
113075             CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data";
113076             CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName";
113077             CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag";
113078             CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName";
113079         })(CompletionDataKind || (CompletionDataKind = {}));
113080         var CompletionKind;
113081         (function (CompletionKind) {
113082             CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration";
113083             CompletionKind[CompletionKind["Global"] = 1] = "Global";
113084             CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess";
113085             CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike";
113086             CompletionKind[CompletionKind["String"] = 4] = "String";
113087             CompletionKind[CompletionKind["None"] = 5] = "None";
113088         })(CompletionKind = Completions.CompletionKind || (Completions.CompletionKind = {}));
113089         function getRecommendedCompletion(previousToken, contextualType, checker) {
113090             // For a union, return the first one with a recommended completion.
113091             return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) {
113092                 var symbol = type && type.symbol;
113093                 // Don't include make a recommended completion for an abstract class
113094                 return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol))
113095                     ? getFirstSymbolInChain(symbol, previousToken, checker)
113096                     : undefined;
113097             });
113098         }
113099         function getContextualType(previousToken, position, sourceFile, checker) {
113100             var parent = previousToken.parent;
113101             switch (previousToken.kind) {
113102                 case 75 /* Identifier */:
113103                     return ts.getContextualTypeFromParent(previousToken, checker);
113104                 case 62 /* EqualsToken */:
113105                     switch (parent.kind) {
113106                         case 242 /* VariableDeclaration */:
113107                             return checker.getContextualType(parent.initializer); // TODO: GH#18217
113108                         case 209 /* BinaryExpression */:
113109                             return checker.getTypeAtLocation(parent.left);
113110                         case 273 /* JsxAttribute */:
113111                             return checker.getContextualTypeForJsxAttribute(parent);
113112                         default:
113113                             return undefined;
113114                     }
113115                 case 99 /* NewKeyword */:
113116                     return checker.getContextualType(parent);
113117                 case 78 /* CaseKeyword */:
113118                     return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker);
113119                 case 18 /* OpenBraceToken */:
113120                     return ts.isJsxExpression(parent) && parent.parent.kind !== 266 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined;
113121                 default:
113122                     var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile);
113123                     return argInfo ?
113124                         // At `,`, treat this as the next argument after the comma.
113125                         checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 27 /* CommaToken */ ? 1 : 0)) :
113126                         ts.isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && ts.isEqualityOperatorKind(parent.operatorToken.kind) ?
113127                             // completion at `x ===/**/` should be for the right side
113128                             checker.getTypeAtLocation(parent.left) :
113129                             checker.getContextualType(previousToken);
113130             }
113131         }
113132         function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) {
113133             var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false);
113134             if (chain)
113135                 return ts.first(chain);
113136             return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
113137         }
113138         function isModuleSymbol(symbol) {
113139             return symbol.declarations.some(function (d) { return d.kind === 290 /* SourceFile */; });
113140         }
113141         function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) {
113142             var typeChecker = program.getTypeChecker();
113143             var start = ts.timestamp();
113144             var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853
113145             // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
113146             log("getCompletionData: Get current token: " + (ts.timestamp() - start));
113147             start = ts.timestamp();
113148             var insideComment = ts.isInComment(sourceFile, position, currentToken);
113149             log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
113150             var insideJsDocTagTypeExpression = false;
113151             var isInSnippetScope = false;
113152             if (insideComment) {
113153                 if (ts.hasDocComment(sourceFile, position)) {
113154                     if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
113155                         // The current position is next to the '@' sign, when no tag name being provided yet.
113156                         // Provide a full list of tag names
113157                         return { kind: 1 /* JsDocTagName */ };
113158                     }
113159                     else {
113160                         // When completion is requested without "@", we will have check to make sure that
113161                         // there are no comments prefix the request position. We will only allow "*" and space.
113162                         // e.g
113163                         //   /** |c| /*
113164                         //
113165                         //   /**
113166                         //     |c|
113167                         //    */
113168                         //
113169                         //   /**
113170                         //    * |c|
113171                         //    */
113172                         //
113173                         //   /**
113174                         //    *         |c|
113175                         //    */
113176                         var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
113177                         if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) {
113178                             return { kind: 2 /* JsDocTag */ };
113179                         }
113180                     }
113181                 }
113182                 // Completion should work inside certain JsDoc tags. For example:
113183                 //     /** @type {number | string} */
113184                 // Completion should work in the brackets
113185                 var tag = getJsDocTagAtPosition(currentToken, position);
113186                 if (tag) {
113187                     if (tag.tagName.pos <= position && position <= tag.tagName.end) {
113188                         return { kind: 1 /* JsDocTagName */ };
113189                     }
113190                     if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
113191                         currentToken = ts.getTokenAtPosition(sourceFile, position);
113192                         if (!currentToken ||
113193                             (!ts.isDeclarationName(currentToken) &&
113194                                 (currentToken.parent.kind !== 323 /* JSDocPropertyTag */ ||
113195                                     currentToken.parent.name !== currentToken))) {
113196                             // Use as type location if inside tag's type expression
113197                             insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
113198                         }
113199                     }
113200                     if (!insideJsDocTagTypeExpression && ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) {
113201                         return { kind: 3 /* JsDocParameterName */, tag: tag };
113202                     }
113203                 }
113204                 if (!insideJsDocTagTypeExpression) {
113205                     // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal
113206                     // comment or the plain text part of a jsDoc comment, so no completion should be available
113207                     log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
113208                     return undefined;
113209                 }
113210             }
113211             start = ts.timestamp();
113212             var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217
113213             log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start));
113214             // The decision to provide completion depends on the contextToken, which is determined through the previousToken.
113215             // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file
113216             var contextToken = previousToken;
113217             // 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|
113218             // Skip this partial identifier and adjust the contextToken to the token that precedes it.
113219             if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
113220                 var start_1 = ts.timestamp();
113221                 contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
113222                 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
113223             }
113224             // Find the node where completion is requested on.
113225             // Also determine whether we are trying to complete with members of that node
113226             // or attributes of a JSX tag.
113227             var node = currentToken;
113228             var propertyAccessToConvert;
113229             var isRightOfDot = false;
113230             var isRightOfQuestionDot = false;
113231             var isRightOfOpenTag = false;
113232             var isStartingCloseTag = false;
113233             var isJsxInitializer = false;
113234             var isJsxIdentifierExpected = false;
113235             var location = ts.getTouchingPropertyName(sourceFile, position);
113236             if (contextToken) {
113237                 // Bail out if this is a known invalid completion location
113238                 if (isCompletionListBlocker(contextToken)) {
113239                     log("Returning an empty list because completion was requested in an invalid position.");
113240                     return undefined;
113241                 }
113242                 var parent = contextToken.parent;
113243                 if (contextToken.kind === 24 /* DotToken */ || contextToken.kind === 28 /* QuestionDotToken */) {
113244                     isRightOfDot = contextToken.kind === 24 /* DotToken */;
113245                     isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */;
113246                     switch (parent.kind) {
113247                         case 194 /* PropertyAccessExpression */:
113248                             propertyAccessToConvert = parent;
113249                             node = propertyAccessToConvert.expression;
113250                             if (node.end === contextToken.pos &&
113251                                 ts.isCallExpression(node) &&
113252                                 node.getChildCount(sourceFile) &&
113253                                 ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
113254                                 // This is likely dot from incorrectly parsed call expression and user is starting to write spread
113255                                 // eg: Math.min(./**/)
113256                                 return undefined;
113257                             }
113258                             break;
113259                         case 153 /* QualifiedName */:
113260                             node = parent.left;
113261                             break;
113262                         case 249 /* ModuleDeclaration */:
113263                             node = parent.name;
113264                             break;
113265                         case 188 /* ImportType */:
113266                         case 219 /* MetaProperty */:
113267                             node = parent;
113268                             break;
113269                         default:
113270                             // There is nothing that precedes the dot, so this likely just a stray character
113271                             // or leading into a '...' token. Just bail out instead.
113272                             return undefined;
113273                     }
113274                 }
113275                 else if (sourceFile.languageVariant === 1 /* JSX */) {
113276                     // <UI.Test /* completion position */ />
113277                     // If the tagname is a property access expression, we will then walk up to the top most of property access expression.
113278                     // Then, try to get a JSX container and its associated attributes type.
113279                     if (parent && parent.kind === 194 /* PropertyAccessExpression */) {
113280                         contextToken = parent;
113281                         parent = parent.parent;
113282                     }
113283                     // Fix location
113284                     if (currentToken.parent === location) {
113285                         switch (currentToken.kind) {
113286                             case 31 /* GreaterThanToken */:
113287                                 if (currentToken.parent.kind === 266 /* JsxElement */ || currentToken.parent.kind === 268 /* JsxOpeningElement */) {
113288                                     location = currentToken;
113289                                 }
113290                                 break;
113291                             case 43 /* SlashToken */:
113292                                 if (currentToken.parent.kind === 267 /* JsxSelfClosingElement */) {
113293                                     location = currentToken;
113294                                 }
113295                                 break;
113296                         }
113297                     }
113298                     switch (parent.kind) {
113299                         case 269 /* JsxClosingElement */:
113300                             if (contextToken.kind === 43 /* SlashToken */) {
113301                                 isStartingCloseTag = true;
113302                                 location = contextToken;
113303                             }
113304                             break;
113305                         case 209 /* BinaryExpression */:
113306                             if (!binaryExpressionMayBeOpenTag(parent)) {
113307                                 break;
113308                             }
113309                         // falls through
113310                         case 267 /* JsxSelfClosingElement */:
113311                         case 266 /* JsxElement */:
113312                         case 268 /* JsxOpeningElement */:
113313                             isJsxIdentifierExpected = true;
113314                             if (contextToken.kind === 29 /* LessThanToken */) {
113315                                 isRightOfOpenTag = true;
113316                                 location = contextToken;
113317                             }
113318                             break;
113319                         case 273 /* JsxAttribute */:
113320                             switch (previousToken.kind) {
113321                                 case 62 /* EqualsToken */:
113322                                     isJsxInitializer = true;
113323                                     break;
113324                                 case 75 /* Identifier */:
113325                                     isJsxIdentifierExpected = true;
113326                                     // For `<div x=[|f/**/|]`, `parent` will be `x` and `previousToken.parent` will be `f` (which is its own JsxAttribute)
113327                                     // Note for `<div someBool f>` we don't want to treat this as a jsx inializer, instead it's the attribute name.
113328                                     if (parent !== previousToken.parent &&
113329                                         !parent.initializer &&
113330                                         ts.findChildOfKind(parent, 62 /* EqualsToken */, sourceFile)) {
113331                                         isJsxInitializer = previousToken;
113332                                     }
113333                             }
113334                             break;
113335                     }
113336                 }
113337             }
113338             var semanticStart = ts.timestamp();
113339             var completionKind = 5 /* None */;
113340             var isNewIdentifierLocation = false;
113341             var keywordFilters = 0 /* None */;
113342             // This also gets mutated in nested-functions after the return
113343             var symbols = [];
113344             var symbolToOriginInfoMap = [];
113345             var symbolToSortTextMap = [];
113346             var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache();
113347             var isTypeOnly = isTypeOnlyCompletion();
113348             if (isRightOfDot || isRightOfQuestionDot) {
113349                 getTypeScriptMemberSymbols();
113350             }
113351             else if (isRightOfOpenTag) {
113352                 var tagSymbols = typeChecker.getJsxIntrinsicTagNamesAt(location);
113353                 ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined");
113354                 tryGetGlobalSymbols();
113355                 symbols = tagSymbols.concat(symbols);
113356                 completionKind = 3 /* MemberLike */;
113357                 keywordFilters = 0 /* None */;
113358             }
113359             else if (isStartingCloseTag) {
113360                 var tagName = contextToken.parent.parent.openingElement.tagName;
113361                 var tagSymbol = typeChecker.getSymbolAtLocation(tagName);
113362                 if (tagSymbol) {
113363                     symbols = [tagSymbol];
113364                 }
113365                 completionKind = 3 /* MemberLike */;
113366                 keywordFilters = 0 /* None */;
113367             }
113368             else {
113369                 // For JavaScript or TypeScript, if we're not after a dot, then just try to get the
113370                 // global symbols in scope.  These results should be valid for either language as
113371                 // the set of symbols that can be referenced from this location.
113372                 if (!tryGetGlobalSymbols()) {
113373                     return undefined;
113374                 }
113375             }
113376             log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
113377             var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
113378             var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
113379             var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
113380             return {
113381                 kind: 0 /* Data */,
113382                 symbols: symbols,
113383                 completionKind: completionKind,
113384                 isInSnippetScope: isInSnippetScope,
113385                 propertyAccessToConvert: propertyAccessToConvert,
113386                 isNewIdentifierLocation: isNewIdentifierLocation,
113387                 location: location,
113388                 keywordFilters: keywordFilters,
113389                 literals: literals,
113390                 symbolToOriginInfoMap: symbolToOriginInfoMap,
113391                 recommendedCompletion: recommendedCompletion,
113392                 previousToken: previousToken,
113393                 isJsxInitializer: isJsxInitializer,
113394                 insideJsDocTagTypeExpression: insideJsDocTagTypeExpression,
113395                 symbolToSortTextMap: symbolToSortTextMap,
113396                 isTypeOnlyLocation: isTypeOnly,
113397                 isJsxIdentifierExpected: isJsxIdentifierExpected,
113398             };
113399             function isTagWithTypeExpression(tag) {
113400                 switch (tag.kind) {
113401                     case 317 /* JSDocParameterTag */:
113402                     case 323 /* JSDocPropertyTag */:
113403                     case 318 /* JSDocReturnTag */:
113404                     case 320 /* JSDocTypeTag */:
113405                     case 322 /* JSDocTypedefTag */:
113406                         return true;
113407                     default:
113408                         return false;
113409                 }
113410             }
113411             function getTypeScriptMemberSymbols() {
113412                 // Right of dot member completion list
113413                 completionKind = 2 /* PropertyAccess */;
113414                 // Since this is qualified name check it's a type node location
113415                 var isImportType = ts.isLiteralImportTypeNode(node);
113416                 var isTypeLocation = insideJsDocTagTypeExpression
113417                     || (isImportType && !node.isTypeOf)
113418                     || ts.isPartOfTypeNode(node.parent)
113419                     || ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker);
113420                 var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node);
113421                 if (ts.isEntityName(node) || isImportType) {
113422                     var isNamespaceName = ts.isModuleDeclaration(node.parent);
113423                     if (isNamespaceName)
113424                         isNewIdentifierLocation = true;
113425                     var symbol = typeChecker.getSymbolAtLocation(node);
113426                     if (symbol) {
113427                         symbol = ts.skipAlias(symbol, typeChecker);
113428                         if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) {
113429                             // Extract module or enum members
113430                             var exportedSymbols = typeChecker.getExportsOfModule(symbol);
113431                             ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined");
113432                             var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); };
113433                             var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); };
113434                             var isValidAccess = isNamespaceName
113435                                 // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion.
113436                                 ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); }
113437                                 : isRhsOfImportDeclaration ?
113438                                     // Any kind is allowed when dotting off namespace in internal import equals declaration
113439                                     function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } :
113440                                     isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1;
113441                             for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) {
113442                                 var exportedSymbol = exportedSymbols_1[_i];
113443                                 if (isValidAccess(exportedSymbol)) {
113444                                     symbols.push(exportedSymbol);
113445                                 }
113446                             }
113447                             // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
113448                             if (!isTypeLocation &&
113449                                 symbol.declarations &&
113450                                 symbol.declarations.some(function (d) { return d.kind !== 290 /* SourceFile */ && d.kind !== 249 /* ModuleDeclaration */ && d.kind !== 248 /* EnumDeclaration */; })) {
113451                                 var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType();
113452                                 var insertQuestionDot = false;
113453                                 if (type.isNullableType()) {
113454                                     var canCorrectToQuestionDot = isRightOfDot &&
113455                                         !isRightOfQuestionDot &&
113456                                         preferences.includeAutomaticOptionalChainCompletions !== false;
113457                                     if (canCorrectToQuestionDot || isRightOfQuestionDot) {
113458                                         type = type.getNonNullableType();
113459                                         if (canCorrectToQuestionDot) {
113460                                             insertQuestionDot = true;
113461                                         }
113462                                     }
113463                                 }
113464                                 addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
113465                             }
113466                             return;
113467                         }
113468                     }
113469                 }
113470                 if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) {
113471                     var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta";
113472                     symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion)));
113473                     return;
113474                 }
113475                 if (!isTypeLocation) {
113476                     var type = typeChecker.getTypeAtLocation(node).getNonOptionalType();
113477                     var insertQuestionDot = false;
113478                     if (type.isNullableType()) {
113479                         var canCorrectToQuestionDot = isRightOfDot &&
113480                             !isRightOfQuestionDot &&
113481                             preferences.includeAutomaticOptionalChainCompletions !== false;
113482                         if (canCorrectToQuestionDot || isRightOfQuestionDot) {
113483                             type = type.getNonNullableType();
113484                             if (canCorrectToQuestionDot) {
113485                                 insertQuestionDot = true;
113486                             }
113487                         }
113488                     }
113489                     addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot);
113490                 }
113491             }
113492             function addTypeProperties(type, insertAwait, insertQuestionDot) {
113493                 isNewIdentifierLocation = !!type.getStringIndexType();
113494                 if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) {
113495                     isNewIdentifierLocation = true;
113496                 }
113497                 var propertyAccess = node.kind === 188 /* ImportType */ ? node : node.parent;
113498                 if (isUncheckedFile) {
113499                     // In javascript files, for union types, we don't just get the members that
113500                     // the individual types have in common, we also include all the members that
113501                     // each individual type has. This is because we're going to add all identifiers
113502                     // anyways. So we might as well elevate the members that were at least part
113503                     // of the individual types to a higher status since we know what they are.
113504                     symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker));
113505                 }
113506                 else {
113507                     for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) {
113508                         var symbol = _a[_i];
113509                         if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
113510                             addPropertySymbol(symbol, /*insertAwait*/ false, insertQuestionDot);
113511                         }
113512                     }
113513                 }
113514                 if (insertAwait && preferences.includeCompletionsWithInsertText) {
113515                     var promiseType = typeChecker.getPromisedTypeOfPromise(type);
113516                     if (promiseType) {
113517                         for (var _b = 0, _c = promiseType.getApparentProperties(); _b < _c.length; _b++) {
113518                             var symbol = _c[_b];
113519                             if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) {
113520                                 addPropertySymbol(symbol, /* insertAwait */ true, insertQuestionDot);
113521                             }
113522                         }
113523                     }
113524                 }
113525             }
113526             function addPropertySymbol(symbol, insertAwait, insertQuestionDot) {
113527                 // For a computed property with an accessible name like `Symbol.iterator`,
113528                 // we'll add a completion for the *name* `Symbol` instead of for the property.
113529                 // If this is e.g. [Symbol.iterator], add a completion for `Symbol`.
113530                 var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); });
113531                 if (computedPropertyName) {
113532                     var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`.
113533                     var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
113534                     // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`.
113535                     var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
113536                     if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) {
113537                         symbols.push(firstAccessibleSymbol);
113538                         var moduleSymbol = firstAccessibleSymbol.parent;
113539                         symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] =
113540                             !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)
113541                                 ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }
113542                                 : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false };
113543                     }
113544                     else if (preferences.includeCompletionsWithInsertText) {
113545                         addSymbolOriginInfo(symbol);
113546                         symbols.push(symbol);
113547                     }
113548                 }
113549                 else {
113550                     addSymbolOriginInfo(symbol);
113551                     symbols.push(symbol);
113552                 }
113553                 function addSymbolOriginInfo(symbol) {
113554                     if (preferences.includeCompletionsWithInsertText) {
113555                         if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) {
113556                             symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) };
113557                         }
113558                         else if (insertQuestionDot) {
113559                             symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ };
113560                         }
113561                     }
113562                 }
113563                 function getNullableSymbolOriginInfoKind(kind) {
113564                     return insertQuestionDot ? kind | 16 /* Nullable */ : kind;
113565                 }
113566             }
113567             /** Given 'a.b.c', returns 'a'. */
113568             function getLeftMostName(e) {
113569                 return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined;
113570             }
113571             function tryGetGlobalSymbols() {
113572                 var result = tryGetObjectLikeCompletionSymbols()
113573                     || tryGetImportOrExportClauseCompletionSymbols()
113574                     || tryGetLocalNamedExportCompletionSymbols()
113575                     || tryGetConstructorCompletion()
113576                     || tryGetClassLikeCompletionSymbols()
113577                     || tryGetJsxCompletionSymbols()
113578                     || (getGlobalCompletions(), 1 /* Success */);
113579                 return result === 1 /* Success */;
113580             }
113581             function tryGetConstructorCompletion() {
113582                 if (!tryGetConstructorLikeCompletionContainer(contextToken))
113583                     return 0 /* Continue */;
113584                 // no members, only keywords
113585                 completionKind = 5 /* None */;
113586                 // Declaring new property/method/accessor
113587                 isNewIdentifierLocation = true;
113588                 // Has keywords for constructor parameter
113589                 keywordFilters = 4 /* ConstructorParameterKeywords */;
113590                 return 1 /* Success */;
113591             }
113592             function tryGetJsxCompletionSymbols() {
113593                 var jsxContainer = tryGetContainingJsxElement(contextToken);
113594                 // Cursor is inside a JSX self-closing element or opening element
113595                 var attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes);
113596                 if (!attrsType)
113597                     return 0 /* Continue */;
113598                 var completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */);
113599                 symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties);
113600                 setSortTextToOptionalMember();
113601                 completionKind = 3 /* MemberLike */;
113602                 isNewIdentifierLocation = false;
113603                 return 1 /* Success */;
113604             }
113605             function getGlobalCompletions() {
113606                 keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */;
113607                 // Get all entities in the current scope.
113608                 completionKind = 1 /* Global */;
113609                 isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
113610                 if (previousToken !== contextToken) {
113611                     ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
113612                 }
113613                 // We need to find the node that will give us an appropriate scope to begin
113614                 // aggregating completion candidates. This is achieved in 'getScopeNode'
113615                 // by finding the first node that encompasses a position, accounting for whether a node
113616                 // is "complete" to decide whether a position belongs to the node.
113617                 //
113618                 // However, at the end of an identifier, we are interested in the scope of the identifier
113619                 // itself, but fall outside of the identifier. For instance:
113620                 //
113621                 //      xyz => x$
113622                 //
113623                 // the cursor is outside of both the 'x' and the arrow function 'xyz => x',
113624                 // so 'xyz' is not returned in our results.
113625                 //
113626                 // We define 'adjustedPosition' so that we may appropriately account for
113627                 // being at the end of an identifier. The intention is that if requesting completion
113628                 // at the end of an identifier, it should be effectively equivalent to requesting completion
113629                 // anywhere inside/at the beginning of the identifier. So in the previous case, the
113630                 // 'adjustedPosition' will work as if requesting completion in the following:
113631                 //
113632                 //      xyz => $x
113633                 //
113634                 // If previousToken !== contextToken, then
113635                 //   - 'contextToken' was adjusted to the token prior to 'previousToken'
113636                 //      because we were at the end of an identifier.
113637                 //   - 'previousToken' is defined.
113638                 var adjustedPosition = previousToken !== contextToken ?
113639                     previousToken.getStart() :
113640                     position;
113641                 var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
113642                 isInSnippetScope = isSnippetScope(scopeNode);
113643                 var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
113644                 symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings);
113645                 ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined");
113646                 for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
113647                     var symbol = symbols_2[_i];
113648                     if (!typeChecker.isArgumentsSymbol(symbol) &&
113649                         !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) {
113650                         symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
113651                     }
113652                 }
113653                 // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
113654                 if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) {
113655                     var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
113656                     if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) {
113657                         for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) {
113658                             var symbol = _b[_a];
113659                             symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ };
113660                             symbols.push(symbol);
113661                             symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers;
113662                         }
113663                     }
113664                 }
113665                 if (shouldOfferImportCompletions()) {
113666                     var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : "";
113667                     var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host);
113668                     if (!detailsEntryId && importSuggestionsCache) {
113669                         importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion());
113670                     }
113671                     autoImportSuggestions.forEach(function (_a) {
113672                         var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin;
113673                         if (detailsEntryId) {
113674                             if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) {
113675                                 return;
113676                             }
113677                         }
113678                         else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) {
113679                             return;
113680                         }
113681                         var symbolId = ts.getSymbolId(symbol);
113682                         symbols.push(symbol);
113683                         symbolToOriginInfoMap[symbolId] = origin;
113684                         symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions;
113685                     });
113686                 }
113687                 filterGlobalCompletion(symbols);
113688             }
113689             function shouldOfferImportCompletions() {
113690                 // If not already a module, must have modules enabled.
113691                 if (!preferences.includeCompletionsForModuleExports)
113692                     return false;
113693                 // If already using ES6 modules, OK to continue using them.
113694                 if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator)
113695                     return true;
113696                 // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK.
113697                 if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))
113698                     return true;
113699                 // If some file is using ES6 modules, assume that it's OK to add more.
113700                 return ts.programContainsModules(program);
113701             }
113702             function isSnippetScope(scopeNode) {
113703                 switch (scopeNode.kind) {
113704                     case 290 /* SourceFile */:
113705                     case 211 /* TemplateExpression */:
113706                     case 276 /* JsxExpression */:
113707                     case 223 /* Block */:
113708                         return true;
113709                     default:
113710                         return ts.isStatement(scopeNode);
113711                 }
113712             }
113713             function filterGlobalCompletion(symbols) {
113714                 var isTypeOnly = isTypeOnlyCompletion();
113715                 if (isTypeOnly) {
113716                     keywordFilters = isTypeAssertion()
113717                         ? 6 /* TypeAssertionKeywords */
113718                         : 7 /* TypeKeywords */;
113719                 }
113720                 ts.filterMutate(symbols, function (symbol) {
113721                     if (!ts.isSourceFile(location)) {
113722                         // export = /**/ here we want to get all meanings, so any symbol is ok
113723                         if (ts.isExportAssignment(location.parent)) {
113724                             return true;
113725                         }
113726                         symbol = ts.skipAlias(symbol, typeChecker);
113727                         // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace)
113728                         if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) {
113729                             return !!(symbol.flags & 1920 /* Namespace */);
113730                         }
113731                         if (isTypeOnly) {
113732                             // It's a type, but you can reach it by namespace.type as well
113733                             return symbolCanBeReferencedAtTypeLocation(symbol);
113734                         }
113735                     }
113736                     // expressions are value space (which includes the value namespaces)
113737                     return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */);
113738                 });
113739             }
113740             function isTypeAssertion() {
113741                 return ts.isAssertionExpression(contextToken.parent);
113742             }
113743             function isTypeOnlyCompletion() {
113744                 return insideJsDocTagTypeExpression
113745                     || !isContextTokenValueLocation(contextToken) &&
113746                         (ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)
113747                             || ts.isPartOfTypeNode(location)
113748                             || isContextTokenTypeLocation(contextToken));
113749             }
113750             function isContextTokenValueLocation(contextToken) {
113751                 return contextToken &&
113752                     contextToken.kind === 108 /* TypeOfKeyword */ &&
113753                     (contextToken.parent.kind === 172 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent));
113754             }
113755             function isContextTokenTypeLocation(contextToken) {
113756                 if (contextToken) {
113757                     var parentKind = contextToken.parent.kind;
113758                     switch (contextToken.kind) {
113759                         case 58 /* ColonToken */:
113760                             return parentKind === 159 /* PropertyDeclaration */ ||
113761                                 parentKind === 158 /* PropertySignature */ ||
113762                                 parentKind === 156 /* Parameter */ ||
113763                                 parentKind === 242 /* VariableDeclaration */ ||
113764                                 ts.isFunctionLikeKind(parentKind);
113765                         case 62 /* EqualsToken */:
113766                             return parentKind === 247 /* TypeAliasDeclaration */;
113767                         case 123 /* AsKeyword */:
113768                             return parentKind === 217 /* AsExpression */;
113769                         case 29 /* LessThanToken */:
113770                             return parentKind === 169 /* TypeReference */ ||
113771                                 parentKind === 199 /* TypeAssertionExpression */;
113772                         case 90 /* ExtendsKeyword */:
113773                             return parentKind === 155 /* TypeParameter */;
113774                     }
113775                 }
113776                 return false;
113777             }
113778             /** True if symbol is a type or a module containing at least one type. */
113779             function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) {
113780                 if (seenModules === void 0) { seenModules = ts.createMap(); }
113781                 var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker);
113782                 return !!(sym.flags & 788968 /* Type */) ||
113783                     !!(sym.flags & 1536 /* Module */) &&
113784                         ts.addToSeen(seenModules, ts.getSymbolId(sym)) &&
113785                         typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); });
113786             }
113787             /**
113788              * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates"
113789              * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but
113790              * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out,
113791              * if and only if the the first can be imported (it may be excluded due to package.json filtering in
113792              * `codefix.forEachExternalModuleToImportFrom`).
113793              *
113794              * Example. Imagine a chain of node_modules re-exporting one original symbol:
113795              *
113796              * ```js
113797              *  node_modules/x/index.js         node_modules/y/index.js           node_modules/z/index.js
113798              * +-----------------------+      +--------------------------+      +--------------------------+
113799              * |                       |      |                          |      |                          |
113800              * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; |
113801              * |                       |      |                          |      |                          |
113802              * +-----------------------+      +--------------------------+      +--------------------------+
113803              * ```
113804              *
113805              * Also imagine three buckets, which we’ll reference soon:
113806              *
113807              * ```md
113808              * |                  |      |                      |      |                   |
113809              * |   **Bucket A**   |      |    **Bucket B**      |      |    **Bucket C**   |
113810              * |    Symbols to    |      | Aliases to symbols   |      | Symbols to return |
113811              * |    definitely    |      | in Buckets A or C    |      | if nothing better |
113812              * |      return      |      | (don’t return these) |      |    comes along    |
113813              * |__________________|      |______________________|      |___________________|
113814              * ```
113815              *
113816              * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it
113817              * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not
113818              * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we
113819              * may not be sure whether or not it should go in the list. So, we’ll take the following steps:
113820              *
113821              * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is
113822              *    already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B
113823              *    (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C.
113824              * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'.
113825              *    At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z'
113826              *    should never be returned in the final list, so put it in Bucket B.
113827              * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so
113828              *    we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out.
113829              *    Put this symbol in Bucket A.
113830              * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t
113831              *    occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move
113832              *    everything from Bucket C to Bucket A.
113833              */
113834             function getSymbolsFromOtherSourceFileExports(target, host) {
113835                 var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined);
113836                 if (cached) {
113837                     log("getSymbolsFromOtherSourceFileExports: Using cached list");
113838                     return cached;
113839                 }
113840                 var startTime = ts.timestamp();
113841                 log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : ""));
113842                 var seenResolvedModules = ts.createMap();
113843                 var seenExports = ts.createMap();
113844                 /** Bucket B */
113845                 var aliasesToAlreadyIncludedSymbols = ts.createMap();
113846                 /** Bucket C */
113847                 var aliasesToReturnIfOriginalsAreMissing = ts.createMap();
113848                 /** Bucket A */
113849                 var results = [];
113850                 /** Ids present in `results` for faster lookup */
113851                 var resultSymbolIds = ts.createMap();
113852                 ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, function (moduleSymbol) {
113853                     // Perf -- ignore other modules if this is a request for details
113854                     if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) {
113855                         return;
113856                     }
113857                     var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol);
113858                     // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one.
113859                     if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) {
113860                         return;
113861                     }
113862                     // Don't add another completion for `export =` of a symbol that's already global.
113863                     // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`.
113864                     if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) {
113865                         pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true);
113866                     }
113867                     for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) {
113868                         var symbol = _a[_i];
113869                         var symbolId = ts.getSymbolId(symbol).toString();
113870                         // `getExportsAndPropertiesOfModule` can include duplicates
113871                         if (!ts.addToSeen(seenExports, symbolId)) {
113872                             continue;
113873                         }
113874                         // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion.
113875                         if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) {
113876                             continue;
113877                         }
113878                         // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols.
113879                         var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol;
113880                         // 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).
113881                         if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) {
113882                             // Walk the export chain back one module (step 1 or 2 in diagrammed example).
113883                             // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that.
113884                             var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol);
113885                             if (!nearestExportSymbol)
113886                                 continue;
113887                             var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString();
113888                             var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId);
113889                             if (!symbolHasBeenSeen) {
113890                                 aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol });
113891                                 aliasesToAlreadyIncludedSymbols.set(symbolId, true);
113892                             }
113893                             else {
113894                                 // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here
113895                                 // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id.
113896                                 ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId);
113897                             }
113898                         }
113899                         else {
113900                             // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example)
113901                             aliasesToReturnIfOriginalsAreMissing.delete(symbolId);
113902                             pushSymbol(symbol, moduleSymbol);
113903                         }
113904                     }
113905                 });
113906                 // By this point, any potential duplicates that were actually duplicates have been
113907                 // removed, so the rest need to be added. (Step 4 in diagrammed example)
113908                 aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) {
113909                     var alias = _a.alias, moduleSymbol = _a.moduleSymbol;
113910                     return pushSymbol(alias, moduleSymbol);
113911                 });
113912                 log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime));
113913                 return results;
113914                 function pushSymbol(symbol, moduleSymbol, skipFilter) {
113915                     if (skipFilter === void 0) { skipFilter = false; }
113916                     var isDefaultExport = symbol.escapedName === "default" /* Default */;
113917                     if (isDefaultExport) {
113918                         symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol;
113919                     }
113920                     if (typeChecker.isUndefinedSymbol(symbol)) {
113921                         return;
113922                     }
113923                     ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol));
113924                     var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport };
113925                     results.push({
113926                         symbol: symbol,
113927                         symbolName: ts.getNameForExportedSymbol(symbol, target),
113928                         origin: origin,
113929                         skipFilter: skipFilter,
113930                     });
113931                 }
113932             }
113933             function getNearestExportSymbol(fromSymbol) {
113934                 return findAlias(typeChecker, fromSymbol, function (alias) {
113935                     return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; });
113936                 });
113937             }
113938             /**
113939              * True if you could remove some characters in `a` to get `b`.
113940              * E.g., true for "abcdef" and "bdf".
113941              * But not true for "abcdef" and "dbf".
113942              */
113943             function stringContainsCharactersInOrder(str, characters) {
113944                 if (characters.length === 0) {
113945                     return true;
113946                 }
113947                 var characterIndex = 0;
113948                 for (var strIndex = 0; strIndex < str.length; strIndex++) {
113949                     if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) {
113950                         characterIndex++;
113951                         if (characterIndex === characters.length) {
113952                             return true;
113953                         }
113954                     }
113955                 }
113956                 // Did not find all characters
113957                 return false;
113958             }
113959             /**
113960              * Finds the first node that "embraces" the position, so that one may
113961              * accurately aggregate locals from the closest containing scope.
113962              */
113963             function getScopeNode(initialToken, position, sourceFile) {
113964                 var scope = initialToken;
113965                 while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {
113966                     scope = scope.parent;
113967                 }
113968                 return scope;
113969             }
113970             function isCompletionListBlocker(contextToken) {
113971                 var start = ts.timestamp();
113972                 var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
113973                     isSolelyIdentifierDefinitionLocation(contextToken) ||
113974                     isDotOfNumericLiteral(contextToken) ||
113975                     isInJsxText(contextToken);
113976                 log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start));
113977                 return result;
113978             }
113979             function isInJsxText(contextToken) {
113980                 if (contextToken.kind === 11 /* JsxText */) {
113981                     return true;
113982                 }
113983                 if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) {
113984                     if (contextToken.parent.kind === 268 /* JsxOpeningElement */) {
113985                         // Two possibilities:
113986                         //   1. <div>/**/
113987                         //      - contextToken: GreaterThanToken (before cursor)
113988                         //      - location: JSXElement
113989                         //      - different parents (JSXOpeningElement, JSXElement)
113990                         //   2. <Component<string> /**/>
113991                         //      - contextToken: GreaterThanToken (before cursor)
113992                         //      - location: GreaterThanToken (after cursor)
113993                         //      - same parent (JSXOpeningElement)
113994                         return location.parent.kind !== 268 /* JsxOpeningElement */;
113995                     }
113996                     if (contextToken.parent.kind === 269 /* JsxClosingElement */ || contextToken.parent.kind === 267 /* JsxSelfClosingElement */) {
113997                         return !!contextToken.parent.parent && contextToken.parent.parent.kind === 266 /* JsxElement */;
113998                     }
113999                 }
114000                 return false;
114001             }
114002             function isNewIdentifierDefinitionLocation(previousToken) {
114003                 if (previousToken) {
114004                     var containingNodeKind = previousToken.parent.kind;
114005                     // Previous token may have been a keyword that was converted to an identifier.
114006                     switch (keywordForNode(previousToken)) {
114007                         case 27 /* CommaToken */:
114008                             return containingNodeKind === 196 /* CallExpression */ // func( a, |
114009                                 || containingNodeKind === 162 /* Constructor */ // constructor( a, |   /* public, protected, private keywords are allowed here, so show completion */
114010                                 || containingNodeKind === 197 /* NewExpression */ // new C(a, |
114011                                 || containingNodeKind === 192 /* ArrayLiteralExpression */ // [a, |
114012                                 || containingNodeKind === 209 /* BinaryExpression */ // const x = (a, |
114013                                 || containingNodeKind === 170 /* FunctionType */; // var x: (s: string, list|
114014                         case 20 /* OpenParenToken */:
114015                             return containingNodeKind === 196 /* CallExpression */ // func( |
114016                                 || containingNodeKind === 162 /* Constructor */ // constructor( |
114017                                 || containingNodeKind === 197 /* NewExpression */ // new C(a|
114018                                 || containingNodeKind === 200 /* ParenthesizedExpression */ // const x = (a|
114019                                 || containingNodeKind === 182 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
114020                         case 22 /* OpenBracketToken */:
114021                             return containingNodeKind === 192 /* ArrayLiteralExpression */ // [ |
114022                                 || containingNodeKind === 167 /* IndexSignature */ // [ | : string ]
114023                                 || containingNodeKind === 154 /* ComputedPropertyName */; // [ |    /* this can become an index signature */
114024                         case 135 /* ModuleKeyword */: // module |
114025                         case 136 /* NamespaceKeyword */: // namespace |
114026                             return true;
114027                         case 24 /* DotToken */:
114028                             return containingNodeKind === 249 /* ModuleDeclaration */; // module A.|
114029                         case 18 /* OpenBraceToken */:
114030                             return containingNodeKind === 245 /* ClassDeclaration */; // class A{ |
114031                         case 62 /* EqualsToken */:
114032                             return containingNodeKind === 242 /* VariableDeclaration */ // const x = a|
114033                                 || containingNodeKind === 209 /* BinaryExpression */; // x = a|
114034                         case 15 /* TemplateHead */:
114035                             return containingNodeKind === 211 /* TemplateExpression */; // `aa ${|
114036                         case 16 /* TemplateMiddle */:
114037                             return containingNodeKind === 221 /* TemplateSpan */; // `aa ${10} dd ${|
114038                         case 119 /* PublicKeyword */:
114039                         case 117 /* PrivateKeyword */:
114040                         case 118 /* ProtectedKeyword */:
114041                             return containingNodeKind === 159 /* PropertyDeclaration */; // class A{ public |
114042                     }
114043                 }
114044                 return false;
114045             }
114046             function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) {
114047                 // To be "in" one of these literals, the position has to be:
114048                 //   1. entirely within the token text.
114049                 //   2. at the end position of an unterminated token.
114050                 //   3. at the end of a regular expression (due to trailing flags like '/foo/g').
114051                 return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) ||
114052                     position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken)));
114053             }
114054             /**
114055              * Aggregates relevant symbols for completion in object literals and object binding patterns.
114056              * Relevant symbols are stored in the captured 'symbols' variable.
114057              *
114058              * @returns true if 'symbols' was successfully populated; false otherwise.
114059              */
114060             function tryGetObjectLikeCompletionSymbols() {
114061                 var objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
114062                 if (!objectLikeContainer)
114063                     return 0 /* Continue */;
114064                 // We're looking up possible property names from contextual/inferred/declared type.
114065                 completionKind = 0 /* ObjectPropertyDeclaration */;
114066                 var typeMembers;
114067                 var existingMembers;
114068                 if (objectLikeContainer.kind === 193 /* ObjectLiteralExpression */) {
114069                     var instantiatedType = typeChecker.getContextualType(objectLikeContainer);
114070                     var completionsType = instantiatedType && typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */);
114071                     if (!instantiatedType || !completionsType)
114072                         return 2 /* Fail */;
114073                     isNewIdentifierLocation = ts.hasIndexSignature(instantiatedType || completionsType);
114074                     typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker);
114075                     existingMembers = objectLikeContainer.properties;
114076                 }
114077                 else {
114078                     ts.Debug.assert(objectLikeContainer.kind === 189 /* ObjectBindingPattern */);
114079                     // We are *only* completing on properties from the type being destructured.
114080                     isNewIdentifierLocation = false;
114081                     var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
114082                     if (!ts.isVariableLike(rootDeclaration))
114083                         return ts.Debug.fail("Root declaration is not variable-like.");
114084                     // We don't want to complete using the type acquired by the shape
114085                     // of the binding pattern; we are only interested in types acquired
114086                     // through type declaration or inference.
114087                     // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed -
114088                     // type of parameter will flow in from the contextual type of the function
114089                     var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 232 /* ForOfStatement */;
114090                     if (!canGetType && rootDeclaration.kind === 156 /* Parameter */) {
114091                         if (ts.isExpression(rootDeclaration.parent)) {
114092                             canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
114093                         }
114094                         else if (rootDeclaration.parent.kind === 161 /* MethodDeclaration */ || rootDeclaration.parent.kind === 164 /* SetAccessor */) {
114095                             canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
114096                         }
114097                     }
114098                     if (canGetType) {
114099                         var typeForObject_1 = typeChecker.getTypeAtLocation(objectLikeContainer);
114100                         if (!typeForObject_1)
114101                             return 2 /* Fail */;
114102                         // In a binding pattern, get only known properties (unless in the same scope).
114103                         // Everywhere else we will get all possible properties.
114104                         var containerClass_1 = ts.getContainingClass(objectLikeContainer);
114105                         typeMembers = typeChecker.getPropertiesOfType(typeForObject_1).filter(function (symbol) {
114106                             // either public
114107                             return !(ts.getDeclarationModifierFlagsFromSymbol(symbol) & 24 /* NonPublicAccessibilityModifier */)
114108                                 // or we're in it
114109                                 || containerClass_1 && ts.contains(typeForObject_1.symbol.declarations, containerClass_1);
114110                         });
114111                         existingMembers = objectLikeContainer.elements;
114112                     }
114113                 }
114114                 if (typeMembers && typeMembers.length > 0) {
114115                     // Add filtered items to the completion list
114116                     symbols = filterObjectMembersList(typeMembers, ts.Debug.checkDefined(existingMembers));
114117                 }
114118                 setSortTextToOptionalMember();
114119                 return 1 /* Success */;
114120             }
114121             /**
114122              * Aggregates relevant symbols for completion in import clauses and export clauses
114123              * whose declarations have a module specifier; for instance, symbols will be aggregated for
114124              *
114125              *      import { | } from "moduleName";
114126              *      export { a as foo, | } from "moduleName";
114127              *
114128              * but not for
114129              *
114130              *      export { | };
114131              *
114132              * Relevant symbols are stored in the captured 'symbols' variable.
114133              */
114134             function tryGetImportOrExportClauseCompletionSymbols() {
114135                 // `import { |` or `import { a as 0, | }`
114136                 var namedImportsOrExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */)
114137                     ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined;
114138                 if (!namedImportsOrExports)
114139                     return 0 /* Continue */;
114140                 // try to show exported member for imported/re-exported module
114141                 var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier;
114142                 if (!moduleSpecifier)
114143                     return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */;
114144                 var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217
114145                 if (!moduleSpecifierSymbol)
114146                     return 2 /* Fail */;
114147                 completionKind = 3 /* MemberLike */;
114148                 isNewIdentifierLocation = false;
114149                 var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
114150                 var existing = ts.arrayToSet(namedImportsOrExports.elements, function (n) { return isCurrentlyEditingNode(n) ? undefined : (n.propertyName || n.name).escapedText; });
114151                 symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); });
114152                 return 1 /* Success */;
114153             }
114154             /**
114155              * Adds local declarations for completions in named exports:
114156              *
114157              *   export { | };
114158              *
114159              * Does not check for the absence of a module specifier (`export {} from "./other"`)
114160              * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that,
114161              * preventing this function from running.
114162              */
114163             function tryGetLocalNamedExportCompletionSymbols() {
114164                 var _a;
114165                 var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */)
114166                     ? ts.tryCast(contextToken.parent, ts.isNamedExports)
114167                     : undefined;
114168                 if (!namedExports) {
114169                     return 0 /* Continue */;
114170                 }
114171                 var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration));
114172                 completionKind = 5 /* None */;
114173                 isNewIdentifierLocation = false;
114174                 (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) {
114175                     var _a, _b;
114176                     symbols.push(symbol);
114177                     if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) {
114178                         symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember;
114179                     }
114180                 });
114181                 return 1 /* Success */;
114182             }
114183             /**
114184              * Aggregates relevant symbols for completion in class declaration
114185              * Relevant symbols are stored in the captured 'symbols' variable.
114186              */
114187             function tryGetClassLikeCompletionSymbols() {
114188                 var decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position);
114189                 if (!decl)
114190                     return 0 /* Continue */;
114191                 // We're looking up possible property names from parent type.
114192                 completionKind = 3 /* MemberLike */;
114193                 // Declaring new property/method/accessor
114194                 isNewIdentifierLocation = true;
114195                 keywordFilters = contextToken.kind === 41 /* AsteriskToken */ ? 0 /* None */ :
114196                     ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */;
114197                 // If you're in an interface you don't want to repeat things from super-interface. So just stop here.
114198                 if (!ts.isClassLike(decl))
114199                     return 1 /* Success */;
114200                 var classElement = contextToken.kind === 26 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent;
114201                 var classElementModifierFlags = ts.isClassElement(classElement) ? ts.getModifierFlags(classElement) : 0 /* None */;
114202                 // If this is context token is not something we are editing now, consider if this would lead to be modifier
114203                 if (contextToken.kind === 75 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) {
114204                     switch (contextToken.getText()) {
114205                         case "private":
114206                             classElementModifierFlags = classElementModifierFlags | 8 /* Private */;
114207                             break;
114208                         case "static":
114209                             classElementModifierFlags = classElementModifierFlags | 32 /* Static */;
114210                             break;
114211                     }
114212                 }
114213                 // No member list for private methods
114214                 if (!(classElementModifierFlags & 8 /* Private */)) {
114215                     // List of property symbols of base type that are not private and already implemented
114216                     var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) {
114217                         var type = typeChecker.getTypeAtLocation(baseTypeNode);
114218                         return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type);
114219                     });
114220                     symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags);
114221                 }
114222                 return 1 /* Success */;
114223             }
114224             /**
114225              * Returns the immediate owning object literal or binding pattern of a context token,
114226              * on the condition that one exists and that the context implies completion should be given.
114227              */
114228             function tryGetObjectLikeCompletionContainer(contextToken) {
114229                 if (contextToken) {
114230                     var parent = contextToken.parent;
114231                     switch (contextToken.kind) {
114232                         case 18 /* OpenBraceToken */: // const x = { |
114233                         case 27 /* CommaToken */: // const x = { a: 0, |
114234                             if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) {
114235                                 return parent;
114236                             }
114237                             break;
114238                         case 41 /* AsteriskToken */:
114239                             return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined;
114240                         case 75 /* Identifier */:
114241                             return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent)
114242                                 ? contextToken.parent.parent : undefined;
114243                     }
114244                 }
114245                 return undefined;
114246             }
114247             function isConstructorParameterCompletion(node) {
114248                 return !!node.parent && ts.isParameter(node.parent) && ts.isConstructorDeclaration(node.parent.parent)
114249                     && (ts.isParameterPropertyModifier(node.kind) || ts.isDeclarationName(node));
114250             }
114251             /**
114252              * Returns the immediate owning class declaration of a context token,
114253              * on the condition that one exists and that the context implies completion should be given.
114254              */
114255             function tryGetConstructorLikeCompletionContainer(contextToken) {
114256                 if (contextToken) {
114257                     var parent = contextToken.parent;
114258                     switch (contextToken.kind) {
114259                         case 20 /* OpenParenToken */:
114260                         case 27 /* CommaToken */:
114261                             return ts.isConstructorDeclaration(contextToken.parent) ? contextToken.parent : undefined;
114262                         default:
114263                             if (isConstructorParameterCompletion(contextToken)) {
114264                                 return parent.parent;
114265                             }
114266                     }
114267                 }
114268                 return undefined;
114269             }
114270             function tryGetFunctionLikeBodyCompletionContainer(contextToken) {
114271                 if (contextToken) {
114272                     var prev_1;
114273                     var container = ts.findAncestor(contextToken.parent, function (node) {
114274                         if (ts.isClassLike(node)) {
114275                             return "quit";
114276                         }
114277                         if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) {
114278                             return true;
114279                         }
114280                         prev_1 = node;
114281                         return false;
114282                     });
114283                     return container && container;
114284                 }
114285             }
114286             function tryGetContainingJsxElement(contextToken) {
114287                 if (contextToken) {
114288                     var parent = contextToken.parent;
114289                     switch (contextToken.kind) {
114290                         case 31 /* GreaterThanToken */: // End of a type argument list
114291                         case 30 /* LessThanSlashToken */:
114292                         case 43 /* SlashToken */:
114293                         case 75 /* Identifier */:
114294                         case 194 /* PropertyAccessExpression */:
114295                         case 274 /* JsxAttributes */:
114296                         case 273 /* JsxAttribute */:
114297                         case 275 /* JsxSpreadAttribute */:
114298                             if (parent && (parent.kind === 267 /* JsxSelfClosingElement */ || parent.kind === 268 /* JsxOpeningElement */)) {
114299                                 if (contextToken.kind === 31 /* GreaterThanToken */) {
114300                                     var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
114301                                     if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */))
114302                                         break;
114303                                 }
114304                                 return parent;
114305                             }
114306                             else if (parent.kind === 273 /* JsxAttribute */) {
114307                                 // Currently we parse JsxOpeningLikeElement as:
114308                                 //      JsxOpeningLikeElement
114309                                 //          attributes: JsxAttributes
114310                                 //             properties: NodeArray<JsxAttributeLike>
114311                                 return parent.parent.parent;
114312                             }
114313                             break;
114314                         // The context token is the closing } or " of an attribute, which means
114315                         // its parent is a JsxExpression, whose parent is a JsxAttribute,
114316                         // whose parent is a JsxOpeningLikeElement
114317                         case 10 /* StringLiteral */:
114318                             if (parent && ((parent.kind === 273 /* JsxAttribute */) || (parent.kind === 275 /* JsxSpreadAttribute */))) {
114319                                 // Currently we parse JsxOpeningLikeElement as:
114320                                 //      JsxOpeningLikeElement
114321                                 //          attributes: JsxAttributes
114322                                 //             properties: NodeArray<JsxAttributeLike>
114323                                 return parent.parent.parent;
114324                             }
114325                             break;
114326                         case 19 /* CloseBraceToken */:
114327                             if (parent &&
114328                                 parent.kind === 276 /* JsxExpression */ &&
114329                                 parent.parent && parent.parent.kind === 273 /* JsxAttribute */) {
114330                                 // Currently we parse JsxOpeningLikeElement as:
114331                                 //      JsxOpeningLikeElement
114332                                 //          attributes: JsxAttributes
114333                                 //             properties: NodeArray<JsxAttributeLike>
114334                                 //                  each JsxAttribute can have initializer as JsxExpression
114335                                 return parent.parent.parent.parent;
114336                             }
114337                             if (parent && parent.kind === 275 /* JsxSpreadAttribute */) {
114338                                 // Currently we parse JsxOpeningLikeElement as:
114339                                 //      JsxOpeningLikeElement
114340                                 //          attributes: JsxAttributes
114341                                 //             properties: NodeArray<JsxAttributeLike>
114342                                 return parent.parent.parent;
114343                             }
114344                             break;
114345                     }
114346                 }
114347                 return undefined;
114348             }
114349             /**
114350              * @returns true if we are certain that the currently edited location must define a new location; false otherwise.
114351              */
114352             function isSolelyIdentifierDefinitionLocation(contextToken) {
114353                 var parent = contextToken.parent;
114354                 var containingNodeKind = parent.kind;
114355                 switch (contextToken.kind) {
114356                     case 27 /* CommaToken */:
114357                         return containingNodeKind === 242 /* VariableDeclaration */ ||
114358                             isVariableDeclarationListButNotTypeArgument(contextToken) ||
114359                             containingNodeKind === 225 /* VariableStatement */ ||
114360                             containingNodeKind === 248 /* EnumDeclaration */ || // enum a { foo, |
114361                             isFunctionLikeButNotConstructor(containingNodeKind) ||
114362                             containingNodeKind === 246 /* InterfaceDeclaration */ || // interface A<T, |
114363                             containingNodeKind === 190 /* ArrayBindingPattern */ || // var [x, y|
114364                             containingNodeKind === 247 /* TypeAliasDeclaration */ || // type Map, K, |
114365                             // class A<T, |
114366                             // var C = class D<T, |
114367                             (ts.isClassLike(parent) &&
114368                                 !!parent.typeParameters &&
114369                                 parent.typeParameters.end >= contextToken.pos);
114370                     case 24 /* DotToken */:
114371                         return containingNodeKind === 190 /* ArrayBindingPattern */; // var [.|
114372                     case 58 /* ColonToken */:
114373                         return containingNodeKind === 191 /* BindingElement */; // var {x :html|
114374                     case 22 /* OpenBracketToken */:
114375                         return containingNodeKind === 190 /* ArrayBindingPattern */; // var [x|
114376                     case 20 /* OpenParenToken */:
114377                         return containingNodeKind === 280 /* CatchClause */ ||
114378                             isFunctionLikeButNotConstructor(containingNodeKind);
114379                     case 18 /* OpenBraceToken */:
114380                         return containingNodeKind === 248 /* EnumDeclaration */; // enum a { |
114381                     case 29 /* LessThanToken */:
114382                         return containingNodeKind === 245 /* ClassDeclaration */ || // class A< |
114383                             containingNodeKind === 214 /* ClassExpression */ || // var C = class D< |
114384                             containingNodeKind === 246 /* InterfaceDeclaration */ || // interface A< |
114385                             containingNodeKind === 247 /* TypeAliasDeclaration */ || // type List< |
114386                             ts.isFunctionLikeKind(containingNodeKind);
114387                     case 120 /* StaticKeyword */:
114388                         return containingNodeKind === 159 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent);
114389                     case 25 /* DotDotDotToken */:
114390                         return containingNodeKind === 156 /* Parameter */ ||
114391                             (!!parent.parent && parent.parent.kind === 190 /* ArrayBindingPattern */); // var [...z|
114392                     case 119 /* PublicKeyword */:
114393                     case 117 /* PrivateKeyword */:
114394                     case 118 /* ProtectedKeyword */:
114395                         return containingNodeKind === 156 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent);
114396                     case 123 /* AsKeyword */:
114397                         return containingNodeKind === 258 /* ImportSpecifier */ ||
114398                             containingNodeKind === 263 /* ExportSpecifier */ ||
114399                             containingNodeKind === 256 /* NamespaceImport */;
114400                     case 131 /* GetKeyword */:
114401                     case 142 /* SetKeyword */:
114402                         return !isFromObjectTypeDeclaration(contextToken);
114403                     case 80 /* ClassKeyword */:
114404                     case 88 /* EnumKeyword */:
114405                     case 114 /* InterfaceKeyword */:
114406                     case 94 /* FunctionKeyword */:
114407                     case 109 /* VarKeyword */:
114408                     case 96 /* ImportKeyword */:
114409                     case 115 /* LetKeyword */:
114410                     case 81 /* ConstKeyword */:
114411                     case 145 /* TypeKeyword */: // type htm|
114412                         return true;
114413                     case 41 /* AsteriskToken */:
114414                         return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent);
114415                 }
114416                 // If the previous token is keyword correspoding to class member completion keyword
114417                 // there will be completion available here
114418                 if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) {
114419                     return false;
114420                 }
114421                 if (isConstructorParameterCompletion(contextToken)) {
114422                     // constructor parameter completion is available only if
114423                     // - its modifier of the constructor parameter or
114424                     // - its name of the parameter and not being edited
114425                     // eg. constructor(a |<- this shouldnt show completion
114426                     if (!ts.isIdentifier(contextToken) ||
114427                         ts.isParameterPropertyModifier(keywordForNode(contextToken)) ||
114428                         isCurrentlyEditingNode(contextToken)) {
114429                         return false;
114430                     }
114431                 }
114432                 // Previous token may have been a keyword that was converted to an identifier.
114433                 switch (keywordForNode(contextToken)) {
114434                     case 122 /* AbstractKeyword */:
114435                     case 80 /* ClassKeyword */:
114436                     case 81 /* ConstKeyword */:
114437                     case 130 /* DeclareKeyword */:
114438                     case 88 /* EnumKeyword */:
114439                     case 94 /* FunctionKeyword */:
114440                     case 114 /* InterfaceKeyword */:
114441                     case 115 /* LetKeyword */:
114442                     case 117 /* PrivateKeyword */:
114443                     case 118 /* ProtectedKeyword */:
114444                     case 119 /* PublicKeyword */:
114445                     case 120 /* StaticKeyword */:
114446                     case 109 /* VarKeyword */:
114447                         return true;
114448                     case 126 /* AsyncKeyword */:
114449                         return ts.isPropertyDeclaration(contextToken.parent);
114450                 }
114451                 return ts.isDeclarationName(contextToken)
114452                     && !ts.isJsxAttribute(contextToken.parent)
114453                     // 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`.
114454                     // If `contextToken !== previousToken`, this is `class C ex/**/`.
114455                     && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end));
114456             }
114457             function isFunctionLikeButNotConstructor(kind) {
114458                 return ts.isFunctionLikeKind(kind) && kind !== 162 /* Constructor */;
114459             }
114460             function isDotOfNumericLiteral(contextToken) {
114461                 if (contextToken.kind === 8 /* NumericLiteral */) {
114462                     var text = contextToken.getFullText();
114463                     return text.charAt(text.length - 1) === ".";
114464                 }
114465                 return false;
114466             }
114467             function isVariableDeclarationListButNotTypeArgument(node) {
114468                 return node.parent.kind === 243 /* VariableDeclarationList */
114469                     && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker);
114470             }
114471             /**
114472              * Filters out completion suggestions for named imports or exports.
114473              *
114474              * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
114475              *          do not occur at the current position and have not otherwise been typed.
114476              */
114477             function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
114478                 if (existingMembers.length === 0) {
114479                     return contextualMemberSymbols;
114480                 }
114481                 var membersDeclaredBySpreadAssignment = ts.createMap();
114482                 var existingMemberNames = ts.createUnderscoreEscapedMap();
114483                 for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
114484                     var m = existingMembers_1[_i];
114485                     // Ignore omitted expressions for missing members
114486                     if (m.kind !== 281 /* PropertyAssignment */ &&
114487                         m.kind !== 282 /* ShorthandPropertyAssignment */ &&
114488                         m.kind !== 191 /* BindingElement */ &&
114489                         m.kind !== 161 /* MethodDeclaration */ &&
114490                         m.kind !== 163 /* GetAccessor */ &&
114491                         m.kind !== 164 /* SetAccessor */ &&
114492                         m.kind !== 283 /* SpreadAssignment */) {
114493                         continue;
114494                     }
114495                     // If this is the current item we are editing right now, do not filter it out
114496                     if (isCurrentlyEditingNode(m)) {
114497                         continue;
114498                     }
114499                     var existingName = void 0;
114500                     if (ts.isSpreadAssignment(m)) {
114501                         setMembersDeclaredBySpreadAssignment(m, membersDeclaredBySpreadAssignment);
114502                     }
114503                     else if (ts.isBindingElement(m) && m.propertyName) {
114504                         // include only identifiers in completion list
114505                         if (m.propertyName.kind === 75 /* Identifier */) {
114506                             existingName = m.propertyName.escapedText;
114507                         }
114508                     }
114509                     else {
114510                         // TODO: Account for computed property name
114511                         // NOTE: if one only performs this step when m.name is an identifier,
114512                         // things like '__proto__' are not filtered out.
114513                         var name = ts.getNameOfDeclaration(m);
114514                         existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
114515                     }
114516                     existingMemberNames.set(existingName, true); // TODO: GH#18217
114517                 }
114518                 var filteredSymbols = contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); });
114519                 setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
114520                 return filteredSymbols;
114521             }
114522             function setMembersDeclaredBySpreadAssignment(declaration, membersDeclaredBySpreadAssignment) {
114523                 var expression = declaration.expression;
114524                 var symbol = typeChecker.getSymbolAtLocation(expression);
114525                 var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression);
114526                 var properties = type && type.properties;
114527                 if (properties) {
114528                     properties.forEach(function (property) {
114529                         membersDeclaredBySpreadAssignment.set(property.name, true);
114530                     });
114531                 }
114532             }
114533             // Set SortText to OptionalMember if it is an optional member
114534             function setSortTextToOptionalMember() {
114535                 symbols.forEach(function (m) {
114536                     if (m.flags & 16777216 /* Optional */) {
114537                         symbolToSortTextMap[ts.getSymbolId(m)] = symbolToSortTextMap[ts.getSymbolId(m)] || SortText.OptionalMember;
114538                     }
114539                 });
114540             }
114541             // Set SortText to MemberDeclaredBySpreadAssignment if it is fulfilled by spread assignment
114542             function setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, contextualMemberSymbols) {
114543                 if (membersDeclaredBySpreadAssignment.size === 0) {
114544                     return;
114545                 }
114546                 for (var _i = 0, contextualMemberSymbols_1 = contextualMemberSymbols; _i < contextualMemberSymbols_1.length; _i++) {
114547                     var contextualMemberSymbol = contextualMemberSymbols_1[_i];
114548                     if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) {
114549                         symbolToSortTextMap[ts.getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment;
114550                     }
114551                 }
114552             }
114553             /**
114554              * Filters out completion suggestions for class elements.
114555              *
114556              * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags
114557              */
114558             function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) {
114559                 var existingMemberNames = ts.createUnderscoreEscapedMap();
114560                 for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) {
114561                     var m = existingMembers_2[_i];
114562                     // Ignore omitted expressions for missing members
114563                     if (m.kind !== 159 /* PropertyDeclaration */ &&
114564                         m.kind !== 161 /* MethodDeclaration */ &&
114565                         m.kind !== 163 /* GetAccessor */ &&
114566                         m.kind !== 164 /* SetAccessor */) {
114567                         continue;
114568                     }
114569                     // If this is the current item we are editing right now, do not filter it out
114570                     if (isCurrentlyEditingNode(m)) {
114571                         continue;
114572                     }
114573                     // Dont filter member even if the name matches if it is declared private in the list
114574                     if (ts.hasModifier(m, 8 /* Private */)) {
114575                         continue;
114576                     }
114577                     // do not filter it out if the static presence doesnt match
114578                     if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) {
114579                         continue;
114580                     }
114581                     var existingName = ts.getPropertyNameForPropertyNameNode(m.name);
114582                     if (existingName) {
114583                         existingMemberNames.set(existingName, true);
114584                     }
114585                 }
114586                 return baseSymbols.filter(function (propertySymbol) {
114587                     return !existingMemberNames.has(propertySymbol.escapedName) &&
114588                         !!propertySymbol.declarations &&
114589                         !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) &&
114590                         !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration);
114591                 });
114592             }
114593             /**
114594              * Filters out completion suggestions from 'symbols' according to existing JSX attributes.
114595              *
114596              * @returns Symbols to be suggested in a JSX element, barring those whose attributes
114597              *          do not occur at the current position and have not otherwise been typed.
114598              */
114599             function filterJsxAttributes(symbols, attributes) {
114600                 var seenNames = ts.createUnderscoreEscapedMap();
114601                 var membersDeclaredBySpreadAssignment = ts.createMap();
114602                 for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
114603                     var attr = attributes_1[_i];
114604                     // If this is the current item we are editing right now, do not filter it out
114605                     if (isCurrentlyEditingNode(attr)) {
114606                         continue;
114607                     }
114608                     if (attr.kind === 273 /* JsxAttribute */) {
114609                         seenNames.set(attr.name.escapedText, true);
114610                     }
114611                     else if (ts.isJsxSpreadAttribute(attr)) {
114612                         setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment);
114613                     }
114614                 }
114615                 var filteredSymbols = symbols.filter(function (a) { return !seenNames.get(a.escapedName); });
114616                 setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols);
114617                 return filteredSymbols;
114618             }
114619             function isCurrentlyEditingNode(node) {
114620                 return node.getStart(sourceFile) <= position && position <= node.getEnd();
114621             }
114622         }
114623         function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) {
114624             var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name;
114625             if (name === undefined
114626                 // If the symbol is external module, don't show it in the completion list
114627                 // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there)
114628                 || symbol.flags & 1536 /* Module */ && ts.isSingleOrDoubleQuote(name.charCodeAt(0))
114629                 // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@"
114630                 || ts.isKnownSymbol(symbol)) {
114631                 return undefined;
114632             }
114633             var validNameResult = { name: name, needsConvertPropertyAccess: false };
114634             if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
114635                 return validNameResult;
114636             }
114637             switch (kind) {
114638                 case 3 /* MemberLike */:
114639                     return undefined;
114640                 case 0 /* ObjectPropertyDeclaration */:
114641                     // TODO: GH#18169
114642                     return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
114643                 case 2 /* PropertyAccess */:
114644                 case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name.
114645                     // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547
114646                     return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true };
114647                 case 5 /* None */:
114648                 case 4 /* String */:
114649                     return validNameResult;
114650                 default:
114651                     ts.Debug.assertNever(kind);
114652             }
114653         }
114654         // A cache of completion entries for keywords, these do not change between sessions
114655         var _keywordCompletions = [];
114656         var allKeywordsCompletions = ts.memoize(function () {
114657             var res = [];
114658             for (var i = 77 /* FirstKeyword */; i <= 152 /* LastKeyword */; i++) {
114659                 res.push({
114660                     name: ts.tokenToString(i),
114661                     kind: "keyword" /* keyword */,
114662                     kindModifiers: "" /* none */,
114663                     sortText: SortText.GlobalsOrKeywords
114664                 });
114665             }
114666             return res;
114667         });
114668         function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
114669             if (!filterOutTsOnlyKeywords)
114670                 return getTypescriptKeywordCompletions(keywordFilter);
114671             var index = keywordFilter + 7 /* Last */ + 1;
114672             return _keywordCompletions[index] ||
114673                 (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
114674                     .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
114675         }
114676         function getTypescriptKeywordCompletions(keywordFilter) {
114677             return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
114678                 var kind = ts.stringToToken(entry.name);
114679                 switch (keywordFilter) {
114680                     case 0 /* None */:
114681                         return false;
114682                     case 1 /* All */:
114683                         return isFunctionLikeBodyKeyword(kind)
114684                             || kind === 130 /* DeclareKeyword */
114685                             || kind === 135 /* ModuleKeyword */
114686                             || kind === 145 /* TypeKeyword */
114687                             || kind === 136 /* NamespaceKeyword */
114688                             || kind === 123 /* AsKeyword */
114689                             || ts.isTypeKeyword(kind) && kind !== 146 /* UndefinedKeyword */;
114690                     case 5 /* FunctionLikeBodyKeywords */:
114691                         return isFunctionLikeBodyKeyword(kind);
114692                     case 2 /* ClassElementKeywords */:
114693                         return isClassMemberCompletionKeyword(kind);
114694                     case 3 /* InterfaceElementKeywords */:
114695                         return isInterfaceOrTypeLiteralCompletionKeyword(kind);
114696                     case 4 /* ConstructorParameterKeywords */:
114697                         return ts.isParameterPropertyModifier(kind);
114698                     case 6 /* TypeAssertionKeywords */:
114699                         return ts.isTypeKeyword(kind) || kind === 81 /* ConstKeyword */;
114700                     case 7 /* TypeKeywords */:
114701                         return ts.isTypeKeyword(kind);
114702                     default:
114703                         return ts.Debug.assertNever(keywordFilter);
114704                 }
114705             }));
114706         }
114707         function isTypeScriptOnlyKeyword(kind) {
114708             switch (kind) {
114709                 case 122 /* AbstractKeyword */:
114710                 case 125 /* AnyKeyword */:
114711                 case 151 /* BigIntKeyword */:
114712                 case 128 /* BooleanKeyword */:
114713                 case 130 /* DeclareKeyword */:
114714                 case 88 /* EnumKeyword */:
114715                 case 150 /* GlobalKeyword */:
114716                 case 113 /* ImplementsKeyword */:
114717                 case 132 /* InferKeyword */:
114718                 case 114 /* InterfaceKeyword */:
114719                 case 133 /* IsKeyword */:
114720                 case 134 /* KeyOfKeyword */:
114721                 case 135 /* ModuleKeyword */:
114722                 case 136 /* NamespaceKeyword */:
114723                 case 137 /* NeverKeyword */:
114724                 case 140 /* NumberKeyword */:
114725                 case 141 /* ObjectKeyword */:
114726                 case 117 /* PrivateKeyword */:
114727                 case 118 /* ProtectedKeyword */:
114728                 case 119 /* PublicKeyword */:
114729                 case 138 /* ReadonlyKeyword */:
114730                 case 143 /* StringKeyword */:
114731                 case 144 /* SymbolKeyword */:
114732                 case 145 /* TypeKeyword */:
114733                 case 147 /* UniqueKeyword */:
114734                 case 148 /* UnknownKeyword */:
114735                     return true;
114736                 default:
114737                     return false;
114738             }
114739         }
114740         function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
114741             return kind === 138 /* ReadonlyKeyword */;
114742         }
114743         function isClassMemberCompletionKeyword(kind) {
114744             switch (kind) {
114745                 case 122 /* AbstractKeyword */:
114746                 case 129 /* ConstructorKeyword */:
114747                 case 131 /* GetKeyword */:
114748                 case 142 /* SetKeyword */:
114749                 case 126 /* AsyncKeyword */:
114750                 case 130 /* DeclareKeyword */:
114751                     return true;
114752                 default:
114753                     return ts.isClassMemberModifier(kind);
114754             }
114755         }
114756         function isFunctionLikeBodyKeyword(kind) {
114757             return kind === 126 /* AsyncKeyword */
114758                 || kind === 127 /* AwaitKeyword */
114759                 || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
114760         }
114761         function keywordForNode(node) {
114762             return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind;
114763         }
114764         /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */
114765         function getJsDocTagAtPosition(node, position) {
114766             var jsdoc = ts.findAncestor(node, ts.isJSDoc);
114767             return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined);
114768         }
114769         function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) {
114770             var hasCompletionsType = completionsType && completionsType !== contextualType;
114771             var type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */)
114772                 ? checker.getUnionType([contextualType, completionsType])
114773                 : contextualType;
114774             var properties = type.isUnion()
114775                 ? checker.getAllPossiblePropertiesOfTypes(type.types.filter(function (memberType) {
114776                     // 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.
114777                     return !(memberType.flags & 131068 /* Primitive */ ||
114778                         checker.isArrayLikeType(memberType) ||
114779                         ts.typeHasCallOrConstructSignatures(memberType, checker) ||
114780                         checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj));
114781                 }))
114782                 : type.getApparentProperties();
114783             return hasCompletionsType ? properties.filter(hasDeclarationOtherThanSelf) : properties;
114784             // Filter out members whose only declaration is the object literal itself to avoid
114785             // self-fulfilling completions like:
114786             //
114787             // function f<T>(x: T) {}
114788             // f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself
114789             function hasDeclarationOtherThanSelf(member) {
114790                 return ts.some(member.declarations, function (decl) { return decl.parent !== obj; });
114791             }
114792         }
114793         /**
114794          * Gets all properties on a type, but if that type is a union of several types,
114795          * excludes array-like types or callable/constructable types.
114796          */
114797         function getPropertiesForCompletion(type, checker) {
114798             return type.isUnion()
114799                 ? ts.Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
114800                 : ts.Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
114801         }
114802         /**
114803          * Returns the immediate owning class declaration of a context token,
114804          * on the condition that one exists and that the context implies completion should be given.
114805          */
114806         function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) {
114807             // class c { method() { } | method2() { } }
114808             switch (location.kind) {
114809                 case 324 /* SyntaxList */:
114810                     return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
114811                 case 1 /* EndOfFileToken */:
114812                     var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
114813                     if (cls && !ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile)) {
114814                         return cls;
114815                     }
114816                     break;
114817                 case 75 /* Identifier */: {
114818                     // class c { public prop = c| }
114819                     if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) {
114820                         return undefined;
114821                     }
114822                     // class c extends React.Component { a: () => 1\n compon| }
114823                     if (isFromObjectTypeDeclaration(location)) {
114824                         return ts.findAncestor(location, ts.isObjectTypeDeclaration);
114825                     }
114826                 }
114827             }
114828             if (!contextToken)
114829                 return undefined;
114830             switch (contextToken.kind) {
114831                 case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ }
114832                     return undefined;
114833                 case 26 /* SemicolonToken */: // class c {getValue(): number; | }
114834                 case 19 /* CloseBraceToken */: // class c { method() { } | }
114835                     // class c { method() { } b| }
114836                     return isFromObjectTypeDeclaration(location) && location.parent.name === location
114837                         ? location.parent.parent
114838                         : ts.tryCast(location, ts.isObjectTypeDeclaration);
114839                 case 18 /* OpenBraceToken */: // class c { |
114840                 case 27 /* CommaToken */: // class c {getValue(): number, | }
114841                     return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration);
114842                 default:
114843                     if (!isFromObjectTypeDeclaration(contextToken)) {
114844                         // class c extends React.Component { a: () => 1\n| }
114845                         if (ts.getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== ts.getLineAndCharacterOfPosition(sourceFile, position).line && ts.isObjectTypeDeclaration(location)) {
114846                             return location;
114847                         }
114848                         return undefined;
114849                     }
114850                     var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword;
114851                     return (isValidKeyword(contextToken.kind) || contextToken.kind === 41 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217
114852                         ? contextToken.parent.parent : undefined;
114853             }
114854         }
114855         // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes
114856         function isFromObjectTypeDeclaration(node) {
114857             return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent);
114858         }
114859         function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
114860             switch (triggerCharacter) {
114861                 case ".":
114862                 case "@":
114863                     return true;
114864                 case '"':
114865                 case "'":
114866                 case "`":
114867                     // Only automatically bring up completions if this is an opening quote.
114868                     return !!contextToken && ts.isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
114869                 case "#":
114870                     return !!contextToken && ts.isPrivateIdentifier(contextToken) && !!ts.getContainingClass(contextToken);
114871                 case "<":
114872                     // Opening JSX tag
114873                     return !!contextToken && contextToken.kind === 29 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
114874                 case "/":
114875                     return !!contextToken && (ts.isStringLiteralLike(contextToken)
114876                         ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
114877                         : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent));
114878                 default:
114879                     return ts.Debug.assertNever(triggerCharacter);
114880             }
114881         }
114882         function binaryExpressionMayBeOpenTag(_a) {
114883             var left = _a.left;
114884             return ts.nodeIsMissing(left);
114885         }
114886         function findAlias(typeChecker, symbol, predicate) {
114887             var currentAlias = symbol;
114888             while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) {
114889                 if (predicate(currentAlias)) {
114890                     return currentAlias;
114891                 }
114892             }
114893         }
114894         /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */
114895         function isProbablyGlobalType(type, sourceFile, checker) {
114896             // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in
114897             // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists.
114898             var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false);
114899             if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) {
114900                 return true;
114901             }
114902             var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false);
114903             if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) {
114904                 return true;
114905             }
114906             var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false);
114907             if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) {
114908                 return true;
114909             }
114910             return false;
114911         }
114912     })(Completions = ts.Completions || (ts.Completions = {}));
114913 })(ts || (ts = {}));
114914 var ts;
114915 (function (ts) {
114916     /* @internal */
114917     var DocumentHighlights;
114918     (function (DocumentHighlights) {
114919         function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) {
114920             var node = ts.getTouchingPropertyName(sourceFile, position);
114921             if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) {
114922                 // For a JSX element, just highlight the matching tag, not all references.
114923                 var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
114924                 var highlightSpans = [openingElement, closingElement].map(function (_a) {
114925                     var tagName = _a.tagName;
114926                     return getHighlightSpanForNode(tagName, sourceFile);
114927                 });
114928                 return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
114929             }
114930             return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
114931         }
114932         DocumentHighlights.getDocumentHighlights = getDocumentHighlights;
114933         function getHighlightSpanForNode(node, sourceFile) {
114934             return {
114935                 fileName: sourceFile.fileName,
114936                 textSpan: ts.createTextSpanFromNode(node, sourceFile),
114937                 kind: "none" /* none */
114938             };
114939         }
114940         function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) {
114941             var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; });
114942             var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet);
114943             if (!referenceEntries)
114944                 return undefined;
114945             var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; });
114946             return ts.arrayFrom(map.entries(), function (_a) {
114947                 var fileName = _a[0], highlightSpans = _a[1];
114948                 if (!sourceFilesSet.has(fileName)) {
114949                     ts.Debug.assert(program.redirectTargetsMap.has(fileName));
114950                     var redirectTarget_1 = program.getSourceFile(fileName);
114951                     var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; });
114952                     fileName = redirect.fileName;
114953                     ts.Debug.assert(sourceFilesSet.has(fileName));
114954                 }
114955                 return { fileName: fileName, highlightSpans: highlightSpans };
114956             });
114957         }
114958         function getSyntacticDocumentHighlights(node, sourceFile) {
114959             var highlightSpans = getHighlightSpans(node, sourceFile);
114960             return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
114961         }
114962         function getHighlightSpans(node, sourceFile) {
114963             switch (node.kind) {
114964                 case 95 /* IfKeyword */:
114965                 case 87 /* ElseKeyword */:
114966                     return ts.isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined;
114967                 case 101 /* ReturnKeyword */:
114968                     return useParent(node.parent, ts.isReturnStatement, getReturnOccurrences);
114969                 case 105 /* ThrowKeyword */:
114970                     return useParent(node.parent, ts.isThrowStatement, getThrowOccurrences);
114971                 case 107 /* TryKeyword */:
114972                 case 79 /* CatchKeyword */:
114973                 case 92 /* FinallyKeyword */:
114974                     var tryStatement = node.kind === 79 /* CatchKeyword */ ? node.parent.parent : node.parent;
114975                     return useParent(tryStatement, ts.isTryStatement, getTryCatchFinallyOccurrences);
114976                 case 103 /* SwitchKeyword */:
114977                     return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
114978                 case 78 /* CaseKeyword */:
114979                 case 84 /* DefaultKeyword */: {
114980                     if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) {
114981                         return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences);
114982                     }
114983                     return undefined;
114984                 }
114985                 case 77 /* BreakKeyword */:
114986                 case 82 /* ContinueKeyword */:
114987                     return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
114988                 case 93 /* ForKeyword */:
114989                 case 111 /* WhileKeyword */:
114990                 case 86 /* DoKeyword */:
114991                     return useParent(node.parent, function (n) { return ts.isIterationStatement(n, /*lookInLabeledStatements*/ true); }, getLoopBreakContinueOccurrences);
114992                 case 129 /* ConstructorKeyword */:
114993                     return getFromAllDeclarations(ts.isConstructorDeclaration, [129 /* ConstructorKeyword */]);
114994                 case 131 /* GetKeyword */:
114995                 case 142 /* SetKeyword */:
114996                     return getFromAllDeclarations(ts.isAccessor, [131 /* GetKeyword */, 142 /* SetKeyword */]);
114997                 case 127 /* AwaitKeyword */:
114998                     return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
114999                 case 126 /* AsyncKeyword */:
115000                     return highlightSpans(getAsyncAndAwaitOccurrences(node));
115001                 case 121 /* YieldKeyword */:
115002                     return highlightSpans(getYieldOccurrences(node));
115003                 default:
115004                     return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
115005                         ? highlightSpans(getModifierOccurrences(node.kind, node.parent))
115006                         : undefined;
115007             }
115008             function getFromAllDeclarations(nodeTest, keywords) {
115009                 return useParent(node.parent, nodeTest, function (decl) { return ts.mapDefined(decl.symbol.declarations, function (d) {
115010                     return nodeTest(d) ? ts.find(d.getChildren(sourceFile), function (c) { return ts.contains(keywords, c.kind); }) : undefined;
115011                 }); });
115012             }
115013             function useParent(node, nodeTest, getNodes) {
115014                 return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined;
115015             }
115016             function highlightSpans(nodes) {
115017                 return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); });
115018             }
115019         }
115020         /**
115021          * Aggregates all throw-statements within this node *without* crossing
115022          * into function boundaries and try-blocks with catch-clauses.
115023          */
115024         function aggregateOwnedThrowStatements(node) {
115025             if (ts.isThrowStatement(node)) {
115026                 return [node];
115027             }
115028             else if (ts.isTryStatement(node)) {
115029                 // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context.
115030                 return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock));
115031             }
115032             // Do not cross function boundaries.
115033             return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements);
115034         }
115035         /**
115036          * For lack of a better name, this function takes a throw statement and returns the
115037          * nearest ancestor that is a try-block (whose try statement has a catch clause),
115038          * function-block, or source file.
115039          */
115040         function getThrowStatementOwner(throwStatement) {
115041             var child = throwStatement;
115042             while (child.parent) {
115043                 var parent = child.parent;
115044                 if (ts.isFunctionBlock(parent) || parent.kind === 290 /* SourceFile */) {
115045                     return parent;
115046                 }
115047                 // A throw-statement is only owned by a try-statement if the try-statement has
115048                 // a catch clause, and if the throw-statement occurs within the try block.
115049                 if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
115050                     return child;
115051                 }
115052                 child = parent;
115053             }
115054             return undefined;
115055         }
115056         function aggregateAllBreakAndContinueStatements(node) {
115057             return ts.isBreakOrContinueStatement(node) ? [node] : ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
115058         }
115059         function flatMapChildren(node, cb) {
115060             var result = [];
115061             node.forEachChild(function (child) {
115062                 var value = cb(child);
115063                 if (value !== undefined) {
115064                     result.push.apply(result, ts.toArray(value));
115065                 }
115066             });
115067             return result;
115068         }
115069         function ownsBreakOrContinueStatement(owner, statement) {
115070             var actualOwner = getBreakOrContinueOwner(statement);
115071             return !!actualOwner && actualOwner === owner;
115072         }
115073         function getBreakOrContinueOwner(statement) {
115074             return ts.findAncestor(statement, function (node) {
115075                 switch (node.kind) {
115076                     case 237 /* SwitchStatement */:
115077                         if (statement.kind === 233 /* ContinueStatement */) {
115078                             return false;
115079                         }
115080                     // falls through
115081                     case 230 /* ForStatement */:
115082                     case 231 /* ForInStatement */:
115083                     case 232 /* ForOfStatement */:
115084                     case 229 /* WhileStatement */:
115085                     case 228 /* DoStatement */:
115086                         return !statement.label || isLabeledBy(node, statement.label.escapedText);
115087                     default:
115088                         // Don't cross function boundaries.
115089                         // TODO: GH#20090
115090                         return ts.isFunctionLike(node) && "quit";
115091                 }
115092             });
115093         }
115094         function getModifierOccurrences(modifier, declaration) {
115095             return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); });
115096         }
115097         function getNodesToSearchForModifier(declaration, modifierFlag) {
115098             // Types of node whose children might have modifiers.
115099             var container = declaration.parent;
115100             switch (container.kind) {
115101                 case 250 /* ModuleBlock */:
115102                 case 290 /* SourceFile */:
115103                 case 223 /* Block */:
115104                 case 277 /* CaseClause */:
115105                 case 278 /* DefaultClause */:
115106                     // Container is either a class declaration or the declaration is a classDeclaration
115107                     if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) {
115108                         return __spreadArrays(declaration.members, [declaration]);
115109                     }
115110                     else {
115111                         return container.statements;
115112                     }
115113                 case 162 /* Constructor */:
115114                 case 161 /* MethodDeclaration */:
115115                 case 244 /* FunctionDeclaration */:
115116                     return __spreadArrays(container.parameters, (ts.isClassLike(container.parent) ? container.parent.members : []));
115117                 case 245 /* ClassDeclaration */:
115118                 case 214 /* ClassExpression */:
115119                 case 246 /* InterfaceDeclaration */:
115120                 case 173 /* TypeLiteral */:
115121                     var nodes = container.members;
115122                     // If we're an accessibility modifier, we're in an instance member and should search
115123                     // the constructor's parameter list for instance members as well.
115124                     if (modifierFlag & (28 /* AccessibilityModifier */ | 64 /* Readonly */)) {
115125                         var constructor = ts.find(container.members, ts.isConstructorDeclaration);
115126                         if (constructor) {
115127                             return __spreadArrays(nodes, constructor.parameters);
115128                         }
115129                     }
115130                     else if (modifierFlag & 128 /* Abstract */) {
115131                         return __spreadArrays(nodes, [container]);
115132                     }
115133                     return nodes;
115134                 default:
115135                     ts.Debug.assertNever(container, "Invalid container kind.");
115136             }
115137         }
115138         function pushKeywordIf(keywordList, token) {
115139             var expected = [];
115140             for (var _i = 2; _i < arguments.length; _i++) {
115141                 expected[_i - 2] = arguments[_i];
115142             }
115143             if (token && ts.contains(expected, token.kind)) {
115144                 keywordList.push(token);
115145                 return true;
115146             }
115147             return false;
115148         }
115149         function getLoopBreakContinueOccurrences(loopNode) {
115150             var keywords = [];
115151             if (pushKeywordIf(keywords, loopNode.getFirstToken(), 93 /* ForKeyword */, 111 /* WhileKeyword */, 86 /* DoKeyword */)) {
115152                 // If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
115153                 if (loopNode.kind === 228 /* DoStatement */) {
115154                     var loopTokens = loopNode.getChildren();
115155                     for (var i = loopTokens.length - 1; i >= 0; i--) {
115156                         if (pushKeywordIf(keywords, loopTokens[i], 111 /* WhileKeyword */)) {
115157                             break;
115158                         }
115159                     }
115160                 }
115161             }
115162             ts.forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), function (statement) {
115163                 if (ownsBreakOrContinueStatement(loopNode, statement)) {
115164                     pushKeywordIf(keywords, statement.getFirstToken(), 77 /* BreakKeyword */, 82 /* ContinueKeyword */);
115165                 }
115166             });
115167             return keywords;
115168         }
115169         function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
115170             var owner = getBreakOrContinueOwner(breakOrContinueStatement);
115171             if (owner) {
115172                 switch (owner.kind) {
115173                     case 230 /* ForStatement */:
115174                     case 231 /* ForInStatement */:
115175                     case 232 /* ForOfStatement */:
115176                     case 228 /* DoStatement */:
115177                     case 229 /* WhileStatement */:
115178                         return getLoopBreakContinueOccurrences(owner);
115179                     case 237 /* SwitchStatement */:
115180                         return getSwitchCaseDefaultOccurrences(owner);
115181                 }
115182             }
115183             return undefined;
115184         }
115185         function getSwitchCaseDefaultOccurrences(switchStatement) {
115186             var keywords = [];
115187             pushKeywordIf(keywords, switchStatement.getFirstToken(), 103 /* SwitchKeyword */);
115188             // Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
115189             ts.forEach(switchStatement.caseBlock.clauses, function (clause) {
115190                 pushKeywordIf(keywords, clause.getFirstToken(), 78 /* CaseKeyword */, 84 /* DefaultKeyword */);
115191                 ts.forEach(aggregateAllBreakAndContinueStatements(clause), function (statement) {
115192                     if (ownsBreakOrContinueStatement(switchStatement, statement)) {
115193                         pushKeywordIf(keywords, statement.getFirstToken(), 77 /* BreakKeyword */);
115194                     }
115195                 });
115196             });
115197             return keywords;
115198         }
115199         function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
115200             var keywords = [];
115201             pushKeywordIf(keywords, tryStatement.getFirstToken(), 107 /* TryKeyword */);
115202             if (tryStatement.catchClause) {
115203                 pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 79 /* CatchKeyword */);
115204             }
115205             if (tryStatement.finallyBlock) {
115206                 var finallyKeyword = ts.findChildOfKind(tryStatement, 92 /* FinallyKeyword */, sourceFile);
115207                 pushKeywordIf(keywords, finallyKeyword, 92 /* FinallyKeyword */);
115208             }
115209             return keywords;
115210         }
115211         function getThrowOccurrences(throwStatement, sourceFile) {
115212             var owner = getThrowStatementOwner(throwStatement);
115213             if (!owner) {
115214                 return undefined;
115215             }
115216             var keywords = [];
115217             ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) {
115218                 keywords.push(ts.findChildOfKind(throwStatement, 105 /* ThrowKeyword */, sourceFile));
115219             });
115220             // If the "owner" is a function, then we equate 'return' and 'throw' statements in their
115221             // ability to "jump out" of the function, and include occurrences for both.
115222             if (ts.isFunctionBlock(owner)) {
115223                 ts.forEachReturnStatement(owner, function (returnStatement) {
115224                     keywords.push(ts.findChildOfKind(returnStatement, 101 /* ReturnKeyword */, sourceFile));
115225                 });
115226             }
115227             return keywords;
115228         }
115229         function getReturnOccurrences(returnStatement, sourceFile) {
115230             var func = ts.getContainingFunction(returnStatement);
115231             if (!func) {
115232                 return undefined;
115233             }
115234             var keywords = [];
115235             ts.forEachReturnStatement(ts.cast(func.body, ts.isBlock), function (returnStatement) {
115236                 keywords.push(ts.findChildOfKind(returnStatement, 101 /* ReturnKeyword */, sourceFile));
115237             });
115238             // Include 'throw' statements that do not occur within a try block.
115239             ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) {
115240                 keywords.push(ts.findChildOfKind(throwStatement, 105 /* ThrowKeyword */, sourceFile));
115241             });
115242             return keywords;
115243         }
115244         function getAsyncAndAwaitOccurrences(node) {
115245             var func = ts.getContainingFunction(node);
115246             if (!func) {
115247                 return undefined;
115248             }
115249             var keywords = [];
115250             if (func.modifiers) {
115251                 func.modifiers.forEach(function (modifier) {
115252                     pushKeywordIf(keywords, modifier, 126 /* AsyncKeyword */);
115253                 });
115254             }
115255             ts.forEachChild(func, function (child) {
115256                 traverseWithoutCrossingFunction(child, function (node) {
115257                     if (ts.isAwaitExpression(node)) {
115258                         pushKeywordIf(keywords, node.getFirstToken(), 127 /* AwaitKeyword */);
115259                     }
115260                 });
115261             });
115262             return keywords;
115263         }
115264         function getYieldOccurrences(node) {
115265             var func = ts.getContainingFunction(node);
115266             if (!func) {
115267                 return undefined;
115268             }
115269             var keywords = [];
115270             ts.forEachChild(func, function (child) {
115271                 traverseWithoutCrossingFunction(child, function (node) {
115272                     if (ts.isYieldExpression(node)) {
115273                         pushKeywordIf(keywords, node.getFirstToken(), 121 /* YieldKeyword */);
115274                     }
115275                 });
115276             });
115277             return keywords;
115278         }
115279         // Do not cross function/class/interface/module/type boundaries.
115280         function traverseWithoutCrossingFunction(node, cb) {
115281             cb(node);
115282             if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
115283                 ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); });
115284             }
115285         }
115286         function getIfElseOccurrences(ifStatement, sourceFile) {
115287             var keywords = getIfElseKeywords(ifStatement, sourceFile);
115288             var result = [];
115289             // We'd like to highlight else/ifs together if they are only separated by whitespace
115290             // (i.e. the keywords are separated by no comments, no newlines).
115291             for (var i = 0; i < keywords.length; i++) {
115292                 if (keywords[i].kind === 87 /* ElseKeyword */ && i < keywords.length - 1) {
115293                     var elseKeyword = keywords[i];
115294                     var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
115295                     var shouldCombineElseAndIf = true;
115296                     // Avoid recalculating getStart() by iterating backwards.
115297                     for (var j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
115298                         if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
115299                             shouldCombineElseAndIf = false;
115300                             break;
115301                         }
115302                     }
115303                     if (shouldCombineElseAndIf) {
115304                         result.push({
115305                             fileName: sourceFile.fileName,
115306                             textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
115307                             kind: "reference" /* reference */
115308                         });
115309                         i++; // skip the next keyword
115310                         continue;
115311                     }
115312                 }
115313                 // Ordinary case: just highlight the keyword.
115314                 result.push(getHighlightSpanForNode(keywords[i], sourceFile));
115315             }
115316             return result;
115317         }
115318         function getIfElseKeywords(ifStatement, sourceFile) {
115319             var keywords = [];
115320             // Traverse upwards through all parent if-statements linked by their else-branches.
115321             while (ts.isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
115322                 ifStatement = ifStatement.parent;
115323             }
115324             // Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
115325             while (true) {
115326                 var children = ifStatement.getChildren(sourceFile);
115327                 pushKeywordIf(keywords, children[0], 95 /* IfKeyword */);
115328                 // Generally the 'else' keyword is second-to-last, so we traverse backwards.
115329                 for (var i = children.length - 1; i >= 0; i--) {
115330                     if (pushKeywordIf(keywords, children[i], 87 /* ElseKeyword */)) {
115331                         break;
115332                     }
115333                 }
115334                 if (!ifStatement.elseStatement || !ts.isIfStatement(ifStatement.elseStatement)) {
115335                     break;
115336                 }
115337                 ifStatement = ifStatement.elseStatement;
115338             }
115339             return keywords;
115340         }
115341         /**
115342          * Whether or not a 'node' is preceded by a label of the given string.
115343          * Note: 'node' cannot be a SourceFile.
115344          */
115345         function isLabeledBy(node, labelName) {
115346             return !!ts.findAncestor(node.parent, function (owner) { return !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName; });
115347         }
115348     })(DocumentHighlights = ts.DocumentHighlights || (ts.DocumentHighlights = {}));
115349 })(ts || (ts = {}));
115350 var ts;
115351 (function (ts) {
115352     function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) {
115353         return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory);
115354     }
115355     ts.createDocumentRegistry = createDocumentRegistry;
115356     /*@internal*/
115357     function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) {
115358         if (currentDirectory === void 0) { currentDirectory = ""; }
115359         // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
115360         // for those settings.
115361         var buckets = ts.createMap();
115362         var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames);
115363         function reportStats() {
115364             var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) {
115365                 var entries = buckets.get(name);
115366                 var sourceFiles = [];
115367                 entries.forEach(function (entry, name) {
115368                     sourceFiles.push({
115369                         name: name,
115370                         refCount: entry.languageServiceRefCount
115371                     });
115372                 });
115373                 sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; });
115374                 return {
115375                     bucket: name,
115376                     sourceFiles: sourceFiles
115377                 };
115378             });
115379             return JSON.stringify(bucketInfoArray, undefined, 2);
115380         }
115381         function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
115382             var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
115383             var key = getKeyForCompilationSettings(compilationSettings);
115384             return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
115385         }
115386         function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
115387             return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind);
115388         }
115389         function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) {
115390             var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
115391             var key = getKeyForCompilationSettings(compilationSettings);
115392             return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
115393         }
115394         function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) {
115395             return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind);
115396         }
115397         function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
115398             var bucket = ts.getOrUpdate(buckets, key, ts.createMap);
115399             var entry = bucket.get(path);
115400             var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */;
115401             if (!entry && externalCache) {
115402                 var sourceFile = externalCache.getDocument(key, path);
115403                 if (sourceFile) {
115404                     ts.Debug.assert(acquiring);
115405                     entry = {
115406                         sourceFile: sourceFile,
115407                         languageServiceRefCount: 0
115408                     };
115409                     bucket.set(path, entry);
115410                 }
115411             }
115412             if (!entry) {
115413                 // Have never seen this file with these settings.  Create a new source file for it.
115414                 var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
115415                 if (externalCache) {
115416                     externalCache.setDocument(key, path, sourceFile);
115417                 }
115418                 entry = {
115419                     sourceFile: sourceFile,
115420                     languageServiceRefCount: 1,
115421                 };
115422                 bucket.set(path, entry);
115423             }
115424             else {
115425                 // We have an entry for this file.  However, it may be for a different version of
115426                 // the script snapshot.  If so, update it appropriately.  Otherwise, we can just
115427                 // return it as is.
115428                 if (entry.sourceFile.version !== version) {
115429                     entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217
115430                     if (externalCache) {
115431                         externalCache.setDocument(key, path, entry.sourceFile);
115432                     }
115433                 }
115434                 // If we're acquiring, then this is the first time this LS is asking for this document.
115435                 // Increase our ref count so we know there's another LS using the document.  If we're
115436                 // not acquiring, then that means the LS is 'updating' the file instead, and that means
115437                 // it has already acquired the document previously.  As such, we do not need to increase
115438                 // the ref count.
115439                 if (acquiring) {
115440                     entry.languageServiceRefCount++;
115441                 }
115442             }
115443             ts.Debug.assert(entry.languageServiceRefCount !== 0);
115444             return entry.sourceFile;
115445         }
115446         function releaseDocument(fileName, compilationSettings) {
115447             var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
115448             var key = getKeyForCompilationSettings(compilationSettings);
115449             return releaseDocumentWithKey(path, key);
115450         }
115451         function releaseDocumentWithKey(path, key) {
115452             var bucket = ts.Debug.checkDefined(buckets.get(key));
115453             var entry = bucket.get(path);
115454             entry.languageServiceRefCount--;
115455             ts.Debug.assert(entry.languageServiceRefCount >= 0);
115456             if (entry.languageServiceRefCount === 0) {
115457                 bucket.delete(path);
115458             }
115459         }
115460         function getLanguageServiceRefCounts(path) {
115461             return ts.arrayFrom(buckets.entries(), function (_a) {
115462                 var key = _a[0], bucket = _a[1];
115463                 var entry = bucket.get(path);
115464                 return [key, entry && entry.languageServiceRefCount];
115465             });
115466         }
115467         return {
115468             acquireDocument: acquireDocument,
115469             acquireDocumentWithKey: acquireDocumentWithKey,
115470             updateDocument: updateDocument,
115471             updateDocumentWithKey: updateDocumentWithKey,
115472             releaseDocument: releaseDocument,
115473             releaseDocumentWithKey: releaseDocumentWithKey,
115474             getLanguageServiceRefCounts: getLanguageServiceRefCounts,
115475             reportStats: reportStats,
115476             getKeyForCompilationSettings: getKeyForCompilationSettings
115477         };
115478     }
115479     ts.createDocumentRegistryInternal = createDocumentRegistryInternal;
115480     function getKeyForCompilationSettings(settings) {
115481         return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|");
115482     }
115483 })(ts || (ts = {}));
115484 /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */
115485 /* @internal */
115486 var ts;
115487 (function (ts) {
115488     var FindAllReferences;
115489     (function (FindAllReferences) {
115490         /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily.  */
115491         function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) {
115492             var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
115493             return function (exportSymbol, exportInfo, isForRename) {
115494                 var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers;
115495                 return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename));
115496             };
115497         }
115498         FindAllReferences.createImportTracker = createImportTracker;
115499         var ExportKind;
115500         (function (ExportKind) {
115501             ExportKind[ExportKind["Named"] = 0] = "Named";
115502             ExportKind[ExportKind["Default"] = 1] = "Default";
115503             ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals";
115504         })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {}));
115505         var ImportExport;
115506         (function (ImportExport) {
115507             ImportExport[ImportExport["Import"] = 0] = "Import";
115508             ImportExport[ImportExport["Export"] = 1] = "Export";
115509         })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {}));
115510         /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */
115511         function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) {
115512             var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind;
115513             var markSeenDirectImport = ts.nodeSeenTracker();
115514             var markSeenIndirectUser = ts.nodeSeenTracker();
115515             var directImports = [];
115516             var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
115517             var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : [];
115518             handleDirectImports(exportingModuleSymbol);
115519             return { directImports: directImports, indirectUsers: getIndirectUsers() };
115520             function getIndirectUsers() {
115521                 if (isAvailableThroughGlobal) {
115522                     // It has `export as namespace`, so anything could potentially use it.
115523                     return sourceFiles;
115524                 }
115525                 // Module augmentations may use this module's exports without importing it.
115526                 for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) {
115527                     var decl = _a[_i];
115528                     if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) {
115529                         addIndirectUser(decl);
115530                     }
115531                 }
115532                 // 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.
115533                 return indirectUserDeclarations.map(ts.getSourceFileOfNode);
115534             }
115535             function handleDirectImports(exportingModuleSymbol) {
115536                 var theseDirectImports = getDirectImports(exportingModuleSymbol);
115537                 if (theseDirectImports) {
115538                     for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) {
115539                         var direct = theseDirectImports_1[_i];
115540                         if (!markSeenDirectImport(direct)) {
115541                             continue;
115542                         }
115543                         if (cancellationToken)
115544                             cancellationToken.throwIfCancellationRequested();
115545                         switch (direct.kind) {
115546                             case 196 /* CallExpression */:
115547                                 if (!isAvailableThroughGlobal) {
115548                                     var parent = direct.parent;
115549                                     if (exportKind === 2 /* ExportEquals */ && parent.kind === 242 /* VariableDeclaration */) {
115550                                         var name = parent.name;
115551                                         if (name.kind === 75 /* Identifier */) {
115552                                             directImports.push(name);
115553                                             break;
115554                                         }
115555                                     }
115556                                     // Don't support re-exporting 'require()' calls, so just add a single indirect user.
115557                                     addIndirectUser(direct.getSourceFile());
115558                                 }
115559                                 break;
115560                             case 75 /* Identifier */: // for 'const x = require("y");
115561                                 break; // TODO: GH#23879
115562                             case 253 /* ImportEqualsDeclaration */:
115563                                 handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false);
115564                                 break;
115565                             case 254 /* ImportDeclaration */:
115566                                 directImports.push(direct);
115567                                 var namedBindings = direct.importClause && direct.importClause.namedBindings;
115568                                 if (namedBindings && namedBindings.kind === 256 /* NamespaceImport */) {
115569                                     handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true);
115570                                 }
115571                                 else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) {
115572                                     addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports
115573                                 }
115574                                 break;
115575                             case 260 /* ExportDeclaration */:
115576                                 if (!direct.exportClause) {
115577                                     // This is `export * from "foo"`, so imports of this module may import the export too.
115578                                     handleDirectImports(getContainingModuleSymbol(direct, checker));
115579                                 }
115580                                 else {
115581                                     // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports.
115582                                     directImports.push(direct);
115583                                 }
115584                                 break;
115585                             case 188 /* ImportType */:
115586                                 directImports.push(direct);
115587                                 break;
115588                             default:
115589                                 ts.Debug.failBadSyntaxKind(direct, "Unexpected import kind.");
115590                         }
115591                     }
115592                 }
115593             }
115594             function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) {
115595                 if (exportKind === 2 /* ExportEquals */) {
115596                     // This is a direct import, not import-as-namespace.
115597                     if (!alreadyAddedDirect)
115598                         directImports.push(importDeclaration);
115599                 }
115600                 else if (!isAvailableThroughGlobal) {
115601                     var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
115602                     ts.Debug.assert(sourceFileLike.kind === 290 /* SourceFile */ || sourceFileLike.kind === 249 /* ModuleDeclaration */);
115603                     if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
115604                         addIndirectUsers(sourceFileLike);
115605                     }
115606                     else {
115607                         addIndirectUser(sourceFileLike);
115608                     }
115609                 }
115610             }
115611             function addIndirectUser(sourceFileLike) {
115612                 ts.Debug.assert(!isAvailableThroughGlobal);
115613                 var isNew = markSeenIndirectUser(sourceFileLike);
115614                 if (isNew) {
115615                     indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217
115616                 }
115617                 return isNew;
115618             }
115619             /** Adds a module and all of its transitive dependencies as possible indirect users. */
115620             function addIndirectUsers(sourceFileLike) {
115621                 if (!addIndirectUser(sourceFileLike)) {
115622                     return;
115623                 }
115624                 var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
115625                 ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
115626                 var directImports = getDirectImports(moduleSymbol);
115627                 if (directImports) {
115628                     for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) {
115629                         var directImport = directImports_1[_i];
115630                         if (!ts.isImportTypeNode(directImport)) {
115631                             addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport));
115632                         }
115633                     }
115634                 }
115635             }
115636             function getDirectImports(moduleSymbol) {
115637                 return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString());
115638             }
115639         }
115640         /**
115641          * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol.
115642          * The returned `importSearches` will result in the entire source file being searched.
115643          * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced.
115644          */
115645         function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
115646             var importSearches = [];
115647             var singleReferences = [];
115648             function addSearch(location, symbol) {
115649                 importSearches.push([location, symbol]);
115650             }
115651             if (directImports) {
115652                 for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) {
115653                     var decl = directImports_2[_i];
115654                     handleImport(decl);
115655                 }
115656             }
115657             return { importSearches: importSearches, singleReferences: singleReferences };
115658             function handleImport(decl) {
115659                 if (decl.kind === 253 /* ImportEqualsDeclaration */) {
115660                     if (isExternalModuleImportEquals(decl)) {
115661                         handleNamespaceImportLike(decl.name);
115662                     }
115663                     return;
115664                 }
115665                 if (decl.kind === 75 /* Identifier */) {
115666                     handleNamespaceImportLike(decl);
115667                     return;
115668                 }
115669                 if (decl.kind === 188 /* ImportType */) {
115670                     if (decl.qualifier) {
115671                         var firstIdentifier = ts.getFirstIdentifier(decl.qualifier);
115672                         if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) {
115673                             singleReferences.push(firstIdentifier);
115674                         }
115675                     }
115676                     else if (exportKind === 2 /* ExportEquals */) {
115677                         singleReferences.push(decl.argument.literal);
115678                     }
115679                     return;
115680                 }
115681                 // Ignore if there's a grammar error
115682                 if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) {
115683                     return;
115684                 }
115685                 if (decl.kind === 260 /* ExportDeclaration */) {
115686                     if (decl.exportClause && ts.isNamedExports(decl.exportClause)) {
115687                         searchForNamedImport(decl.exportClause);
115688                     }
115689                     return;
115690                 }
115691                 var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings;
115692                 if (namedBindings) {
115693                     switch (namedBindings.kind) {
115694                         case 256 /* NamespaceImport */:
115695                             handleNamespaceImportLike(namedBindings.name);
115696                             break;
115697                         case 257 /* NamedImports */:
115698                             // 'default' might be accessed as a named import `{ default as foo }`.
115699                             if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
115700                                 searchForNamedImport(namedBindings);
115701                             }
115702                             break;
115703                         default:
115704                             ts.Debug.assertNever(namedBindings);
115705                     }
115706                 }
115707                 // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals.
115708                 // If a default import has the same name as the default export, allow to rename it.
115709                 // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
115710                 if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
115711                     var defaultImportAlias = checker.getSymbolAtLocation(name);
115712                     addSearch(name, defaultImportAlias);
115713                 }
115714             }
115715             /**
115716              * `import x = require("./x")` or `import * as x from "./x"`.
115717              * An `export =` may be imported by this syntax, so it may be a direct import.
115718              * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
115719              */
115720             function handleNamespaceImportLike(importName) {
115721                 // Don't rename an import that already has a different name than the export.
115722                 if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) {
115723                     addSearch(importName, checker.getSymbolAtLocation(importName));
115724                 }
115725             }
115726             function searchForNamedImport(namedBindings) {
115727                 if (!namedBindings) {
115728                     return;
115729                 }
115730                 for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
115731                     var element = _a[_i];
115732                     var name = element.name, propertyName = element.propertyName;
115733                     if (!isNameMatch((propertyName || name).escapedText)) {
115734                         continue;
115735                     }
115736                     if (propertyName) {
115737                         // 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.
115738                         singleReferences.push(propertyName);
115739                         // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`.
115740                         // But do rename `foo` in ` { default as foo }` if that's the original export name.
115741                         if (!isForRename || name.escapedText === exportSymbol.escapedName) {
115742                             // Search locally for `bar`.
115743                             addSearch(name, checker.getSymbolAtLocation(name));
115744                         }
115745                     }
115746                     else {
115747                         var localSymbol = element.kind === 263 /* ExportSpecifier */ && element.propertyName
115748                             ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
115749                             : checker.getSymbolAtLocation(name);
115750                         addSearch(name, localSymbol);
115751                     }
115752                 }
115753             }
115754             function isNameMatch(name) {
115755                 // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports
115756                 return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */;
115757             }
115758         }
115759         /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */
115760         function findNamespaceReExports(sourceFileLike, name, checker) {
115761             var namespaceImportSymbol = checker.getSymbolAtLocation(name);
115762             return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
115763                 if (!ts.isExportDeclaration(statement))
115764                     return;
115765                 var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
115766                 return !moduleSpecifier && exportClause && ts.isNamedExports(exportClause) &&
115767                     exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
115768             });
115769         }
115770         function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
115771             var refs = [];
115772             var checker = program.getTypeChecker();
115773             for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
115774                 var referencingFile = sourceFiles_1[_i];
115775                 var searchSourceFile = searchModuleSymbol.valueDeclaration;
115776                 if (searchSourceFile.kind === 290 /* SourceFile */) {
115777                     for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
115778                         var ref = _b[_a];
115779                         if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
115780                             refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
115781                         }
115782                     }
115783                     for (var _c = 0, _d = referencingFile.typeReferenceDirectives; _c < _d.length; _c++) {
115784                         var ref = _d[_c];
115785                         var referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName);
115786                         if (referenced !== undefined && referenced.resolvedFileName === searchSourceFile.fileName) {
115787                             refs.push({ kind: "reference", referencingFile: referencingFile, ref: ref });
115788                         }
115789                     }
115790                 }
115791                 forEachImport(referencingFile, function (_importDecl, moduleSpecifier) {
115792                     var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
115793                     if (moduleSymbol === searchModuleSymbol) {
115794                         refs.push({ kind: "import", literal: moduleSpecifier });
115795                     }
115796                 });
115797             }
115798             return refs;
115799         }
115800         FindAllReferences.findModuleReferences = findModuleReferences;
115801         /** Returns a map from a module symbol Id to all import statements that directly reference the module. */
115802         function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
115803             var map = ts.createMap();
115804             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
115805                 var sourceFile = sourceFiles_2[_i];
115806                 if (cancellationToken)
115807                     cancellationToken.throwIfCancellationRequested();
115808                 forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
115809                     var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
115810                     if (moduleSymbol) {
115811                         var id = ts.getSymbolId(moduleSymbol).toString();
115812                         var imports = map.get(id);
115813                         if (!imports) {
115814                             map.set(id, imports = []);
115815                         }
115816                         imports.push(importDecl);
115817                     }
115818                 });
115819             }
115820             return map;
115821         }
115822         /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
115823         function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
115824             return ts.forEach(sourceFileLike.kind === 290 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
115825                 return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
115826             });
115827         }
115828         /** Calls `action` for each import, re-export, or require() in a file. */
115829         function forEachImport(sourceFile, action) {
115830             if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) {
115831                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
115832                     var i = _a[_i];
115833                     action(ts.importFromModuleSpecifier(i), i);
115834                 }
115835             }
115836             else {
115837                 forEachPossibleImportOrExportStatement(sourceFile, function (statement) {
115838                     switch (statement.kind) {
115839                         case 260 /* ExportDeclaration */:
115840                         case 254 /* ImportDeclaration */: {
115841                             var decl = statement;
115842                             if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) {
115843                                 action(decl, decl.moduleSpecifier);
115844                             }
115845                             break;
115846                         }
115847                         case 253 /* ImportEqualsDeclaration */: {
115848                             var decl = statement;
115849                             if (isExternalModuleImportEquals(decl)) {
115850                                 action(decl, decl.moduleReference.expression);
115851                             }
115852                             break;
115853                         }
115854                     }
115855                 });
115856             }
115857         }
115858         /**
115859          * Given a local reference, we might notice that it's an import/export and recursively search for references of that.
115860          * If at an import, look locally for the symbol it imports.
115861          * If at an export, look for all imports of it.
115862          * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`.
115863          * @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.
115864          */
115865         function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
115866             return comingFromExport ? getExport() : getExport() || getImport();
115867             function getExport() {
115868                 var parent = node.parent;
115869                 var grandParent = parent.parent;
115870                 if (symbol.exportSymbol) {
115871                     if (parent.kind === 194 /* PropertyAccessExpression */) {
115872                         // 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.
115873                         // So check that we are at the declaration.
115874                         return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent)
115875                             ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false)
115876                             : undefined;
115877                     }
115878                     else {
115879                         return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent));
115880                     }
115881                 }
115882                 else {
115883                     var exportNode = getExportNode(parent, node);
115884                     if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) {
115885                         if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) {
115886                             // 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.
115887                             if (comingFromExport) {
115888                                 return undefined;
115889                             }
115890                             var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
115891                             return { kind: 0 /* Import */, symbol: lhsSymbol };
115892                         }
115893                         else {
115894                             return exportInfo(symbol, getExportKindForDeclaration(exportNode));
115895                         }
115896                     }
115897                     // If we are in `export = a;` or `export default a;`, `parent` is the export assignment.
115898                     else if (ts.isExportAssignment(parent)) {
115899                         return getExportAssignmentExport(parent);
115900                     }
115901                     // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment.
115902                     else if (ts.isExportAssignment(grandParent)) {
115903                         return getExportAssignmentExport(grandParent);
115904                     }
115905                     // Similar for `module.exports =` and `exports.A =`.
115906                     else if (ts.isBinaryExpression(parent)) {
115907                         return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
115908                     }
115909                     else if (ts.isBinaryExpression(grandParent)) {
115910                         return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true);
115911                     }
115912                     else if (ts.isJSDocTypedefTag(parent)) {
115913                         return exportInfo(symbol, 0 /* Named */);
115914                     }
115915                 }
115916                 function getExportAssignmentExport(ex) {
115917                     // Get the symbol for the `export =` node; its parent is the module it's the export of.
115918                     var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent");
115919                     var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */;
115920                     return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } };
115921                 }
115922                 function getSpecialPropertyExport(node, useLhsSymbol) {
115923                     var kind;
115924                     switch (ts.getAssignmentDeclarationKind(node)) {
115925                         case 1 /* ExportsProperty */:
115926                             kind = 0 /* Named */;
115927                             break;
115928                         case 2 /* ModuleExports */:
115929                             kind = 2 /* ExportEquals */;
115930                             break;
115931                         default:
115932                             return undefined;
115933                     }
115934                     var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.getNameOfAccessExpression(ts.cast(node.left, ts.isAccessExpression))) : symbol;
115935                     return sym && exportInfo(sym, kind);
115936                 }
115937             }
115938             function getImport() {
115939                 var isImport = isNodeImport(node);
115940                 if (!isImport)
115941                     return undefined;
115942                 // A symbol being imported is always an alias. So get what that aliases to find the local symbol.
115943                 var importedSymbol = checker.getImmediateAliasedSymbol(symbol);
115944                 if (!importedSymbol)
115945                     return undefined;
115946                 // Search on the local symbol in the exporting module, not the exported symbol.
115947                 importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
115948                 // Similarly, skip past the symbol for 'export ='
115949                 if (importedSymbol.escapedName === "export=") {
115950                     importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker);
115951                 }
115952                 // If the import has a different name than the export, do not continue searching.
115953                 // If `importedName` is undefined, do continue searching as the export is anonymous.
115954                 // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
115955                 var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
115956                 if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
115957                     return { kind: 0 /* Import */, symbol: importedSymbol };
115958                 }
115959             }
115960             function exportInfo(symbol, kind) {
115961                 var exportInfo = getExportInfo(symbol, kind, checker);
115962                 return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo };
115963             }
115964             // Not meant for use with export specifiers or export assignment.
115965             function getExportKindForDeclaration(node) {
115966                 return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */;
115967             }
115968         }
115969         FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol;
115970         function getExportEqualsLocalSymbol(importedSymbol, checker) {
115971             if (importedSymbol.flags & 2097152 /* Alias */) {
115972                 return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol));
115973             }
115974             var decl = importedSymbol.valueDeclaration;
115975             if (ts.isExportAssignment(decl)) { // `export = class {}`
115976                 return ts.Debug.checkDefined(decl.expression.symbol);
115977             }
115978             else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}`
115979                 return ts.Debug.checkDefined(decl.right.symbol);
115980             }
115981             else if (ts.isSourceFile(decl)) { // json module
115982                 return ts.Debug.checkDefined(decl.symbol);
115983             }
115984             return ts.Debug.fail();
115985         }
115986         // If a reference is a class expression, the exported node would be its parent.
115987         // If a reference is a variable declaration, the exported node would be the variable statement.
115988         function getExportNode(parent, node) {
115989             var declaration = ts.isVariableDeclaration(parent) ? parent : ts.isBindingElement(parent) ? ts.walkUpBindingElementsAndPatterns(parent) : undefined;
115990             if (declaration) {
115991                 return parent.name !== node ? undefined :
115992                     ts.isCatchClause(declaration.parent) ? undefined : ts.isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : undefined;
115993             }
115994             else {
115995                 return parent;
115996             }
115997         }
115998         function isNodeImport(node) {
115999             var parent = node.parent;
116000             switch (parent.kind) {
116001                 case 253 /* ImportEqualsDeclaration */:
116002                     return parent.name === node && isExternalModuleImportEquals(parent);
116003                 case 258 /* ImportSpecifier */:
116004                     // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
116005                     return !parent.propertyName;
116006                 case 255 /* ImportClause */:
116007                 case 256 /* NamespaceImport */:
116008                     ts.Debug.assert(parent.name === node);
116009                     return true;
116010                 default:
116011                     return false;
116012             }
116013         }
116014         function getExportInfo(exportSymbol, exportKind, checker) {
116015             var moduleSymbol = exportSymbol.parent;
116016             if (!moduleSymbol)
116017                 return undefined; // This can happen if an `export` is not at the top-level (which is a compile error).
116018             var exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); // Need to get merged symbol in case there's an augmentation.
116019             // `export` may appear in a namespace. In that case, just rely on global search.
116020             return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
116021         }
116022         FindAllReferences.getExportInfo = getExportInfo;
116023         /** If at an export specifier, go to the symbol it refers to. */
116024         function skipExportSpecifierSymbol(symbol, checker) {
116025             // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
116026             if (symbol.declarations) {
116027                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
116028                     var declaration = _a[_i];
116029                     if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
116030                         return checker.getExportSpecifierLocalTargetSymbol(declaration);
116031                     }
116032                 }
116033             }
116034             return symbol;
116035         }
116036         function getContainingModuleSymbol(importer, checker) {
116037             return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
116038         }
116039         function getSourceFileLikeForImportDeclaration(node) {
116040             if (node.kind === 196 /* CallExpression */) {
116041                 return node.getSourceFile();
116042             }
116043             var parent = node.parent;
116044             if (parent.kind === 290 /* SourceFile */) {
116045                 return parent;
116046             }
116047             ts.Debug.assert(parent.kind === 250 /* ModuleBlock */);
116048             return ts.cast(parent.parent, isAmbientModuleDeclaration);
116049         }
116050         function isAmbientModuleDeclaration(node) {
116051             return node.kind === 249 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */;
116052         }
116053         function isExternalModuleImportEquals(eq) {
116054             return eq.moduleReference.kind === 265 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */;
116055         }
116056     })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
116057 })(ts || (ts = {}));
116058 /* @internal */
116059 var ts;
116060 (function (ts) {
116061     var FindAllReferences;
116062     (function (FindAllReferences) {
116063         var DefinitionKind;
116064         (function (DefinitionKind) {
116065             DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol";
116066             DefinitionKind[DefinitionKind["Label"] = 1] = "Label";
116067             DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword";
116068             DefinitionKind[DefinitionKind["This"] = 3] = "This";
116069             DefinitionKind[DefinitionKind["String"] = 4] = "String";
116070         })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {}));
116071         var EntryKind;
116072         (function (EntryKind) {
116073             EntryKind[EntryKind["Span"] = 0] = "Span";
116074             EntryKind[EntryKind["Node"] = 1] = "Node";
116075             EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral";
116076             EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty";
116077             EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal";
116078         })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {}));
116079         function nodeEntry(node, kind) {
116080             if (kind === void 0) { kind = 1 /* Node */; }
116081             return {
116082                 kind: kind,
116083                 node: node.name || node,
116084                 context: getContextNodeForNodeEntry(node)
116085             };
116086         }
116087         FindAllReferences.nodeEntry = nodeEntry;
116088         function isContextWithStartAndEndNode(node) {
116089             return node && node.kind === undefined;
116090         }
116091         FindAllReferences.isContextWithStartAndEndNode = isContextWithStartAndEndNode;
116092         function getContextNodeForNodeEntry(node) {
116093             if (ts.isDeclaration(node)) {
116094                 return getContextNode(node);
116095             }
116096             if (!node.parent)
116097                 return undefined;
116098             if (!ts.isDeclaration(node.parent) && !ts.isExportAssignment(node.parent)) {
116099                 // Special property assignment in javascript
116100                 if (ts.isInJSFile(node)) {
116101                     var binaryExpression = ts.isBinaryExpression(node.parent) ?
116102                         node.parent :
116103                         ts.isAccessExpression(node.parent) &&
116104                             ts.isBinaryExpression(node.parent.parent) &&
116105                             node.parent.parent.left === node.parent ?
116106                             node.parent.parent :
116107                             undefined;
116108                     if (binaryExpression && ts.getAssignmentDeclarationKind(binaryExpression) !== 0 /* None */) {
116109                         return getContextNode(binaryExpression);
116110                     }
116111                 }
116112                 // Jsx Tags
116113                 if (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) {
116114                     return node.parent.parent;
116115                 }
116116                 else if (ts.isJsxSelfClosingElement(node.parent) ||
116117                     ts.isLabeledStatement(node.parent) ||
116118                     ts.isBreakOrContinueStatement(node.parent)) {
116119                     return node.parent;
116120                 }
116121                 else if (ts.isStringLiteralLike(node)) {
116122                     var validImport = ts.tryGetImportFromModuleSpecifier(node);
116123                     if (validImport) {
116124                         var declOrStatement = ts.findAncestor(validImport, function (node) {
116125                             return ts.isDeclaration(node) ||
116126                                 ts.isStatement(node) ||
116127                                 ts.isJSDocTag(node);
116128                         });
116129                         return ts.isDeclaration(declOrStatement) ?
116130                             getContextNode(declOrStatement) :
116131                             declOrStatement;
116132                     }
116133                 }
116134                 // Handle computed property name
116135                 var propertyName = ts.findAncestor(node, ts.isComputedPropertyName);
116136                 return propertyName ?
116137                     getContextNode(propertyName.parent) :
116138                     undefined;
116139             }
116140             if (node.parent.name === node || // node is name of declaration, use parent
116141                 ts.isConstructorDeclaration(node.parent) ||
116142                 ts.isExportAssignment(node.parent) ||
116143                 // Property name of the import export specifier or binding pattern, use parent
116144                 ((ts.isImportOrExportSpecifier(node.parent) || ts.isBindingElement(node.parent))
116145                     && node.parent.propertyName === node) ||
116146                 // Is default export
116147                 (node.kind === 84 /* DefaultKeyword */ && ts.hasModifier(node.parent, 513 /* ExportDefault */))) {
116148                 return getContextNode(node.parent);
116149             }
116150             return undefined;
116151         }
116152         function getContextNode(node) {
116153             if (!node)
116154                 return undefined;
116155             switch (node.kind) {
116156                 case 242 /* VariableDeclaration */:
116157                     return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ?
116158                         node :
116159                         ts.isVariableStatement(node.parent.parent) ?
116160                             node.parent.parent :
116161                             ts.isForInOrOfStatement(node.parent.parent) ?
116162                                 getContextNode(node.parent.parent) :
116163                                 node.parent;
116164                 case 191 /* BindingElement */:
116165                     return getContextNode(node.parent.parent);
116166                 case 258 /* ImportSpecifier */:
116167                     return node.parent.parent.parent;
116168                 case 263 /* ExportSpecifier */:
116169                 case 256 /* NamespaceImport */:
116170                     return node.parent.parent;
116171                 case 255 /* ImportClause */:
116172                     return node.parent;
116173                 case 209 /* BinaryExpression */:
116174                     return ts.isExpressionStatement(node.parent) ?
116175                         node.parent :
116176                         node;
116177                 case 232 /* ForOfStatement */:
116178                 case 231 /* ForInStatement */:
116179                     return {
116180                         start: node.initializer,
116181                         end: node.expression
116182                     };
116183                 case 281 /* PropertyAssignment */:
116184                 case 282 /* ShorthandPropertyAssignment */:
116185                     return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ?
116186                         getContextNode(ts.findAncestor(node.parent, function (node) {
116187                             return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node);
116188                         })) :
116189                         node;
116190                 default:
116191                     return node;
116192             }
116193         }
116194         FindAllReferences.getContextNode = getContextNode;
116195         function toContextSpan(textSpan, sourceFile, context) {
116196             if (!context)
116197                 return undefined;
116198             var contextSpan = isContextWithStartAndEndNode(context) ?
116199                 getTextSpan(context.start, sourceFile, context.end) :
116200                 getTextSpan(context, sourceFile);
116201             return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ?
116202                 { contextSpan: contextSpan } :
116203                 undefined;
116204         }
116205         FindAllReferences.toContextSpan = toContextSpan;
116206         var FindReferencesUse;
116207         (function (FindReferencesUse) {
116208             /**
116209              * When searching for references to a symbol, the location will not be adjusted (this is the default behavior when not specified).
116210              */
116211             FindReferencesUse[FindReferencesUse["Other"] = 0] = "Other";
116212             /**
116213              * When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
116214              */
116215             FindReferencesUse[FindReferencesUse["References"] = 1] = "References";
116216             /**
116217              * When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
116218              * Unlike `References`, the location will only be adjusted keyword belonged to a declaration with a valid name.
116219              * If set, we will find fewer references -- if it is referenced by several different names, we still only find references for the original name.
116220              */
116221             FindReferencesUse[FindReferencesUse["Rename"] = 2] = "Rename";
116222         })(FindReferencesUse = FindAllReferences.FindReferencesUse || (FindAllReferences.FindReferencesUse = {}));
116223         function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) {
116224             var node = ts.getTouchingPropertyName(sourceFile, position);
116225             var referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, { use: 1 /* References */ });
116226             var checker = program.getTypeChecker();
116227             return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) {
116228                 var definition = _a.definition, references = _a.references;
116229                 // Only include referenced symbols that have a valid definition.
116230                 return definition && {
116231                     definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }),
116232                     references: references.map(toReferenceEntry)
116233                 };
116234             });
116235         }
116236         FindAllReferences.findReferencedSymbols = findReferencedSymbols;
116237         function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) {
116238             var node = ts.getTouchingPropertyName(sourceFile, position);
116239             var referenceEntries;
116240             var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
116241             if (node.parent.kind === 194 /* PropertyAccessExpression */
116242                 || node.parent.kind === 191 /* BindingElement */
116243                 || node.parent.kind === 195 /* ElementAccessExpression */
116244                 || node.kind === 102 /* SuperKeyword */) {
116245                 referenceEntries = entries && __spreadArrays(entries);
116246             }
116247             else {
116248                 var queue = entries && __spreadArrays(entries);
116249                 var seenNodes = ts.createMap();
116250                 while (queue && queue.length) {
116251                     var entry = queue.shift();
116252                     if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) {
116253                         continue;
116254                     }
116255                     referenceEntries = ts.append(referenceEntries, entry);
116256                     var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos);
116257                     if (entries_1) {
116258                         queue.push.apply(queue, entries_1);
116259                     }
116260                 }
116261             }
116262             var checker = program.getTypeChecker();
116263             return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); });
116264         }
116265         FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
116266         function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
116267             if (node.kind === 290 /* SourceFile */) {
116268                 return undefined;
116269             }
116270             var checker = program.getTypeChecker();
116271             // If invoked directly on a shorthand property assignment, then return
116272             // the declaration of the symbol being assigned (not the symbol being assigned to).
116273             if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
116274                 var result_1 = [];
116275                 Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
116276                 return result_1;
116277             }
116278             else if (node.kind === 102 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
116279                 // References to and accesses on the super keyword only have one possible implementation, so no
116280                 // need to "Find all References"
116281                 var symbol = checker.getSymbolAtLocation(node);
116282                 return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
116283             }
116284             else {
116285                 // Perform "Find all References" and retrieve only those that are implementations
116286                 return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: 1 /* References */ });
116287             }
116288         }
116289         function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) {
116290             return ts.map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node, program.getTypeChecker()); });
116291         }
116292         FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries;
116293         function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
116294             if (options === void 0) { options = {}; }
116295             if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
116296             return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
116297         }
116298         FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
116299         function flattenEntries(referenceSymbols) {
116300             return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
116301         }
116302         function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) {
116303             var info = (function () {
116304                 switch (def.type) {
116305                     case 0 /* Symbol */: {
116306                         var symbol = def.symbol;
116307                         var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
116308                         var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
116309                         var declaration = symbol.declarations ? ts.first(symbol.declarations) : undefined;
116310                         return {
116311                             node: declaration ?
116312                                 ts.getNameOfDeclaration(declaration) || declaration :
116313                                 originalNode,
116314                             name: name_1,
116315                             kind: kind_1,
116316                             displayParts: displayParts_1,
116317                             context: getContextNode(declaration)
116318                         };
116319                     }
116320                     case 1 /* Label */: {
116321                         var node_1 = def.node;
116322                         return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
116323                     }
116324                     case 2 /* Keyword */: {
116325                         var node_2 = def.node;
116326                         var name_2 = ts.tokenToString(node_2.kind);
116327                         return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
116328                     }
116329                     case 3 /* This */: {
116330                         var node_3 = def.node;
116331                         var symbol = checker.getSymbolAtLocation(node_3);
116332                         var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
116333                         return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
116334                     }
116335                     case 4 /* String */: {
116336                         var node_4 = def.node;
116337                         return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
116338                     }
116339                     default:
116340                         return ts.Debug.assertNever(def);
116341                 }
116342             })();
116343             var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts, context = info.context;
116344             var sourceFile = node.getSourceFile();
116345             var textSpan = getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile);
116346             return __assign({ containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind,
116347                 name: name,
116348                 textSpan: textSpan,
116349                 displayParts: displayParts }, toContextSpan(textSpan, sourceFile, context));
116350         }
116351         function getDefinitionKindAndDisplayParts(symbol, checker, node) {
116352             var meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
116353             var enclosingDeclaration = symbol.declarations && ts.firstOrUndefined(symbol.declarations) || node;
116354             var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
116355             return { displayParts: displayParts, kind: symbolKind };
116356         }
116357         function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) {
116358             return __assign(__assign({}, entryToDocumentSpan(entry)), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker)));
116359         }
116360         FindAllReferences.toRenameLocation = toRenameLocation;
116361         function toReferenceEntry(entry) {
116362             var documentSpan = entryToDocumentSpan(entry);
116363             if (entry.kind === 0 /* Span */) {
116364                 return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false });
116365             }
116366             var kind = entry.kind, node = entry.node;
116367             return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined });
116368         }
116369         FindAllReferences.toReferenceEntry = toReferenceEntry;
116370         function entryToDocumentSpan(entry) {
116371             if (entry.kind === 0 /* Span */) {
116372                 return { textSpan: entry.textSpan, fileName: entry.fileName };
116373             }
116374             else {
116375                 var sourceFile = entry.node.getSourceFile();
116376                 var textSpan = getTextSpan(entry.node, sourceFile);
116377                 return __assign({ textSpan: textSpan, fileName: sourceFile.fileName }, toContextSpan(textSpan, sourceFile, entry.context));
116378             }
116379         }
116380         function getPrefixAndSuffixText(entry, originalNode, checker) {
116381             if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) {
116382                 var node = entry.node, kind = entry.kind;
116383                 var name = originalNode.text;
116384                 var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent);
116385                 if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent) && node.parent.name === node) {
116386                     var prefixColon = { prefixText: name + ": " };
116387                     var suffixColon = { suffixText: ": " + name };
116388                     return kind === 3 /* SearchedLocalFoundProperty */ ? prefixColon
116389                         : kind === 4 /* SearchedPropertyFoundLocal */ ? suffixColon
116390                             // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
116391                             // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
116392                             : isShorthandAssignment ? suffixColon : prefixColon;
116393                 }
116394                 else if (ts.isImportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
116395                     // If the original symbol was using this alias, just rename the alias.
116396                     var originalSymbol = ts.isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
116397                     return ts.contains(originalSymbol.declarations, entry.node.parent) ? { prefixText: name + " as " } : ts.emptyOptions;
116398                 }
116399                 else if (ts.isExportSpecifier(entry.node.parent) && !entry.node.parent.propertyName) {
116400                     // If the symbol for the node is same as declared node symbol use prefix text
116401                     return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ?
116402                         { prefixText: name + " as " } :
116403                         { suffixText: " as " + name };
116404                 }
116405             }
116406             return ts.emptyOptions;
116407         }
116408         function toImplementationLocation(entry, checker) {
116409             var documentSpan = entryToDocumentSpan(entry);
116410             if (entry.kind !== 0 /* Span */) {
116411                 var node = entry.node;
116412                 return __assign(__assign({}, documentSpan), implementationKindDisplayParts(node, checker));
116413             }
116414             else {
116415                 return __assign(__assign({}, documentSpan), { kind: "" /* unknown */, displayParts: [] });
116416             }
116417         }
116418         function implementationKindDisplayParts(node, checker) {
116419             var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
116420             if (symbol) {
116421                 return getDefinitionKindAndDisplayParts(symbol, checker, node);
116422             }
116423             else if (node.kind === 193 /* ObjectLiteralExpression */) {
116424                 return {
116425                     kind: "interface" /* interfaceElement */,
116426                     displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)]
116427                 };
116428             }
116429             else if (node.kind === 214 /* ClassExpression */) {
116430                 return {
116431                     kind: "local class" /* localClassElement */,
116432                     displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)]
116433                 };
116434             }
116435             else {
116436                 return { kind: ts.getNodeKind(node), displayParts: [] };
116437             }
116438         }
116439         function toHighlightSpan(entry) {
116440             var documentSpan = entryToDocumentSpan(entry);
116441             if (entry.kind === 0 /* Span */) {
116442                 return {
116443                     fileName: documentSpan.fileName,
116444                     span: {
116445                         textSpan: documentSpan.textSpan,
116446                         kind: "reference" /* reference */
116447                     }
116448                 };
116449             }
116450             var writeAccess = isWriteAccessForReference(entry.node);
116451             var span = __assign({ textSpan: documentSpan.textSpan, kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: entry.kind === 2 /* StringLiteral */ ? true : undefined }, documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan });
116452             return { fileName: documentSpan.fileName, span: span };
116453         }
116454         FindAllReferences.toHighlightSpan = toHighlightSpan;
116455         function getTextSpan(node, sourceFile, endNode) {
116456             var start = node.getStart(sourceFile);
116457             var end = (endNode || node).getEnd();
116458             if (ts.isStringLiteralLike(node)) {
116459                 ts.Debug.assert(endNode === undefined);
116460                 start += 1;
116461                 end -= 1;
116462             }
116463             return ts.createTextSpanFromBounds(start, end);
116464         }
116465         function getTextSpanOfEntry(entry) {
116466             return entry.kind === 0 /* Span */ ? entry.textSpan :
116467                 getTextSpan(entry.node, entry.node.getSourceFile());
116468         }
116469         FindAllReferences.getTextSpanOfEntry = getTextSpanOfEntry;
116470         /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
116471         function isWriteAccessForReference(node) {
116472             var decl = ts.getDeclarationFromName(node);
116473             return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node);
116474         }
116475         function isDefinitionForReference(node) {
116476             return node.kind === 84 /* DefaultKeyword */
116477                 || !!ts.getDeclarationFromName(node)
116478                 || ts.isLiteralComputedPropertyDeclarationName(node)
116479                 || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent));
116480         }
116481         /**
116482          * True if 'decl' provides a value, as in `function f() {}`;
116483          * false if 'decl' is just a location for a future write, as in 'let x;'
116484          */
116485         function declarationIsWriteAccess(decl) {
116486             // Consider anything in an ambient declaration to be a write access since it may be coming from JS.
116487             if (!!(decl.flags & 8388608 /* Ambient */))
116488                 return true;
116489             switch (decl.kind) {
116490                 case 209 /* BinaryExpression */:
116491                 case 191 /* BindingElement */:
116492                 case 245 /* ClassDeclaration */:
116493                 case 214 /* ClassExpression */:
116494                 case 84 /* DefaultKeyword */:
116495                 case 248 /* EnumDeclaration */:
116496                 case 284 /* EnumMember */:
116497                 case 263 /* ExportSpecifier */:
116498                 case 255 /* ImportClause */: // default import
116499                 case 253 /* ImportEqualsDeclaration */:
116500                 case 258 /* ImportSpecifier */:
116501                 case 246 /* InterfaceDeclaration */:
116502                 case 315 /* JSDocCallbackTag */:
116503                 case 322 /* JSDocTypedefTag */:
116504                 case 273 /* JsxAttribute */:
116505                 case 249 /* ModuleDeclaration */:
116506                 case 252 /* NamespaceExportDeclaration */:
116507                 case 256 /* NamespaceImport */:
116508                 case 262 /* NamespaceExport */:
116509                 case 156 /* Parameter */:
116510                 case 282 /* ShorthandPropertyAssignment */:
116511                 case 247 /* TypeAliasDeclaration */:
116512                 case 155 /* TypeParameter */:
116513                     return true;
116514                 case 281 /* PropertyAssignment */:
116515                     // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.)
116516                     return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent);
116517                 case 244 /* FunctionDeclaration */:
116518                 case 201 /* FunctionExpression */:
116519                 case 162 /* Constructor */:
116520                 case 161 /* MethodDeclaration */:
116521                 case 163 /* GetAccessor */:
116522                 case 164 /* SetAccessor */:
116523                     return !!decl.body;
116524                 case 242 /* VariableDeclaration */:
116525                 case 159 /* PropertyDeclaration */:
116526                     return !!decl.initializer || ts.isCatchClause(decl.parent);
116527                 case 160 /* MethodSignature */:
116528                 case 158 /* PropertySignature */:
116529                 case 323 /* JSDocPropertyTag */:
116530                 case 317 /* JSDocParameterTag */:
116531                     return false;
116532                 default:
116533                     return ts.Debug.failBadSyntaxKind(decl);
116534             }
116535         }
116536         /** Encapsulates the core find-all-references algorithm. */
116537         var Core;
116538         (function (Core) {
116539             /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
116540             function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
116541                 if (options === void 0) { options = {}; }
116542                 if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
116543                 if (options.use === 1 /* References */) {
116544                     node = ts.getAdjustedReferenceLocation(node);
116545                 }
116546                 else if (options.use === 2 /* Rename */) {
116547                     node = ts.getAdjustedRenameLocation(node);
116548                 }
116549                 if (ts.isSourceFile(node)) {
116550                     var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
116551                     var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol);
116552                     return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
116553                 }
116554                 if (!options.implementations) {
116555                     var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
116556                     if (special) {
116557                         return special;
116558                     }
116559                 }
116560                 var checker = program.getTypeChecker();
116561                 var symbol = checker.getSymbolAtLocation(node);
116562                 // Could not find a symbol e.g. unknown identifier
116563                 if (!symbol) {
116564                     // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
116565                     return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
116566                 }
116567                 if (symbol.escapedName === "export=" /* ExportEquals */) {
116568                     return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
116569                 }
116570                 var moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
116571                 if (moduleReferences && !(symbol.flags & 33554432 /* Transient */)) {
116572                     return moduleReferences;
116573                 }
116574                 var aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker);
116575                 var moduleReferencesOfExportTarget = aliasedSymbol &&
116576                     getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
116577                 var references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
116578                 return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
116579             }
116580             Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
116581             function getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker) {
116582                 if (node.parent && ts.isNamespaceExportDeclaration(node.parent)) {
116583                     var aliasedSymbol = checker.getAliasedSymbol(symbol);
116584                     var targetSymbol = checker.getMergedSymbol(aliasedSymbol);
116585                     if (aliasedSymbol !== targetSymbol) {
116586                         return targetSymbol;
116587                     }
116588                 }
116589                 return undefined;
116590             }
116591             function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) {
116592                 var moduleSourceFile = (symbol.flags & 1536 /* Module */) && symbol.declarations && ts.find(symbol.declarations, ts.isSourceFile);
116593                 if (!moduleSourceFile)
116594                     return undefined;
116595                 var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
116596                 // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
116597                 var moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
116598                 if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
116599                     return moduleReferences;
116600                 // Continue to get references to 'export ='.
116601                 var checker = program.getTypeChecker();
116602                 symbol = ts.skipAlias(exportEquals, checker);
116603                 return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ undefined, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
116604             }
116605             /**
116606              * Merges the references by sorting them (by file index in sourceFiles and their location in it) that point to same definition symbol
116607              */
116608             function mergeReferences(program) {
116609                 var referencesToMerge = [];
116610                 for (var _i = 1; _i < arguments.length; _i++) {
116611                     referencesToMerge[_i - 1] = arguments[_i];
116612                 }
116613                 var result;
116614                 for (var _a = 0, referencesToMerge_1 = referencesToMerge; _a < referencesToMerge_1.length; _a++) {
116615                     var references = referencesToMerge_1[_a];
116616                     if (!references || !references.length)
116617                         continue;
116618                     if (!result) {
116619                         result = references;
116620                         continue;
116621                     }
116622                     var _loop_3 = function (entry) {
116623                         if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
116624                             result.push(entry);
116625                             return "continue";
116626                         }
116627                         var symbol = entry.definition.symbol;
116628                         var refIndex = ts.findIndex(result, function (ref) { return !!ref.definition &&
116629                             ref.definition.type === 0 /* Symbol */ &&
116630                             ref.definition.symbol === symbol; });
116631                         if (refIndex === -1) {
116632                             result.push(entry);
116633                             return "continue";
116634                         }
116635                         var reference = result[refIndex];
116636                         result[refIndex] = {
116637                             definition: reference.definition,
116638                             references: reference.references.concat(entry.references).sort(function (entry1, entry2) {
116639                                 var entry1File = getSourceFileIndexOfEntry(program, entry1);
116640                                 var entry2File = getSourceFileIndexOfEntry(program, entry2);
116641                                 if (entry1File !== entry2File) {
116642                                     return ts.compareValues(entry1File, entry2File);
116643                                 }
116644                                 var entry1Span = getTextSpanOfEntry(entry1);
116645                                 var entry2Span = getTextSpanOfEntry(entry2);
116646                                 return entry1Span.start !== entry2Span.start ?
116647                                     ts.compareValues(entry1Span.start, entry2Span.start) :
116648                                     ts.compareValues(entry1Span.length, entry2Span.length);
116649                             })
116650                         };
116651                     };
116652                     for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
116653                         var entry = references_1[_b];
116654                         _loop_3(entry);
116655                     }
116656                 }
116657                 return result;
116658             }
116659             function getSourceFileIndexOfEntry(program, entry) {
116660                 var sourceFile = entry.kind === 0 /* Span */ ?
116661                     program.getSourceFile(entry.fileName) :
116662                     entry.node.getSourceFile();
116663                 return program.getSourceFiles().indexOf(sourceFile);
116664             }
116665             function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
116666                 ts.Debug.assert(!!symbol.valueDeclaration);
116667                 var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
116668                     if (reference.kind === "import") {
116669                         var parent = reference.literal.parent;
116670                         if (ts.isLiteralTypeNode(parent)) {
116671                             var importType = ts.cast(parent.parent, ts.isImportTypeNode);
116672                             if (excludeImportTypeOfExportEquals && !importType.qualifier) {
116673                                 return undefined;
116674                             }
116675                         }
116676                         // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
116677                         return nodeEntry(reference.literal);
116678                     }
116679                     else {
116680                         return {
116681                             kind: 0 /* Span */,
116682                             fileName: reference.referencingFile.fileName,
116683                             textSpan: ts.createTextSpanFromRange(reference.ref),
116684                         };
116685                     }
116686                 });
116687                 if (symbol.declarations) {
116688                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
116689                         var decl = _a[_i];
116690                         switch (decl.kind) {
116691                             case 290 /* SourceFile */:
116692                                 // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
116693                                 break;
116694                             case 249 /* ModuleDeclaration */:
116695                                 if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
116696                                     references.push(nodeEntry(decl.name));
116697                                 }
116698                                 break;
116699                             default:
116700                                 // This may be merged with something.
116701                                 ts.Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
116702                         }
116703                     }
116704                 }
116705                 var exported = symbol.exports.get("export=" /* ExportEquals */);
116706                 if (exported) {
116707                     for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) {
116708                         var decl = _c[_b];
116709                         var sourceFile = decl.getSourceFile();
116710                         if (sourceFilesSet.has(sourceFile.fileName)) {
116711                             // At `module.exports = ...`, reference node is `module`
116712                             var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) ? decl.left.expression :
116713                                 ts.isExportAssignment(decl) ? ts.Debug.checkDefined(ts.findChildOfKind(decl, 89 /* ExportKeyword */, sourceFile)) :
116714                                     ts.getNameOfDeclaration(decl) || decl;
116715                             references.push(nodeEntry(node));
116716                         }
116717                     }
116718                 }
116719                 return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray;
116720             }
116721             /** As in a `readonly prop: any` or `constructor(readonly prop: any)`, not a `readonly any[]`. */
116722             function isReadonlyTypeOperator(node) {
116723                 return node.kind === 138 /* ReadonlyKeyword */
116724                     && ts.isTypeOperatorNode(node.parent)
116725                     && node.parent.operator === 138 /* ReadonlyKeyword */;
116726             }
116727             /** getReferencedSymbols for special node kinds. */
116728             function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
116729                 if (ts.isTypeKeyword(node.kind)) {
116730                     // A void expression (i.e., `void foo()`) is not special, but the `void` type is.
116731                     if (node.kind === 110 /* VoidKeyword */ && ts.isVoidExpression(node.parent)) {
116732                         return undefined;
116733                     }
116734                     // A modifier readonly (like on a property declaration) is not special;
116735                     // a readonly type keyword (like `readonly string[]`) is.
116736                     if (node.kind === 138 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) {
116737                         return undefined;
116738                     }
116739                     // Likewise, when we *are* looking for a special keyword, make sure we
116740                     // *don’t* include readonly member modifiers.
116741                     return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 138 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : undefined);
116742                 }
116743                 // Labels
116744                 if (ts.isJumpStatementTarget(node)) {
116745                     var labelDefinition = ts.getTargetLabel(node.parent, node.text);
116746                     // if we have a label definition, look within its statement for references, if not, then
116747                     // the label is undefined and we have no results..
116748                     return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
116749                 }
116750                 else if (ts.isLabelOfLabeledStatement(node)) {
116751                     // it is a label definition and not a target, search within the parent labeledStatement
116752                     return getLabelReferencesInNode(node.parent, node);
116753                 }
116754                 if (ts.isThis(node)) {
116755                     return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
116756                 }
116757                 if (node.kind === 102 /* SuperKeyword */) {
116758                     return getReferencesForSuperKeyword(node);
116759                 }
116760                 return undefined;
116761             }
116762             /** Core find-all-references algorithm for a normal symbol. */
116763             function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
116764                 var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol;
116765                 // Compute the meaning from the location and the symbol it references
116766                 var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
116767                 var result = [];
116768                 var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
116769                 var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier);
116770                 if (exportSpecifier) {
116771                     // When renaming at an export specifier, rename the export and not the thing being exported.
116772                     getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
116773                 }
116774                 else if (node && node.kind === 84 /* DefaultKeyword */) {
116775                     addReference(node, symbol, state);
116776                     searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
116777                 }
116778                 else {
116779                     var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
116780                     getReferencesInContainerOrFiles(symbol, state, search);
116781                 }
116782                 return result;
116783             }
116784             function getReferencesInContainerOrFiles(symbol, state, search) {
116785                 // Try to get the smallest valid scope that we can limit our search to;
116786                 // otherwise we'll need to search globally (i.e. include each file).
116787                 var scope = getSymbolScope(symbol);
116788                 if (scope) {
116789                     getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
116790                 }
116791                 else {
116792                     // Global search
116793                     for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) {
116794                         var sourceFile = _a[_i];
116795                         state.cancellationToken.throwIfCancellationRequested();
116796                         searchForName(sourceFile, search, state);
116797                     }
116798                 }
116799             }
116800             function getSpecialSearchKind(node) {
116801                 switch (node.kind) {
116802                     case 129 /* ConstructorKeyword */:
116803                         return 1 /* Constructor */;
116804                     case 75 /* Identifier */:
116805                         if (ts.isClassLike(node.parent)) {
116806                             ts.Debug.assert(node.parent.name === node);
116807                             return 2 /* Class */;
116808                         }
116809                     // falls through
116810                     default:
116811                         return 0 /* None */;
116812                 }
116813             }
116814             /** Handle a few special cases relating to export/import specifiers. */
116815             function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) {
116816                 var parent = node.parent;
116817                 if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) {
116818                     return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
116819                 }
116820                 // 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.
116821                 return ts.firstDefined(symbol.declarations, function (decl) {
116822                     if (!decl.parent) {
116823                         // Ignore UMD module and global merge
116824                         if (symbol.flags & 33554432 /* Transient */)
116825                             return undefined;
116826                         // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
116827                         ts.Debug.fail("Unexpected symbol at " + ts.Debug.formatSyntaxKind(node.kind) + ": " + ts.Debug.formatSymbol(symbol));
116828                     }
116829                     return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
116830                         ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name)
116831                         : undefined;
116832                 });
116833             }
116834             var SpecialSearchKind;
116835             (function (SpecialSearchKind) {
116836                 SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None";
116837                 SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor";
116838                 SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class";
116839             })(SpecialSearchKind || (SpecialSearchKind = {}));
116840             function getNonModuleSymbolOfMergedModuleSymbol(symbol) {
116841                 if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */)))
116842                     return undefined;
116843                 var decl = symbol.declarations && ts.find(symbol.declarations, function (d) { return !ts.isSourceFile(d) && !ts.isModuleDeclaration(d); });
116844                 return decl && decl.symbol;
116845             }
116846             /**
116847              * Holds all state needed for the finding references.
116848              * Unlike `Search`, there is only one `State`.
116849              */
116850             var State = /** @class */ (function () {
116851                 function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
116852                     this.sourceFiles = sourceFiles;
116853                     this.sourceFilesSet = sourceFilesSet;
116854                     this.specialSearchKind = specialSearchKind;
116855                     this.checker = checker;
116856                     this.cancellationToken = cancellationToken;
116857                     this.searchMeaning = searchMeaning;
116858                     this.options = options;
116859                     this.result = result;
116860                     /** Cache for `explicitlyinheritsFrom`. */
116861                     this.inheritsFromCache = ts.createMap();
116862                     /**
116863                      * Type nodes can contain multiple references to the same type. For example:
116864                      *      let x: Foo & (Foo & Bar) = ...
116865                      * Because we are returning the implementation locations and not the identifier locations,
116866                      * duplicate entries would be returned here as each of the type references is part of
116867                      * the same implementation. For that reason, check before we add a new entry.
116868                      */
116869                     this.markSeenContainingTypeReference = ts.nodeSeenTracker();
116870                     /**
116871                      * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
116872                      * For example:
116873                      *     // b.ts
116874                      *     export { foo as bar } from "./a";
116875                      *     import { bar } from "./b";
116876                      *
116877                      * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
116878                      * But another reference to it may appear in the same source file.
116879                      * See `tests/cases/fourslash/transitiveExportImports3.ts`.
116880                      */
116881                     this.markSeenReExportRHS = ts.nodeSeenTracker();
116882                     this.symbolIdToReferences = [];
116883                     // Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
116884                     this.sourceFileToSeenSymbols = [];
116885                 }
116886                 State.prototype.includesSourceFile = function (sourceFile) {
116887                     return this.sourceFilesSet.has(sourceFile.fileName);
116888                 };
116889                 /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
116890                 State.prototype.getImportSearches = function (exportSymbol, exportInfo) {
116891                     if (!this.importTracker)
116892                         this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
116893                     return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */);
116894                 };
116895                 /** @param allSearchSymbols set of additional symbols for use by `includes`. */
116896                 State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) {
116897                     if (searchOptions === void 0) { searchOptions = {}; }
116898                     // Note: if this is an external module symbol, the name doesn't include quotes.
116899                     // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`.
116900                     // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
116901                     // here appears to be intentional).
116902                     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;
116903                     var escapedText = ts.escapeLeadingUnderscores(text);
116904                     var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined;
116905                     return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
116906                 };
116907                 /**
116908                  * Callback to add references for a particular searched symbol.
116909                  * This initializes a reference group, so only call this if you will add at least one reference.
116910                  */
116911                 State.prototype.referenceAdder = function (searchSymbol) {
116912                     var symbolId = ts.getSymbolId(searchSymbol);
116913                     var references = this.symbolIdToReferences[symbolId];
116914                     if (!references) {
116915                         references = this.symbolIdToReferences[symbolId] = [];
116916                         this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references });
116917                     }
116918                     return function (node, kind) { return references.push(nodeEntry(node, kind)); };
116919                 };
116920                 /** Add a reference with no associated definition. */
116921                 State.prototype.addStringOrCommentReference = function (fileName, textSpan) {
116922                     this.result.push({
116923                         definition: undefined,
116924                         references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }]
116925                     });
116926                 };
116927                 /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
116928                 State.prototype.markSearchedSymbols = function (sourceFile, symbols) {
116929                     var sourceId = ts.getNodeId(sourceFile);
116930                     var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
116931                     var anyNewSymbols = false;
116932                     for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
116933                         var sym = symbols_3[_i];
116934                         anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
116935                     }
116936                     return anyNewSymbols;
116937                 };
116938                 return State;
116939             }());
116940             /** Search for all imports of a given exported symbol using `State.getImportSearches`. */
116941             function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
116942                 var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
116943                 // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
116944                 if (singleReferences.length) {
116945                     var addRef = state.referenceAdder(exportSymbol);
116946                     for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
116947                         var singleRef = singleReferences_1[_i];
116948                         if (shouldAddSingleReference(singleRef, state))
116949                             addRef(singleRef);
116950                     }
116951                 }
116952                 // For each import, find all references to that import in its source file.
116953                 for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) {
116954                     var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1];
116955                     getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
116956                 }
116957                 if (indirectUsers.length) {
116958                     var indirectSearch = void 0;
116959                     switch (exportInfo.exportKind) {
116960                         case 0 /* Named */:
116961                             indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
116962                             break;
116963                         case 1 /* Default */:
116964                             // Search for a property access to '.default'. This can't be renamed.
116965                             indirectSearch = state.options.use === 2 /* Rename */ ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
116966                             break;
116967                         case 2 /* ExportEquals */:
116968                             break;
116969                     }
116970                     if (indirectSearch) {
116971                         for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) {
116972                             var indirectUser = indirectUsers_1[_d];
116973                             searchForName(indirectUser, indirectSearch, state);
116974                         }
116975                     }
116976                 }
116977             }
116978             function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
116979                 var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken);
116980                 var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers;
116981                 for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) {
116982                     var importLocation = importSearches_2[_i][0];
116983                     cb(importLocation);
116984                 }
116985                 for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) {
116986                     var indirectUser = indirectUsers_2[_b];
116987                     for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
116988                         var node = _d[_c];
116989                         // Import specifiers should be handled by importSearches
116990                         if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) {
116991                             cb(node);
116992                         }
116993                     }
116994                 }
116995             }
116996             Core.eachExportReference = eachExportReference;
116997             function shouldAddSingleReference(singleRef, state) {
116998                 if (!hasMatchingMeaning(singleRef, state))
116999                     return false;
117000                 if (state.options.use !== 2 /* Rename */)
117001                     return true;
117002                 // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
117003                 if (!ts.isIdentifier(singleRef))
117004                     return false;
117005                 // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
117006                 return !(ts.isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */);
117007             }
117008             // Go to the symbol we imported from and find references for it.
117009             function searchForImportedSymbol(symbol, state) {
117010                 if (!symbol.declarations)
117011                     return;
117012                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
117013                     var declaration = _a[_i];
117014                     var exportingFile = declaration.getSourceFile();
117015                     // Need to search in the file even if it's not in the search-file set, because it might export the symbol.
117016                     getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile));
117017                 }
117018             }
117019             /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
117020             function searchForName(sourceFile, search, state) {
117021                 if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) {
117022                     getReferencesInSourceFile(sourceFile, search, state);
117023                 }
117024             }
117025             function getPropertySymbolOfDestructuringAssignment(location, checker) {
117026                 return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent)
117027                     ? checker.getPropertySymbolOfDestructuringAssignment(location)
117028                     : undefined;
117029             }
117030             /**
117031              * Determines the smallest scope in which a symbol may have named references.
117032              * Note that not every construct has been accounted for. This function can
117033              * probably be improved.
117034              *
117035              * @returns undefined if the scope cannot be determined, implying that
117036              * a reference to a symbol can occur anywhere.
117037              */
117038             function getSymbolScope(symbol) {
117039                 // If this is the symbol of a named function expression or named class expression,
117040                 // then named references are limited to its own scope.
117041                 var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration;
117042                 if (valueDeclaration && (valueDeclaration.kind === 201 /* FunctionExpression */ || valueDeclaration.kind === 214 /* ClassExpression */)) {
117043                     return valueDeclaration;
117044                 }
117045                 if (!declarations) {
117046                     return undefined;
117047                 }
117048                 // If this is private property or method, the scope is the containing class
117049                 if (flags & (4 /* Property */ | 8192 /* Method */)) {
117050                     var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); });
117051                     if (privateDeclaration) {
117052                         return ts.getAncestor(privateDeclaration, 245 /* ClassDeclaration */);
117053                     }
117054                     // Else this is a public property and could be accessed from anywhere.
117055                     return undefined;
117056                 }
117057                 // If symbol is of object binding pattern element without property name we would want to
117058                 // look for property too and that could be anywhere
117059                 if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) {
117060                     return undefined;
117061                 }
117062                 /*
117063                 If the symbol has a parent, it's globally visible unless:
117064                 - It's a private property (handled above).
117065                 - It's a type parameter.
117066                 - The parent is an external module: then we should only search in the module (and recurse on the export later).
117067                 - But if the parent has `export as namespace`, the symbol is globally visible through that namespace.
117068                 */
117069                 var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */);
117070                 if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) {
117071                     return undefined;
117072                 }
117073                 var scope;
117074                 for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
117075                     var declaration = declarations_1[_i];
117076                     var container = ts.getContainerNode(declaration);
117077                     if (scope && scope !== container) {
117078                         // Different declarations have different containers, bail out
117079                         return undefined;
117080                     }
117081                     if (!container || container.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
117082                         // This is a global variable and not an external module, any declaration defined
117083                         // within this scope is visible outside the file
117084                         return undefined;
117085                     }
117086                     // The search scope is the container node
117087                     scope = container;
117088                 }
117089                 // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
117090                 // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
117091                 //     declare module "a" { export type T = number; }
117092                 //     declare module "b" { import { T } from "a"; export const x: T; }
117093                 // 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.)
117094                 return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217
117095             }
117096             /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
117097             function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer) {
117098                 if (searchContainer === void 0) { searchContainer = sourceFile; }
117099                 return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }, searchContainer) || false;
117100             }
117101             Core.isSymbolReferencedInFile = isSymbolReferencedInFile;
117102             function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer) {
117103                 if (searchContainer === void 0) { searchContainer = sourceFile; }
117104                 var symbol = ts.isParameterPropertyDeclaration(definition.parent, definition.parent.parent)
117105                     ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text))
117106                     : checker.getSymbolAtLocation(definition);
117107                 if (!symbol)
117108                     return undefined;
117109                 for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer); _i < _a.length; _i++) {
117110                     var token = _a[_i];
117111                     if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText)
117112                         continue;
117113                     var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary
117114                     if (referenceSymbol === symbol
117115                         || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol
117116                         || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) {
117117                         var res = cb(token);
117118                         if (res)
117119                             return res;
117120                     }
117121                 }
117122             }
117123             Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
117124             function eachSignatureCall(signature, sourceFiles, checker, cb) {
117125                 if (!signature.name || !ts.isIdentifier(signature.name))
117126                     return;
117127                 var symbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(signature.name));
117128                 for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
117129                     var sourceFile = sourceFiles_3[_i];
117130                     for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
117131                         var name = _b[_a];
117132                         if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
117133                             continue;
117134                         var called = ts.climbPastPropertyAccess(name);
117135                         var call = called.parent;
117136                         if (!ts.isCallExpression(call) || call.expression !== called)
117137                             continue;
117138                         var referenceSymbol = checker.getSymbolAtLocation(name);
117139                         if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) {
117140                             cb(call);
117141                         }
117142                     }
117143                 }
117144             }
117145             Core.eachSignatureCall = eachSignatureCall;
117146             function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) {
117147                 if (container === void 0) { container = sourceFile; }
117148                 return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); });
117149             }
117150             function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) {
117151                 if (container === void 0) { container = sourceFile; }
117152                 var positions = [];
117153                 /// TODO: Cache symbol existence for files to save text search
117154                 // Also, need to make this work for unicode escapes.
117155                 // Be resilient in the face of a symbol with no name or zero length name
117156                 if (!symbolName || !symbolName.length) {
117157                     return positions;
117158                 }
117159                 var text = sourceFile.text;
117160                 var sourceLength = text.length;
117161                 var symbolNameLength = symbolName.length;
117162                 var position = text.indexOf(symbolName, container.pos);
117163                 while (position >= 0) {
117164                     // If we are past the end, stop looking
117165                     if (position > container.end)
117166                         break;
117167                     // We found a match.  Make sure it's not part of a larger word (i.e. the char
117168                     // before and after it have to be a non-identifier char).
117169                     var endPosition = position + symbolNameLength;
117170                     if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */)) &&
117171                         (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */))) {
117172                         // Found a real match.  Keep searching.
117173                         positions.push(position);
117174                     }
117175                     position = text.indexOf(symbolName, position + symbolNameLength + 1);
117176                 }
117177                 return positions;
117178             }
117179             function getLabelReferencesInNode(container, targetLabel) {
117180                 var sourceFile = container.getSourceFile();
117181                 var labelName = targetLabel.text;
117182                 var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) {
117183                     // Only pick labels that are either the target label, or have a target that is the target label
117184                     return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? nodeEntry(node) : undefined;
117185                 });
117186                 return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }];
117187             }
117188             function isValidReferencePosition(node, searchSymbolName) {
117189                 // Compare the length so we filter out strict superstrings of the symbol we are looking for
117190                 switch (node.kind) {
117191                     case 76 /* PrivateIdentifier */:
117192                     case 75 /* Identifier */:
117193                         return node.text.length === searchSymbolName.length;
117194                     case 14 /* NoSubstitutionTemplateLiteral */:
117195                     case 10 /* StringLiteral */: {
117196                         var str = node;
117197                         return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || (ts.isCallExpression(node.parent) && ts.isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) &&
117198                             str.text.length === searchSymbolName.length;
117199                     }
117200                     case 8 /* NumericLiteral */:
117201                         return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length;
117202                     case 84 /* DefaultKeyword */:
117203                         return "default".length === searchSymbolName.length;
117204                     default:
117205                         return false;
117206                 }
117207             }
117208             function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter) {
117209                 var references = ts.flatMap(sourceFiles, function (sourceFile) {
117210                     cancellationToken.throwIfCancellationRequested();
117211                     return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) {
117212                         if (referenceLocation.kind === keywordKind && (!filter || filter(referenceLocation))) {
117213                             return nodeEntry(referenceLocation);
117214                         }
117215                     });
117216                 });
117217                 return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined;
117218             }
117219             function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) {
117220                 if (addReferencesHere === void 0) { addReferencesHere = true; }
117221                 state.cancellationToken.throwIfCancellationRequested();
117222                 return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere);
117223             }
117224             /**
117225              * Search within node "container" for references for a search value, where the search value is defined as a
117226              * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
117227              * searchLocation: a node where the search value
117228              */
117229             function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) {
117230                 if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) {
117231                     return;
117232                 }
117233                 for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) {
117234                     var position = _a[_i];
117235                     getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
117236                 }
117237             }
117238             function hasMatchingMeaning(referenceLocation, state) {
117239                 return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
117240             }
117241             function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
117242                 var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
117243                 if (!isValidReferencePosition(referenceLocation, search.text)) {
117244                     // This wasn't the start of a token.  Check to see if it might be a
117245                     // match in a comment or string if that's what the caller is asking
117246                     // for.
117247                     if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) {
117248                         // In the case where we're looking inside comments/strings, we don't have
117249                         // an actual definition.  So just use 'undefined' here.  Features like
117250                         // 'Rename' won't care (as they ignore the definitions), and features like
117251                         // 'FindReferences' will just filter out these results.
117252                         state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length));
117253                     }
117254                     return;
117255                 }
117256                 if (!hasMatchingMeaning(referenceLocation, state))
117257                     return;
117258                 var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
117259                 if (!referenceSymbol) {
117260                     return;
117261                 }
117262                 var parent = referenceLocation.parent;
117263                 if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) {
117264                     // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again.
117265                     return;
117266                 }
117267                 if (ts.isExportSpecifier(parent)) {
117268                     ts.Debug.assert(referenceLocation.kind === 75 /* Identifier */);
117269                     getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere);
117270                     return;
117271                 }
117272                 var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
117273                 if (!relatedSymbol) {
117274                     getReferenceForShorthandProperty(referenceSymbol, search, state);
117275                     return;
117276                 }
117277                 switch (state.specialSearchKind) {
117278                     case 0 /* None */:
117279                         if (addReferencesHere)
117280                             addReference(referenceLocation, relatedSymbol, state);
117281                         break;
117282                     case 1 /* Constructor */:
117283                         addConstructorReferences(referenceLocation, sourceFile, search, state);
117284                         break;
117285                     case 2 /* Class */:
117286                         addClassStaticThisReferences(referenceLocation, search, state);
117287                         break;
117288                     default:
117289                         ts.Debug.assertNever(state.specialSearchKind);
117290                 }
117291                 getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
117292             }
117293             function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) {
117294                 ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled");
117295                 var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
117296                 var exportDeclaration = parent.parent;
117297                 var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
117298                 if (!alwaysGetReferences && !search.includes(localSymbol)) {
117299                     return;
117300                 }
117301                 if (!propertyName) {
117302                     // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export)
117303                     if (!(state.options.use === 2 /* Rename */ && (name.escapedText === "default" /* Default */))) {
117304                         addRef();
117305                     }
117306                 }
117307                 else if (referenceLocation === propertyName) {
117308                     // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export.
117309                     // For `export { foo as bar };`, where `foo` is a local, so add it now.
117310                     if (!exportDeclaration.moduleSpecifier) {
117311                         addRef();
117312                     }
117313                     if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) {
117314                         addReference(name, ts.Debug.checkDefined(exportSpecifier.symbol), state);
117315                     }
117316                 }
117317                 else {
117318                     if (state.markSeenReExportRHS(referenceLocation)) {
117319                         addRef();
117320                     }
117321                 }
117322                 // For `export { foo as bar }`, rename `foo`, but not `bar`.
117323                 if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
117324                     var isDefaultExport = referenceLocation.originalKeywordKind === 84 /* DefaultKeyword */
117325                         || exportSpecifier.name.originalKeywordKind === 84 /* DefaultKeyword */;
117326                     var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
117327                     var exportSymbol = ts.Debug.checkDefined(exportSpecifier.symbol);
117328                     var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker);
117329                     if (exportInfo) {
117330                         searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
117331                     }
117332                 }
117333                 // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
117334                 if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) {
117335                     var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
117336                     if (imported)
117337                         searchForImportedSymbol(imported, state);
117338                 }
117339                 function addRef() {
117340                     if (addReferencesHere)
117341                         addReference(referenceLocation, localSymbol, state);
117342                 }
117343             }
117344             function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
117345                 return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol;
117346             }
117347             function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
117348                 var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
117349                 ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation);
117350                 if (propertyName) {
117351                     // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol.
117352                     return propertyName === referenceLocation;
117353                 }
117354                 else {
117355                     // `export { foo } from "foo"` is a re-export.
117356                     // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`.
117357                     return !parent.parent.moduleSpecifier;
117358                 }
117359             }
117360             function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
117361                 var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
117362                 if (!importOrExport)
117363                     return;
117364                 var symbol = importOrExport.symbol;
117365                 if (importOrExport.kind === 0 /* Import */) {
117366                     if (!(isForRenameWithPrefixAndSuffixText(state.options))) {
117367                         searchForImportedSymbol(symbol, state);
117368                     }
117369                 }
117370                 else {
117371                     searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
117372                 }
117373             }
117374             function getReferenceForShorthandProperty(_a, search, state) {
117375                 var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
117376                 var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
117377                 var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration);
117378                 /*
117379                 * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
117380                 * has two meanings: property name and property value. Therefore when we do findAllReference at the position where
117381                 * an identifier is declared, the language service should return the position of the variable declaration as well as
117382                 * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
117383                 * position of property accessing, the referenceEntry of such position will be handled in the first case.
117384                 */
117385                 if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
117386                     addReference(name, shorthandValueSymbol, state);
117387                 }
117388             }
117389             function addReference(referenceLocation, relatedSymbol, state) {
117390                 var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; // eslint-disable-line no-in-operator
117391                 var addRef = state.referenceAdder(symbol);
117392                 if (state.options.implementations) {
117393                     addImplementationReferences(referenceLocation, addRef, state);
117394                 }
117395                 else {
117396                     addRef(referenceLocation, kind);
117397                 }
117398             }
117399             /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses.  */
117400             function addConstructorReferences(referenceLocation, sourceFile, search, state) {
117401                 if (ts.isNewExpressionTarget(referenceLocation)) {
117402                     addReference(referenceLocation, search.symbol, state);
117403                 }
117404                 var pusher = function () { return state.referenceAdder(search.symbol); };
117405                 if (ts.isClassLike(referenceLocation.parent)) {
117406                     ts.Debug.assert(referenceLocation.kind === 84 /* DefaultKeyword */ || referenceLocation.parent.name === referenceLocation);
117407                     // This is the class declaration containing the constructor.
117408                     findOwnConstructorReferences(search.symbol, sourceFile, pusher());
117409                 }
117410                 else {
117411                     // If this class appears in `extends C`, then the extending class' "super" calls are references.
117412                     var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
117413                     if (classExtending) {
117414                         findSuperConstructorAccesses(classExtending, pusher());
117415                         findInheritedConstructorReferences(classExtending, state);
117416                     }
117417                 }
117418             }
117419             function addClassStaticThisReferences(referenceLocation, search, state) {
117420                 addReference(referenceLocation, search.symbol, state);
117421                 var classLike = referenceLocation.parent;
117422                 if (state.options.use === 2 /* Rename */ || !ts.isClassLike(classLike))
117423                     return;
117424                 ts.Debug.assert(classLike.name === referenceLocation);
117425                 var addRef = state.referenceAdder(search.symbol);
117426                 for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) {
117427                     var member = _a[_i];
117428                     if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) {
117429                         continue;
117430                     }
117431                     if (member.body) {
117432                         member.body.forEachChild(function cb(node) {
117433                             if (node.kind === 104 /* ThisKeyword */) {
117434                                 addRef(node);
117435                             }
117436                             else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
117437                                 node.forEachChild(cb);
117438                             }
117439                         });
117440                     }
117441                 }
117442             }
117443             /**
117444              * `classSymbol` is the class where the constructor was defined.
117445              * Reference the constructor and all calls to `new this()`.
117446              */
117447             function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
117448                 var constructorSymbol = getClassConstructorSymbol(classSymbol);
117449                 if (constructorSymbol && constructorSymbol.declarations) {
117450                     for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
117451                         var decl = _a[_i];
117452                         var ctrKeyword = ts.findChildOfKind(decl, 129 /* ConstructorKeyword */, sourceFile);
117453                         ts.Debug.assert(decl.kind === 162 /* Constructor */ && !!ctrKeyword);
117454                         addNode(ctrKeyword);
117455                     }
117456                 }
117457                 if (classSymbol.exports) {
117458                     classSymbol.exports.forEach(function (member) {
117459                         var decl = member.valueDeclaration;
117460                         if (decl && decl.kind === 161 /* MethodDeclaration */) {
117461                             var body = decl.body;
117462                             if (body) {
117463                                 forEachDescendantOfKind(body, 104 /* ThisKeyword */, function (thisKeyword) {
117464                                     if (ts.isNewExpressionTarget(thisKeyword)) {
117465                                         addNode(thisKeyword);
117466                                     }
117467                                 });
117468                             }
117469                         }
117470                     });
117471                 }
117472             }
117473             function getClassConstructorSymbol(classSymbol) {
117474                 return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
117475             }
117476             /** Find references to `super` in the constructor of an extending class.  */
117477             function findSuperConstructorAccesses(classDeclaration, addNode) {
117478                 var constructor = getClassConstructorSymbol(classDeclaration.symbol);
117479                 if (!(constructor && constructor.declarations)) {
117480                     return;
117481                 }
117482                 for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
117483                     var decl = _a[_i];
117484                     ts.Debug.assert(decl.kind === 162 /* Constructor */);
117485                     var body = decl.body;
117486                     if (body) {
117487                         forEachDescendantOfKind(body, 102 /* SuperKeyword */, function (node) {
117488                             if (ts.isCallExpressionTarget(node)) {
117489                                 addNode(node);
117490                             }
117491                         });
117492                     }
117493                 }
117494             }
117495             function hasOwnConstructor(classDeclaration) {
117496                 return !!getClassConstructorSymbol(classDeclaration.symbol);
117497             }
117498             function findInheritedConstructorReferences(classDeclaration, state) {
117499                 if (hasOwnConstructor(classDeclaration))
117500                     return;
117501                 var classSymbol = classDeclaration.symbol;
117502                 var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
117503                 getReferencesInContainerOrFiles(classSymbol, state, search);
117504             }
117505             function addImplementationReferences(refNode, addReference, state) {
117506                 // Check if we found a function/propertyAssignment/method with an implementation or initializer
117507                 if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
117508                     addReference(refNode);
117509                     return;
117510                 }
117511                 if (refNode.kind !== 75 /* Identifier */) {
117512                     return;
117513                 }
117514                 if (refNode.parent.kind === 282 /* ShorthandPropertyAssignment */) {
117515                     // Go ahead and dereference the shorthand assignment by going to its definition
117516                     getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference);
117517                 }
117518                 // Check if the node is within an extends or implements clause
117519                 var containingClass = getContainingClassIfInHeritageClause(refNode);
117520                 if (containingClass) {
117521                     addReference(containingClass);
117522                     return;
117523                 }
117524                 // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface
117525                 // Find the first node whose parent isn't a type node -- i.e., the highest type node.
117526                 var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); });
117527                 var typeHavingNode = typeNode.parent;
117528                 if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) {
117529                     if (ts.hasInitializer(typeHavingNode)) {
117530                         addIfImplementation(typeHavingNode.initializer);
117531                     }
117532                     else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) {
117533                         var body = typeHavingNode.body;
117534                         if (body.kind === 223 /* Block */) {
117535                             ts.forEachReturnStatement(body, function (returnStatement) {
117536                                 if (returnStatement.expression)
117537                                     addIfImplementation(returnStatement.expression);
117538                             });
117539                         }
117540                         else {
117541                             addIfImplementation(body);
117542                         }
117543                     }
117544                     else if (ts.isAssertionExpression(typeHavingNode)) {
117545                         addIfImplementation(typeHavingNode.expression);
117546                     }
117547                 }
117548                 function addIfImplementation(e) {
117549                     if (isImplementationExpression(e))
117550                         addReference(e);
117551                 }
117552             }
117553             function getContainingClassIfInHeritageClause(node) {
117554                 return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent)
117555                     : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined;
117556             }
117557             /**
117558              * Returns true if this is an expression that can be considered an implementation
117559              */
117560             function isImplementationExpression(node) {
117561                 switch (node.kind) {
117562                     case 200 /* ParenthesizedExpression */:
117563                         return isImplementationExpression(node.expression);
117564                     case 202 /* ArrowFunction */:
117565                     case 201 /* FunctionExpression */:
117566                     case 193 /* ObjectLiteralExpression */:
117567                     case 214 /* ClassExpression */:
117568                     case 192 /* ArrayLiteralExpression */:
117569                         return true;
117570                     default:
117571                         return false;
117572                 }
117573             }
117574             /**
117575              * Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol
117576              * is an interface, determines if some ancestor of the child symbol extends or inherits from it.
117577              * Also takes in a cache of previous results which makes this slightly more efficient and is
117578              * necessary to avoid potential loops like so:
117579              *     class A extends B { }
117580              *     class B extends A { }
117581              *
117582              * We traverse the AST rather than using the type checker because users are typically only interested
117583              * in explicit implementations of an interface/class when calling "Go to Implementation". Sibling
117584              * implementations of types that share a common ancestor with the type whose implementation we are
117585              * searching for need to be filtered out of the results. The type checker doesn't let us make the
117586              * distinction between structurally compatible implementations and explicit implementations, so we
117587              * must use the AST.
117588              *
117589              * @param symbol         A class or interface Symbol
117590              * @param parent        Another class or interface Symbol
117591              * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results
117592              */
117593             function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) {
117594                 if (symbol === parent) {
117595                     return true;
117596                 }
117597                 var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent);
117598                 var cached = cachedResults.get(key);
117599                 if (cached !== undefined) {
117600                     return cached;
117601                 }
117602                 // Set the key so that we don't infinitely recurse
117603                 cachedResults.set(key, false);
117604                 var inherits = !!symbol.declarations && symbol.declarations.some(function (declaration) {
117605                     return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) {
117606                         var type = checker.getTypeAtLocation(typeReference);
117607                         return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker);
117608                     });
117609                 });
117610                 cachedResults.set(key, inherits);
117611                 return inherits;
117612             }
117613             function getReferencesForSuperKeyword(superKeyword) {
117614                 var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false);
117615                 if (!searchSpaceNode) {
117616                     return undefined;
117617                 }
117618                 // Whether 'super' occurs in a static context within a class.
117619                 var staticFlag = 32 /* Static */;
117620                 switch (searchSpaceNode.kind) {
117621                     case 159 /* PropertyDeclaration */:
117622                     case 158 /* PropertySignature */:
117623                     case 161 /* MethodDeclaration */:
117624                     case 160 /* MethodSignature */:
117625                     case 162 /* Constructor */:
117626                     case 163 /* GetAccessor */:
117627                     case 164 /* SetAccessor */:
117628                         staticFlag &= ts.getModifierFlags(searchSpaceNode);
117629                         searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
117630                         break;
117631                     default:
117632                         return undefined;
117633                 }
117634                 var sourceFile = searchSpaceNode.getSourceFile();
117635                 var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) {
117636                     if (node.kind !== 102 /* SuperKeyword */) {
117637                         return;
117638                     }
117639                     var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
117640                     // If we have a 'super' container, we must have an enclosing class.
117641                     // Now make sure the owning class is the same as the search-space
117642                     // and has the same static qualifier as the original 'super's owner.
117643                     return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : undefined;
117644                 });
117645                 return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }];
117646             }
117647             function isParameterName(node) {
117648                 return node.kind === 75 /* Identifier */ && node.parent.kind === 156 /* Parameter */ && node.parent.name === node;
117649             }
117650             function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
117651                 var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
117652                 // Whether 'this' occurs in a static context within a class.
117653                 var staticFlag = 32 /* Static */;
117654                 switch (searchSpaceNode.kind) {
117655                     case 161 /* MethodDeclaration */:
117656                     case 160 /* MethodSignature */:
117657                         if (ts.isObjectLiteralMethod(searchSpaceNode)) {
117658                             break;
117659                         }
117660                     // falls through
117661                     case 159 /* PropertyDeclaration */:
117662                     case 158 /* PropertySignature */:
117663                     case 162 /* Constructor */:
117664                     case 163 /* GetAccessor */:
117665                     case 164 /* SetAccessor */:
117666                         staticFlag &= ts.getModifierFlags(searchSpaceNode);
117667                         searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
117668                         break;
117669                     case 290 /* SourceFile */:
117670                         if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
117671                             return undefined;
117672                         }
117673                     // falls through
117674                     case 244 /* FunctionDeclaration */:
117675                     case 201 /* FunctionExpression */:
117676                         break;
117677                     // Computed properties in classes are not handled here because references to this are illegal,
117678                     // so there is no point finding references to them.
117679                     default:
117680                         return undefined;
117681                 }
117682                 var references = ts.flatMap(searchSpaceNode.kind === 290 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
117683                     cancellationToken.throwIfCancellationRequested();
117684                     return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
117685                         if (!ts.isThis(node)) {
117686                             return false;
117687                         }
117688                         var container = ts.getThisContainer(node, /* includeArrowFunctions */ false);
117689                         switch (searchSpaceNode.kind) {
117690                             case 201 /* FunctionExpression */:
117691                             case 244 /* FunctionDeclaration */:
117692                                 return searchSpaceNode.symbol === container.symbol;
117693                             case 161 /* MethodDeclaration */:
117694                             case 160 /* MethodSignature */:
117695                                 return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
117696                             case 214 /* ClassExpression */:
117697                             case 245 /* ClassDeclaration */:
117698                                 // Make sure the container belongs to the same class
117699                                 // and has the appropriate static modifier from the original container.
117700                                 return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
117701                             case 290 /* SourceFile */:
117702                                 return container.kind === 290 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
117703                         }
117704                     });
117705                 }).map(function (n) { return nodeEntry(n); });
117706                 var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; });
117707                 return [{
117708                         definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword },
117709                         references: references
117710                     }];
117711             }
117712             function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
117713                 var references = ts.flatMap(sourceFiles, function (sourceFile) {
117714                     cancellationToken.throwIfCancellationRequested();
117715                     return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) {
117716                         return ts.isStringLiteral(ref) && ref.text === node.text ? nodeEntry(ref, 2 /* StringLiteral */) : undefined;
117717                     });
117718                 });
117719                 return [{
117720                         definition: { type: 4 /* String */, node: node },
117721                         references: references
117722                     }];
117723             }
117724             // For certain symbol kinds, we need to include other symbols in the search set.
117725             // This is not needed when searching for re-exports.
117726             function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) {
117727                 var result = [];
117728                 forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); }, 
117729                 /*allowBaseTypes*/ function () { return !implementations; });
117730                 return result;
117731             }
117732             function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) {
117733                 var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location);
117734                 if (containingObjectLiteralElement) {
117735                     /* Because in short-hand property assignment, location has two meaning : property name and as value of the property
117736                     * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of
117737                     * property name and variable declaration of the identifier.
117738                     * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service
117739                     * should show both 'name' in 'obj' and 'name' in variable declaration
117740                     *      const name = "Foo";
117741                     *      const obj = { name };
117742                     * 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
117743                     * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration
117744                     * will be included correctly.
117745                     */
117746                     var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol
117747                     if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) {
117748                         // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property.
117749                         return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */);
117750                     }
117751                     // If the location is in a context sensitive location (i.e. in an object literal) try
117752                     // to get a contextual type for it, and add the property symbol from the contextual
117753                     // type to the search set
117754                     var contextualType = checker.getContextualType(containingObjectLiteralElement.parent);
117755                     var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); });
117756                     if (res_1)
117757                         return res_1;
117758                     // If the location is name of property symbol from object literal destructuring pattern
117759                     // Search the property symbol
117760                     //      for ( { property: p2 } of elems) { }
117761                     var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
117762                     var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */);
117763                     if (res1)
117764                         return res1;
117765                     var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */);
117766                     if (res2)
117767                         return res2;
117768                 }
117769                 var aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker);
117770                 if (aliasedSymbol) {
117771                     // In case of UMD module and global merging, search for global as well
117772                     var res_2 = cbSymbol(aliasedSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 1 /* Node */);
117773                     if (res_2)
117774                         return res_2;
117775                 }
117776                 var res = fromRoot(symbol);
117777                 if (res)
117778                     return res;
117779                 if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) {
117780                     // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property).
117781                     var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name);
117782                     ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property]
117783                     return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]);
117784                 }
117785                 var exportSpecifier = ts.getDeclarationOfKind(symbol, 263 /* ExportSpecifier */);
117786                 if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) {
117787                     var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
117788                     if (localSymbol) {
117789                         var res_3 = cbSymbol(localSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 1 /* Node */);
117790                         if (res_3)
117791                             return res_3;
117792                     }
117793                 }
117794                 // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property.
117795                 // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local.
117796                 if (!isForRenamePopulateSearchSymbolSet) {
117797                     var bindingElementPropertySymbol = void 0;
117798                     if (onlyIncludeBindingElementAtReferenceLocation) {
117799                         bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined;
117800                     }
117801                     else {
117802                         bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
117803                     }
117804                     return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
117805                 }
117806                 ts.Debug.assert(isForRenamePopulateSearchSymbolSet);
117807                 // due to the above assert and the arguments at the uses of this function,
117808                 // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds
117809                 var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation;
117810                 if (includeOriginalSymbolOfBindingElement) {
117811                     var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
117812                     return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */);
117813                 }
117814                 function fromRoot(sym, kind) {
117815                     // If this is a union property:
117816                     //   - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types.
117817                     //   - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search.
117818                     // If the symbol is an instantiation from a another symbol (e.g. widened symbol):
117819                     //   - In populateSearchSymbolsSet, add the root the list
117820                     //   - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.)
117821                     return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) {
117822                         return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind)
117823                             // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
117824                             || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol)
117825                                 ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); })
117826                                 : undefined);
117827                     });
117828                 }
117829                 function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
117830                     var bindingElement = ts.getDeclarationOfKind(symbol, 191 /* BindingElement */);
117831                     if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) {
117832                         return ts.getPropertySymbolFromBindingElement(checker, bindingElement);
117833                     }
117834                 }
117835             }
117836             function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
117837                 var checker = state.checker;
117838                 return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, 
117839                 /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym)
117840                     // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol.
117841                     ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind }
117842                     : undefined; }, 
117843                 /*allowBaseTypes*/ function (rootSymbol) {
117844                     return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); }));
117845                 });
117846             }
117847             /**
117848              * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
117849              * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
117850              * then we need to widen the search to include type positions as well.
117851              * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated
117852              * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
117853              * do not intersect in any of the three spaces.
117854              */
117855             function getIntersectingMeaningFromDeclarations(node, symbol) {
117856                 var meaning = ts.getMeaningFromLocation(node);
117857                 var declarations = symbol.declarations;
117858                 if (declarations) {
117859                     var lastIterationMeaning = void 0;
117860                     do {
117861                         // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module]
117862                         // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module
117863                         // intersects with the class in the value space.
117864                         // To achieve that we will keep iterating until the result stabilizes.
117865                         // Remember the last meaning
117866                         lastIterationMeaning = meaning;
117867                         for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
117868                             var declaration = declarations_2[_i];
117869                             var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
117870                             if (declarationMeaning & meaning) {
117871                                 meaning |= declarationMeaning;
117872                             }
117873                         }
117874                     } while (meaning !== lastIterationMeaning);
117875                 }
117876                 return meaning;
117877             }
117878             Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations;
117879             function isImplementation(node) {
117880                 return !!(node.flags & 8388608 /* Ambient */) ? !(ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) :
117881                     (ts.isVariableLike(node) ? ts.hasInitializer(node) :
117882                         ts.isFunctionLikeDeclaration(node) ? !!node.body :
117883                             ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node));
117884             }
117885             function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) {
117886                 var refSymbol = checker.getSymbolAtLocation(node);
117887                 var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
117888                 if (shorthandSymbol) {
117889                     for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
117890                         var declaration = _a[_i];
117891                         if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
117892                             addReference(declaration);
117893                         }
117894                     }
117895                 }
117896             }
117897             Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
117898             function forEachDescendantOfKind(node, kind, action) {
117899                 ts.forEachChild(node, function (child) {
117900                     if (child.kind === kind) {
117901                         action(child);
117902                     }
117903                     forEachDescendantOfKind(child, kind, action);
117904                 });
117905             }
117906             /** 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. */
117907             function tryGetClassByExtendingIdentifier(node) {
117908                 return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent);
117909             }
117910             /**
117911              * If we are just looking for implementations and this is a property access expression, we need to get the
117912              * symbol of the local type of the symbol the property is being accessed on. This is because our search
117913              * symbol may have a different parent symbol if the local type's symbol does not declare the property
117914              * being accessed (i.e. it is declared in some parent class or interface)
117915              */
117916             function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
117917                 var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined;
117918                 var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
117919                 var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) {
117920                     return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined;
117921                 });
117922                 return res.length === 0 ? undefined : res;
117923             }
117924             function isForRenameWithPrefixAndSuffixText(options) {
117925                 return options.use === 2 /* Rename */ && options.providePrefixAndSuffixTextForRename;
117926             }
117927         })(Core = FindAllReferences.Core || (FindAllReferences.Core = {}));
117928     })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
117929 })(ts || (ts = {}));
117930 /* @internal */
117931 var ts;
117932 (function (ts) {
117933     var CallHierarchy;
117934     (function (CallHierarchy) {
117935         /** Indictates whether a node is named function or class expression. */
117936         function isNamedExpression(node) {
117937             return (ts.isFunctionExpression(node) || ts.isClassExpression(node)) && ts.isNamedDeclaration(node);
117938         }
117939         /** Indicates whether a node is a function, arrow, or class expression assigned to a constant variable. */
117940         function isConstNamedExpression(node) {
117941             return (ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node))
117942                 && ts.isVariableDeclaration(node.parent)
117943                 && node === node.parent.initializer
117944                 && ts.isIdentifier(node.parent.name)
117945                 && !!(ts.getCombinedNodeFlags(node.parent) & 2 /* Const */);
117946         }
117947         /**
117948          * Indicates whether a node could possibly be a call hierarchy declaration.
117949          *
117950          * See `resolveCallHierarchyDeclaration` for the specific rules.
117951          */
117952         function isPossibleCallHierarchyDeclaration(node) {
117953             return ts.isSourceFile(node)
117954                 || ts.isModuleDeclaration(node)
117955                 || ts.isFunctionDeclaration(node)
117956                 || ts.isFunctionExpression(node)
117957                 || ts.isClassDeclaration(node)
117958                 || ts.isClassExpression(node)
117959                 || ts.isMethodDeclaration(node)
117960                 || ts.isMethodSignature(node)
117961                 || ts.isGetAccessorDeclaration(node)
117962                 || ts.isSetAccessorDeclaration(node);
117963         }
117964         /**
117965          * Indicates whether a node is a valid a call hierarchy declaration.
117966          *
117967          * See `resolveCallHierarchyDeclaration` for the specific rules.
117968          */
117969         function isValidCallHierarchyDeclaration(node) {
117970             return ts.isSourceFile(node)
117971                 || ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)
117972                 || ts.isFunctionDeclaration(node)
117973                 || ts.isClassDeclaration(node)
117974                 || ts.isMethodDeclaration(node)
117975                 || ts.isMethodSignature(node)
117976                 || ts.isGetAccessorDeclaration(node)
117977                 || ts.isSetAccessorDeclaration(node)
117978                 || isNamedExpression(node)
117979                 || isConstNamedExpression(node);
117980         }
117981         /** Gets the node that can be used as a reference to a call hierarchy declaration. */
117982         function getCallHierarchyDeclarationReferenceNode(node) {
117983             if (ts.isSourceFile(node))
117984                 return node;
117985             if (ts.isNamedDeclaration(node))
117986                 return node.name;
117987             if (isConstNamedExpression(node))
117988                 return node.parent.name;
117989             return ts.Debug.checkDefined(node.modifiers && ts.find(node.modifiers, isDefaultModifier));
117990         }
117991         function isDefaultModifier(node) {
117992             return node.kind === 84 /* DefaultKeyword */;
117993         }
117994         /** Gets the symbol for a call hierarchy declaration. */
117995         function getSymbolOfCallHierarchyDeclaration(typeChecker, node) {
117996             var location = getCallHierarchyDeclarationReferenceNode(node);
117997             return location && typeChecker.getSymbolAtLocation(location);
117998         }
117999         /** Gets the text and range for the name of a call hierarchy declaration. */
118000         function getCallHierarchyItemName(program, node) {
118001             if (ts.isSourceFile(node)) {
118002                 return { text: node.fileName, pos: 0, end: 0 };
118003             }
118004             if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && !ts.isNamedDeclaration(node)) {
118005                 var defaultModifier = node.modifiers && ts.find(node.modifiers, isDefaultModifier);
118006                 if (defaultModifier) {
118007                     return { text: "default", pos: defaultModifier.getStart(), end: defaultModifier.getEnd() };
118008                 }
118009             }
118010             var declName = isConstNamedExpression(node) ? node.parent.name :
118011                 ts.Debug.checkDefined(ts.getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
118012             var text = ts.isIdentifier(declName) ? ts.idText(declName) :
118013                 ts.isStringOrNumericLiteralLike(declName) ? declName.text :
118014                     ts.isComputedPropertyName(declName) ?
118015                         ts.isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text :
118016                             undefined :
118017                         undefined;
118018             if (text === undefined) {
118019                 var typeChecker = program.getTypeChecker();
118020                 var symbol = typeChecker.getSymbolAtLocation(declName);
118021                 if (symbol) {
118022                     text = typeChecker.symbolToString(symbol, node);
118023                 }
118024             }
118025             if (text === undefined) {
118026                 // get the text from printing the node on a single line without comments...
118027                 var printer_1 = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
118028                 text = ts.usingSingleLineStringWriter(function (writer) { return printer_1.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer); });
118029             }
118030             return { text: text, pos: declName.getStart(), end: declName.getEnd() };
118031         }
118032         function findImplementation(typeChecker, node) {
118033             if (node.body) {
118034                 return node;
118035             }
118036             if (ts.isConstructorDeclaration(node)) {
118037                 return ts.getFirstConstructorWithBody(node.parent);
118038             }
118039             if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
118040                 var symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
118041                 if (symbol && symbol.valueDeclaration && ts.isFunctionLikeDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.body) {
118042                     return symbol.valueDeclaration;
118043                 }
118044                 return undefined;
118045             }
118046             return node;
118047         }
118048         function findAllInitialDeclarations(typeChecker, node) {
118049             var symbol = getSymbolOfCallHierarchyDeclaration(typeChecker, node);
118050             var declarations;
118051             if (symbol && symbol.declarations) {
118052                 var indices = ts.indicesOf(symbol.declarations);
118053                 var keys_1 = ts.map(symbol.declarations, function (decl) { return ({ file: decl.getSourceFile().fileName, pos: decl.pos }); });
118054                 indices.sort(function (a, b) { return ts.compareStringsCaseSensitive(keys_1[a].file, keys_1[b].file) || keys_1[a].pos - keys_1[b].pos; });
118055                 var sortedDeclarations = ts.map(indices, function (i) { return symbol.declarations[i]; });
118056                 var lastDecl = void 0;
118057                 for (var _i = 0, sortedDeclarations_1 = sortedDeclarations; _i < sortedDeclarations_1.length; _i++) {
118058                     var decl = sortedDeclarations_1[_i];
118059                     if (isValidCallHierarchyDeclaration(decl)) {
118060                         if (!lastDecl || lastDecl.parent !== decl.parent || lastDecl.end !== decl.pos) {
118061                             declarations = ts.append(declarations, decl);
118062                         }
118063                         lastDecl = decl;
118064                     }
118065                 }
118066             }
118067             return declarations;
118068         }
118069         /** Find the implementation or the first declaration for a call hierarchy declaration. */
118070         function findImplementationOrAllInitialDeclarations(typeChecker, node) {
118071             var _a, _b, _c;
118072             if (ts.isFunctionLikeDeclaration(node)) {
118073                 return (_b = (_a = findImplementation(typeChecker, node)) !== null && _a !== void 0 ? _a : findAllInitialDeclarations(typeChecker, node)) !== null && _b !== void 0 ? _b : node;
118074             }
118075             return (_c = findAllInitialDeclarations(typeChecker, node)) !== null && _c !== void 0 ? _c : node;
118076         }
118077         /** Resolves the call hierarchy declaration for a node. */
118078         function resolveCallHierarchyDeclaration(program, location) {
118079             // A call hierarchy item must refer to either a SourceFile, Module Declaration, or something intrinsically callable that has a name:
118080             // - Class Declarations
118081             // - Class Expressions (with a name)
118082             // - Function Declarations
118083             // - Function Expressions (with a name or assigned to a const variable)
118084             // - Arrow Functions (assigned to a const variable)
118085             // - Constructors
118086             // - Methods
118087             // - Accessors
118088             //
118089             // If a call is contained in a non-named callable Node (function expression, arrow function, etc.), then
118090             // its containing `CallHierarchyItem` is a containing function or SourceFile that matches the above list.
118091             var typeChecker = program.getTypeChecker();
118092             var followingSymbol = false;
118093             while (true) {
118094                 if (isValidCallHierarchyDeclaration(location)) {
118095                     return findImplementationOrAllInitialDeclarations(typeChecker, location);
118096                 }
118097                 if (isPossibleCallHierarchyDeclaration(location)) {
118098                     var ancestor = ts.findAncestor(location, isValidCallHierarchyDeclaration);
118099                     return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
118100                 }
118101                 if (ts.isDeclarationName(location)) {
118102                     if (isValidCallHierarchyDeclaration(location.parent)) {
118103                         return findImplementationOrAllInitialDeclarations(typeChecker, location.parent);
118104                     }
118105                     if (isPossibleCallHierarchyDeclaration(location.parent)) {
118106                         var ancestor = ts.findAncestor(location.parent, isValidCallHierarchyDeclaration);
118107                         return ancestor && findImplementationOrAllInitialDeclarations(typeChecker, ancestor);
118108                     }
118109                     if (ts.isVariableDeclaration(location.parent) && location.parent.initializer && isConstNamedExpression(location.parent.initializer)) {
118110                         return location.parent.initializer;
118111                     }
118112                     return undefined;
118113                 }
118114                 if (ts.isConstructorDeclaration(location)) {
118115                     if (isValidCallHierarchyDeclaration(location.parent)) {
118116                         return location.parent;
118117                     }
118118                     return undefined;
118119                 }
118120                 if (!followingSymbol) {
118121                     var symbol = typeChecker.getSymbolAtLocation(location);
118122                     if (symbol) {
118123                         if (symbol.flags & 2097152 /* Alias */) {
118124                             symbol = typeChecker.getAliasedSymbol(symbol);
118125                         }
118126                         if (symbol.valueDeclaration) {
118127                             followingSymbol = true;
118128                             location = symbol.valueDeclaration;
118129                             continue;
118130                         }
118131                     }
118132                 }
118133                 return undefined;
118134             }
118135         }
118136         CallHierarchy.resolveCallHierarchyDeclaration = resolveCallHierarchyDeclaration;
118137         /** Creates a `CallHierarchyItem` for a call hierarchy declaration. */
118138         function createCallHierarchyItem(program, node) {
118139             var sourceFile = node.getSourceFile();
118140             var name = getCallHierarchyItemName(program, node);
118141             var kind = ts.getNodeKind(node);
118142             var span = ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, node.getFullStart(), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true), node.getEnd());
118143             var selectionSpan = ts.createTextSpanFromBounds(name.pos, name.end);
118144             return { file: sourceFile.fileName, kind: kind, name: name.text, span: span, selectionSpan: selectionSpan };
118145         }
118146         CallHierarchy.createCallHierarchyItem = createCallHierarchyItem;
118147         function isDefined(x) {
118148             return x !== undefined;
118149         }
118150         function convertEntryToCallSite(entry) {
118151             if (entry.kind === 1 /* Node */) {
118152                 var node = entry.node;
118153                 if (ts.isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
118154                     || ts.isTaggedTemplateTag(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
118155                     || ts.isDecoratorTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
118156                     || ts.isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true)
118157                     || ts.isRightSideOfPropertyAccess(node)
118158                     || ts.isArgumentExpressionOfElementAccess(node)) {
118159                     var sourceFile = node.getSourceFile();
118160                     var ancestor = ts.findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile;
118161                     return { declaration: ancestor, range: ts.createTextRangeFromNode(node, sourceFile) };
118162                 }
118163             }
118164         }
118165         function getCallSiteGroupKey(entry) {
118166             return "" + ts.getNodeId(entry.declaration);
118167         }
118168         function createCallHierarchyIncomingCall(from, fromSpans) {
118169             return { from: from, fromSpans: fromSpans };
118170         }
118171         function convertCallSiteGroupToIncomingCall(program, entries) {
118172             return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, function (entry) { return ts.createTextSpanFromRange(entry.range); }));
118173         }
118174         /** Gets the call sites that call into the provided call hierarchy declaration. */
118175         function getIncomingCalls(program, declaration, cancellationToken) {
118176             // Source files and modules have no incoming calls.
118177             if (ts.isSourceFile(declaration) || ts.isModuleDeclaration(declaration)) {
118178                 return [];
118179             }
118180             var location = getCallHierarchyDeclarationReferenceNode(declaration);
118181             var calls = ts.filter(ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, program.getSourceFiles(), location, /*position*/ 0, { use: 1 /* References */ }, convertEntryToCallSite), isDefined);
118182             return calls ? ts.group(calls, getCallSiteGroupKey, function (entries) { return convertCallSiteGroupToIncomingCall(program, entries); }) : [];
118183         }
118184         CallHierarchy.getIncomingCalls = getIncomingCalls;
118185         function createCallSiteCollector(program, callSites) {
118186             function recordCallSite(node) {
118187                 var target = ts.isTaggedTemplateExpression(node) ? node.tag :
118188                     ts.isJsxOpeningLikeElement(node) ? node.tagName :
118189                         ts.isAccessExpression(node) ? node :
118190                             node.expression;
118191                 var declaration = resolveCallHierarchyDeclaration(program, target);
118192                 if (declaration) {
118193                     var range = ts.createTextRangeFromNode(target, node.getSourceFile());
118194                     if (ts.isArray(declaration)) {
118195                         for (var _i = 0, declaration_1 = declaration; _i < declaration_1.length; _i++) {
118196                             var decl = declaration_1[_i];
118197                             callSites.push({ declaration: decl, range: range });
118198                         }
118199                     }
118200                     else {
118201                         callSites.push({ declaration: declaration, range: range });
118202                     }
118203                 }
118204             }
118205             function collect(node) {
118206                 if (!node)
118207                     return;
118208                 if (node.flags & 8388608 /* Ambient */) {
118209                     // do not descend into ambient nodes.
118210                     return;
118211                 }
118212                 if (isValidCallHierarchyDeclaration(node)) {
118213                     // do not descend into other call site declarations, other than class member names
118214                     if (ts.isClassLike(node)) {
118215                         for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
118216                             var member = _a[_i];
118217                             if (member.name && ts.isComputedPropertyName(member.name)) {
118218                                 collect(member.name.expression);
118219                             }
118220                         }
118221                     }
118222                     return;
118223                 }
118224                 switch (node.kind) {
118225                     case 75 /* Identifier */:
118226                     case 253 /* ImportEqualsDeclaration */:
118227                     case 254 /* ImportDeclaration */:
118228                     case 260 /* ExportDeclaration */:
118229                     case 246 /* InterfaceDeclaration */:
118230                     case 247 /* TypeAliasDeclaration */:
118231                         // do not descend into nodes that cannot contain callable nodes
118232                         return;
118233                     case 199 /* TypeAssertionExpression */:
118234                     case 217 /* AsExpression */:
118235                         // do not descend into the type side of an assertion
118236                         collect(node.expression);
118237                         return;
118238                     case 242 /* VariableDeclaration */:
118239                     case 156 /* Parameter */:
118240                         // do not descend into the type of a variable or parameter declaration
118241                         collect(node.name);
118242                         collect(node.initializer);
118243                         return;
118244                     case 196 /* CallExpression */:
118245                         // do not descend into the type arguments of a call expression
118246                         recordCallSite(node);
118247                         collect(node.expression);
118248                         ts.forEach(node.arguments, collect);
118249                         return;
118250                     case 197 /* NewExpression */:
118251                         // do not descend into the type arguments of a new expression
118252                         recordCallSite(node);
118253                         collect(node.expression);
118254                         ts.forEach(node.arguments, collect);
118255                         return;
118256                     case 198 /* TaggedTemplateExpression */:
118257                         // do not descend into the type arguments of a tagged template expression
118258                         recordCallSite(node);
118259                         collect(node.tag);
118260                         collect(node.template);
118261                         return;
118262                     case 268 /* JsxOpeningElement */:
118263                     case 267 /* JsxSelfClosingElement */:
118264                         // do not descend into the type arguments of a JsxOpeningLikeElement
118265                         recordCallSite(node);
118266                         collect(node.tagName);
118267                         collect(node.attributes);
118268                         return;
118269                     case 157 /* Decorator */:
118270                         recordCallSite(node);
118271                         collect(node.expression);
118272                         return;
118273                     case 194 /* PropertyAccessExpression */:
118274                     case 195 /* ElementAccessExpression */:
118275                         recordCallSite(node);
118276                         ts.forEachChild(node, collect);
118277                         break;
118278                 }
118279                 if (ts.isPartOfTypeNode(node)) {
118280                     // do not descend into types
118281                     return;
118282                 }
118283                 ts.forEachChild(node, collect);
118284             }
118285             return collect;
118286         }
118287         function collectCallSitesOfSourceFile(node, collect) {
118288             ts.forEach(node.statements, collect);
118289         }
118290         function collectCallSitesOfModuleDeclaration(node, collect) {
118291             if (!ts.hasModifier(node, 2 /* Ambient */) && node.body && ts.isModuleBlock(node.body)) {
118292                 ts.forEach(node.body.statements, collect);
118293             }
118294         }
118295         function collectCallSitesOfFunctionLikeDeclaration(typeChecker, node, collect) {
118296             var implementation = findImplementation(typeChecker, node);
118297             if (implementation) {
118298                 ts.forEach(implementation.parameters, collect);
118299                 collect(implementation.body);
118300             }
118301         }
118302         function collectCallSitesOfClassLikeDeclaration(node, collect) {
118303             ts.forEach(node.decorators, collect);
118304             var heritage = ts.getClassExtendsHeritageElement(node);
118305             if (heritage) {
118306                 collect(heritage.expression);
118307             }
118308             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
118309                 var member = _a[_i];
118310                 ts.forEach(member.decorators, collect);
118311                 if (ts.isPropertyDeclaration(member)) {
118312                     collect(member.initializer);
118313                 }
118314                 else if (ts.isConstructorDeclaration(member) && member.body) {
118315                     ts.forEach(member.parameters, collect);
118316                     collect(member.body);
118317                 }
118318             }
118319         }
118320         function collectCallSites(program, node) {
118321             var callSites = [];
118322             var collect = createCallSiteCollector(program, callSites);
118323             switch (node.kind) {
118324                 case 290 /* SourceFile */:
118325                     collectCallSitesOfSourceFile(node, collect);
118326                     break;
118327                 case 249 /* ModuleDeclaration */:
118328                     collectCallSitesOfModuleDeclaration(node, collect);
118329                     break;
118330                 case 244 /* FunctionDeclaration */:
118331                 case 201 /* FunctionExpression */:
118332                 case 202 /* ArrowFunction */:
118333                 case 161 /* MethodDeclaration */:
118334                 case 163 /* GetAccessor */:
118335                 case 164 /* SetAccessor */:
118336                     collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect);
118337                     break;
118338                 case 245 /* ClassDeclaration */:
118339                 case 214 /* ClassExpression */:
118340                     collectCallSitesOfClassLikeDeclaration(node, collect);
118341                     break;
118342                 default:
118343                     ts.Debug.assertNever(node);
118344             }
118345             return callSites;
118346         }
118347         function createCallHierarchyOutgoingCall(to, fromSpans) {
118348             return { to: to, fromSpans: fromSpans };
118349         }
118350         function convertCallSiteGroupToOutgoingCall(program, entries) {
118351             return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, function (entry) { return ts.createTextSpanFromRange(entry.range); }));
118352         }
118353         /** Gets the call sites that call out of the provided call hierarchy declaration. */
118354         function getOutgoingCalls(program, declaration) {
118355             if (declaration.flags & 8388608 /* Ambient */ || ts.isMethodSignature(declaration)) {
118356                 return [];
118357             }
118358             return ts.group(collectCallSites(program, declaration), getCallSiteGroupKey, function (entries) { return convertCallSiteGroupToOutgoingCall(program, entries); });
118359         }
118360         CallHierarchy.getOutgoingCalls = getOutgoingCalls;
118361     })(CallHierarchy = ts.CallHierarchy || (ts.CallHierarchy = {}));
118362 })(ts || (ts = {}));
118363 /* @internal */
118364 var ts;
118365 (function (ts) {
118366     function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) {
118367         var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
118368         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
118369         var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper);
118370         var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
118371         return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, function (changeTracker) {
118372             updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
118373             updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
118374         });
118375     }
118376     ts.getEditsForFileRename = getEditsForFileRename;
118377     // exported for tests
118378     function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) {
118379         var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
118380         return function (path) {
118381             var originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 });
118382             var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path);
118383             return originalPath
118384                 ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName)
118385                 : updatedPath;
118386         };
118387         function getUpdatedPath(pathToUpdate) {
118388             if (getCanonicalFileName(pathToUpdate) === canonicalOldPath)
118389                 return newFileOrDirPath;
118390             var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName);
118391             return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix;
118392         }
118393     }
118394     ts.getPathUpdater = getPathUpdater;
118395     // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1.
118396     function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) {
118397         var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName);
118398         return combinePathsSafe(ts.getDirectoryPath(a1), rel);
118399     }
118400     function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) {
118401         var configFile = program.getCompilerOptions().configFile;
118402         if (!configFile)
118403             return;
118404         var configDir = ts.getDirectoryPath(configFile.fileName);
118405         var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
118406         if (!jsonObjectLiteral)
118407             return;
118408         forEachProperty(jsonObjectLiteral, function (property, propertyName) {
118409             switch (propertyName) {
118410                 case "files":
118411                 case "include":
118412                 case "exclude": {
118413                     var foundExactMatch = updatePaths(property);
118414                     if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) {
118415                         var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; });
118416                         var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory);
118417                         // If there isn't some include for this, add a new one.
118418                         if (ts.getRegexFromPattern(ts.Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) &&
118419                             !ts.getRegexFromPattern(ts.Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
118420                             changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath)));
118421                         }
118422                     }
118423                     break;
118424                 }
118425                 case "compilerOptions":
118426                     forEachProperty(property.initializer, function (property, propertyName) {
118427                         var option = ts.getOptionFromName(propertyName);
118428                         if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) {
118429                             updatePaths(property);
118430                         }
118431                         else if (propertyName === "paths") {
118432                             forEachProperty(property.initializer, function (pathsProperty) {
118433                                 if (!ts.isArrayLiteralExpression(pathsProperty.initializer))
118434                                     return;
118435                                 for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) {
118436                                     var e = _a[_i];
118437                                     tryUpdateString(e);
118438                                 }
118439                             });
118440                         }
118441                     });
118442                     break;
118443             }
118444         });
118445         function updatePaths(property) {
118446             // Type annotation needed due to #7294
118447             var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
118448             var foundExactMatch = false;
118449             for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
118450                 var element = elements_1[_i];
118451                 foundExactMatch = tryUpdateString(element) || foundExactMatch;
118452             }
118453             return foundExactMatch;
118454         }
118455         function tryUpdateString(element) {
118456             if (!ts.isStringLiteral(element))
118457                 return false;
118458             var elementFileName = combinePathsSafe(configDir, element.text);
118459             var updated = oldToNew(elementFileName);
118460             if (updated !== undefined) {
118461                 changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated));
118462                 return true;
118463             }
118464             return false;
118465         }
118466         function relativePath(path) {
118467             return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames);
118468         }
118469     }
118470     function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
118471         var allFiles = program.getSourceFiles();
118472         var _loop_4 = function (sourceFile) {
118473             var newFromOld = oldToNew(sourceFile.path);
118474             var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
118475             var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
118476             var oldFromNew = newToOld(sourceFile.fileName);
118477             var oldImportFromPath = oldFromNew || sourceFile.fileName;
118478             var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath);
118479             var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined;
118480             updateImportsWorker(sourceFile, changeTracker, function (referenceText) {
118481                 if (!ts.pathIsRelative(referenceText))
118482                     return undefined;
118483                 var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText);
118484                 var newAbsolute = oldToNew(oldAbsolute);
118485                 return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
118486             }, function (importLiteral) {
118487                 var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
118488                 // No need to update if it's an ambient module^M
118489                 if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); }))
118490                     return undefined;
118491                 var toImport = oldFromNew !== undefined
118492                     // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
118493                     // TODO:GH#18217
118494                     ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles)
118495                     : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
118496                 // Need an update if the imported file moved, or the importing file moved and was using a relative path.
118497                 return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
118498                     ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text)
118499                     : undefined;
118500             });
118501         };
118502         for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
118503             var sourceFile = allFiles_1[_i];
118504             _loop_4(sourceFile);
118505         }
118506     }
118507     function combineNormal(pathA, pathB) {
118508         return ts.normalizePath(ts.combinePaths(pathA, pathB));
118509     }
118510     function combinePathsSafe(pathA, pathB) {
118511         return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB));
118512     }
118513     function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
118514         if (importedModuleSymbol) {
118515             // `find` should succeed because we checked for ambient modules before calling this function.
118516             var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName;
118517             var newFileName = oldToNew(oldFileName);
118518             return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true };
118519         }
118520         else {
118521             var resolved = host.resolveModuleNames
118522                 ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName)
118523                 : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName);
118524             return getSourceFileToImportFromResolved(resolved, oldToNew, program.getSourceFiles());
118525         }
118526     }
118527     function getSourceFileToImportFromResolved(resolved, oldToNew, sourceFiles) {
118528         // Search through all locations looking for a moved file, and only then test already existing files.
118529         // 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.
118530         if (!resolved)
118531             return undefined;
118532         // First try resolved module
118533         if (resolved.resolvedModule) {
118534             var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
118535             if (result_2)
118536                 return result_2;
118537         }
118538         // Then failed lookups that are in the list of sources
118539         var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting)
118540             // Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
118541             || ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
118542         if (result)
118543             return result;
118544         // If nothing changed, then result is resolved module file thats not updated
118545         return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false };
118546         function tryChangeWithIgnoringPackageJsonExisting(oldFileName) {
118547             var newFileName = oldToNew(oldFileName);
118548             return newFileName && ts.find(sourceFiles, function (src) { return src.fileName === newFileName; })
118549                 ? tryChangeWithIgnoringPackageJson(oldFileName) : undefined;
118550         }
118551         function tryChangeWithIgnoringPackageJson(oldFileName) {
118552             return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined;
118553         }
118554         function tryChange(oldFileName) {
118555             var newFileName = oldToNew(oldFileName);
118556             return newFileName && { newFileName: newFileName, updated: true };
118557         }
118558     }
118559     function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) {
118560         for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162
118561             var ref = _a[_i];
118562             var updated = updateRef(ref.fileName);
118563             if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end))
118564                 changeTracker.replaceRangeWithText(sourceFile, ref, updated);
118565         }
118566         for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) {
118567             var importStringLiteral = _c[_b];
118568             var updated = updateImport(importStringLiteral);
118569             if (updated !== undefined && updated !== importStringLiteral.text)
118570                 changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated);
118571         }
118572     }
118573     function createStringRange(node, sourceFile) {
118574         return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1);
118575     }
118576     function forEachProperty(objectLiteral, cb) {
118577         if (!ts.isObjectLiteralExpression(objectLiteral))
118578             return;
118579         for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) {
118580             var property = _a[_i];
118581             if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) {
118582                 cb(property, property.name.text);
118583             }
118584         }
118585     }
118586 })(ts || (ts = {}));
118587 /* @internal */
118588 var ts;
118589 (function (ts) {
118590     var GoToDefinition;
118591     (function (GoToDefinition) {
118592         function getDefinitionAtPosition(program, sourceFile, position) {
118593             var reference = getReferenceAtPosition(sourceFile, position, program);
118594             if (reference) {
118595                 return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)];
118596             }
118597             var node = ts.getTouchingPropertyName(sourceFile, position);
118598             if (node === sourceFile) {
118599                 return undefined;
118600             }
118601             var parent = node.parent;
118602             var typeChecker = program.getTypeChecker();
118603             // Labels
118604             if (ts.isJumpStatementTarget(node)) {
118605                 var label = ts.getTargetLabel(node.parent, node.text);
118606                 return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217
118607             }
118608             var symbol = getSymbol(node, typeChecker);
118609             // Could not find a symbol e.g. node is string or number keyword,
118610             // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
118611             if (!symbol) {
118612                 return getDefinitionInfoForIndexSignatures(node, typeChecker);
118613             }
118614             var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
118615             // Don't go to the component constructor definition for a JSX element, just go to the component definition.
118616             if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) {
118617                 var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
118618                 // For a function, if this is the original function definition, return just sigInfo.
118619                 // If this is the original constructor definition, parent is the class.
118620                 if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) ||
118621                     // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias
118622                     symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) {
118623                     return [sigInfo];
118624                 }
118625                 else {
118626                     var defs = getDefinitionFromSymbol(typeChecker, symbol, node, calledDeclaration) || ts.emptyArray;
118627                     // For a 'super()' call, put the signature first, else put the variable first.
118628                     return node.kind === 102 /* SuperKeyword */ ? __spreadArrays([sigInfo], defs) : __spreadArrays(defs, [sigInfo]);
118629                 }
118630             }
118631             // Because name in short-hand property assignment has two different meanings: property name and property value,
118632             // using go-to-definition at such position should go to the variable declaration of the property value rather than
118633             // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
118634             // is performed at the location of property access, we would like to go to definition of the property in the short-hand
118635             // assignment. This case and others are handled by the following code.
118636             if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
118637                 var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
118638                 return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : [];
118639             }
118640             // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the
118641             // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern
118642             // and return the property declaration for the referenced property.
118643             // For example:
118644             //      import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo"
118645             //
118646             //      function bar<T>(onfulfilled: (value: T) => void) { //....}
118647             //      interface Test {
118648             //          pr/*destination*/op1: number
118649             //      }
118650             //      bar<Test>(({pr/*goto*/op1})=>{});
118651             if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
118652                 (node === (parent.propertyName || parent.name))) {
118653                 var name_3 = ts.getNameFromPropertyName(node);
118654                 var type = typeChecker.getTypeAtLocation(parent.parent);
118655                 return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
118656                     var prop = t.getProperty(name_3);
118657                     return prop && getDefinitionFromSymbol(typeChecker, prop, node);
118658                 });
118659             }
118660             // If the current location we want to find its definition is in an object literal, try to get the contextual type for the
118661             // object literal, lookup the property symbol in the contextual type, and use this for goto-definition.
118662             // For example
118663             //      interface Props{
118664             //          /*first*/prop1: number
118665             //          prop2: boolean
118666             //      }
118667             //      function Foo(arg: Props) {}
118668             //      Foo( { pr/*1*/op1: 10, prop2: true })
118669             var element = ts.getContainingObjectLiteralElement(node);
118670             if (element) {
118671                 var contextualType = element && typeChecker.getContextualType(element.parent);
118672                 if (contextualType) {
118673                     return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) {
118674                         return getDefinitionFromSymbol(typeChecker, propertySymbol, node);
118675                     });
118676                 }
118677             }
118678             return getDefinitionFromSymbol(typeChecker, symbol, node);
118679         }
118680         GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition;
118681         /**
118682          * True if we should not add definitions for both the signature symbol and the definition symbol.
118683          * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`.
118684          */
118685         function symbolMatchesSignature(s, calledDeclaration) {
118686             return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent ||
118687                 !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
118688         }
118689         function getReferenceAtPosition(sourceFile, position, program) {
118690             var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
118691             if (referencePath) {
118692                 var file = program.getSourceFileFromReference(sourceFile, referencePath);
118693                 return file && { fileName: referencePath.fileName, file: file };
118694             }
118695             var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
118696             if (typeReferenceDirective) {
118697                 var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
118698                 var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217
118699                 return file && { fileName: typeReferenceDirective.fileName, file: file };
118700             }
118701             var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position);
118702             if (libReferenceDirective) {
118703                 var file = program.getLibFileFromReference(libReferenceDirective);
118704                 return file && { fileName: libReferenceDirective.fileName, file: file };
118705             }
118706             return undefined;
118707         }
118708         GoToDefinition.getReferenceAtPosition = getReferenceAtPosition;
118709         /// Goto type
118710         function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) {
118711             var node = ts.getTouchingPropertyName(sourceFile, position);
118712             if (node === sourceFile) {
118713                 return undefined;
118714             }
118715             var symbol = typeChecker.getSymbolAtLocation(node);
118716             if (!symbol)
118717                 return undefined;
118718             var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
118719             var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker);
118720             var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node);
118721             // If a function returns 'void' or some other type with no definition, just return the function definition.
118722             return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node);
118723         }
118724         GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition;
118725         function definitionFromType(type, checker, node) {
118726             return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) {
118727                 return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node);
118728             });
118729         }
118730         function tryGetReturnTypeOfFunction(symbol, type, checker) {
118731             // If the type is just a function's inferred type,
118732             // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway.
118733             if (type.symbol === symbol ||
118734                 // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}`
118735                 symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) {
118736                 var sigs = type.getCallSignatures();
118737                 if (sigs.length === 1)
118738                     return checker.getReturnTypeOfSignature(ts.first(sigs));
118739             }
118740             return undefined;
118741         }
118742         function getDefinitionAndBoundSpan(program, sourceFile, position) {
118743             var definitions = getDefinitionAtPosition(program, sourceFile, position);
118744             if (!definitions || definitions.length === 0) {
118745                 return undefined;
118746             }
118747             // Check if position is on triple slash reference.
118748             var comment = findReferenceInPosition(sourceFile.referencedFiles, position) ||
118749                 findReferenceInPosition(sourceFile.typeReferenceDirectives, position) ||
118750                 findReferenceInPosition(sourceFile.libReferenceDirectives, position);
118751             if (comment) {
118752                 return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) };
118753             }
118754             var node = ts.getTouchingPropertyName(sourceFile, position);
118755             var textSpan = ts.createTextSpan(node.getStart(), node.getWidth());
118756             return { definitions: definitions, textSpan: textSpan };
118757         }
118758         GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan;
118759         // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations.
118760         function getDefinitionInfoForIndexSignatures(node, checker) {
118761             if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node)
118762                 return;
118763             var type = checker.getTypeAtLocation(node.parent.expression);
118764             return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) {
118765                 var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */);
118766                 return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration);
118767             });
118768         }
118769         function getSymbol(node, checker) {
118770             var symbol = checker.getSymbolAtLocation(node);
118771             // If this is an alias, and the request came at the declaration location
118772             // get the aliased symbol instead. This allows for goto def on an import e.g.
118773             //   import {A, B} from "mod";
118774             // to jump to the implementation directly.
118775             if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) {
118776                 var aliased = checker.getAliasedSymbol(symbol);
118777                 if (aliased.declarations) {
118778                     return aliased;
118779                 }
118780             }
118781             if (symbol && ts.isInJSFile(node)) {
118782                 var requireCall = ts.forEach(symbol.declarations, function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true) ? d.initializer : undefined; });
118783                 if (requireCall) {
118784                     var moduleSymbol = checker.getSymbolAtLocation(requireCall.arguments[0]);
118785                     if (moduleSymbol) {
118786                         return checker.resolveExternalModuleSymbol(moduleSymbol);
118787                     }
118788                 }
118789             }
118790             return symbol;
118791         }
118792         // Go to the original declaration for cases:
118793         //
118794         //   (1) when the aliased symbol was declared in the location(parent).
118795         //   (2) when the aliased symbol is originating from an import.
118796         //
118797         function shouldSkipAlias(node, declaration) {
118798             if (node.kind !== 75 /* Identifier */) {
118799                 return false;
118800             }
118801             if (node.parent === declaration) {
118802                 return true;
118803             }
118804             switch (declaration.kind) {
118805                 case 255 /* ImportClause */:
118806                 case 253 /* ImportEqualsDeclaration */:
118807                     return true;
118808                 case 258 /* ImportSpecifier */:
118809                     return declaration.parent.kind === 257 /* NamedImports */;
118810                 default:
118811                     return false;
118812             }
118813         }
118814         function getDefinitionFromSymbol(typeChecker, symbol, node, declarationNode) {
118815             // There are cases when you extend a function by adding properties to it afterwards,
118816             // we want to strip those extra properties.
118817             // For deduping purposes, we also want to exclude any declarationNodes if provided.
118818             var filteredDeclarations = ts.filter(symbol.declarations, function (d) { return d !== declarationNode && (!ts.isAssignmentDeclaration(d) || d === symbol.valueDeclaration); }) || undefined;
118819             return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(filteredDeclarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); });
118820             function getConstructSignatureDefinition() {
118821                 // Applicable only if we are in a new expression, or we are on a constructor declaration
118822                 // and in either case the symbol has a construct signature definition, i.e. class
118823                 if (symbol.flags & 32 /* Class */ && !(symbol.flags & (16 /* Function */ | 3 /* Variable */)) && (ts.isNewExpressionTarget(node) || node.kind === 129 /* ConstructorKeyword */)) {
118824                     var cls = ts.find(filteredDeclarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration");
118825                     return getSignatureDefinition(cls.members, /*selectConstructors*/ true);
118826                 }
118827             }
118828             function getCallSignatureDefinition() {
118829                 return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node)
118830                     ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ false)
118831                     : undefined;
118832             }
118833             function getSignatureDefinition(signatureDeclarations, selectConstructors) {
118834                 if (!signatureDeclarations) {
118835                     return undefined;
118836                 }
118837                 var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike);
118838                 var declarationsWithBody = declarations.filter(function (d) { return !!d.body; });
118839                 // declarations defined on the global scope can be defined on multiple files. Get all of them.
118840                 return declarations.length
118841                     ? declarationsWithBody.length !== 0
118842                         ? declarationsWithBody.map(function (x) { return createDefinitionInfo(x, typeChecker, symbol, node); })
118843                         : [createDefinitionInfo(ts.last(declarations), typeChecker, symbol, node)]
118844                     : undefined;
118845             }
118846         }
118847         /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
118848         function createDefinitionInfo(declaration, checker, symbol, node) {
118849             var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
118850             var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node);
118851             var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : "";
118852             return createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName, containerName);
118853         }
118854         /** Creates a DefinitionInfo directly from the name of a declaration. */
118855         function createDefinitionInfoFromName(checker, declaration, symbolKind, symbolName, containerName) {
118856             var name = ts.getNameOfDeclaration(declaration) || declaration;
118857             var sourceFile = name.getSourceFile();
118858             var textSpan = ts.createTextSpanFromNode(name, sourceFile);
118859             return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217
118860                 containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) });
118861         }
118862         function createDefinitionFromSignatureDeclaration(typeChecker, decl) {
118863             return createDefinitionInfo(decl, typeChecker, decl.symbol, decl);
118864         }
118865         function findReferenceInPosition(refs, pos) {
118866             return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); });
118867         }
118868         GoToDefinition.findReferenceInPosition = findReferenceInPosition;
118869         function getDefinitionInfoForFileReference(name, targetFileName) {
118870             return {
118871                 fileName: targetFileName,
118872                 textSpan: ts.createTextSpanFromBounds(0, 0),
118873                 kind: "script" /* scriptElement */,
118874                 name: name,
118875                 containerName: undefined,
118876                 containerKind: undefined,
118877             };
118878         }
118879         /** Returns a CallLikeExpression where `node` is the target being invoked. */
118880         function getAncestorCallLikeExpression(node) {
118881             var target = climbPastManyPropertyAccesses(node);
118882             var callLike = target.parent;
118883             return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined;
118884         }
118885         function climbPastManyPropertyAccesses(node) {
118886             return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node;
118887         }
118888         function tryGetSignatureDeclaration(typeChecker, node) {
118889             var callLike = getAncestorCallLikeExpression(node);
118890             var signature = callLike && typeChecker.getResolvedSignature(callLike);
118891             // Don't go to a function type, go to the value having that type.
118892             return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); });
118893         }
118894         function isConstructorLike(node) {
118895             switch (node.kind) {
118896                 case 162 /* Constructor */:
118897                 case 171 /* ConstructorType */:
118898                 case 166 /* ConstructSignature */:
118899                     return true;
118900                 default:
118901                     return false;
118902             }
118903         }
118904     })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
118905 })(ts || (ts = {}));
118906 /* @internal */
118907 var ts;
118908 (function (ts) {
118909     var JsDoc;
118910     (function (JsDoc) {
118911         var jsDocTagNames = [
118912             "abstract",
118913             "access",
118914             "alias",
118915             "argument",
118916             "async",
118917             "augments",
118918             "author",
118919             "borrows",
118920             "callback",
118921             "class",
118922             "classdesc",
118923             "constant",
118924             "constructor",
118925             "constructs",
118926             "copyright",
118927             "default",
118928             "deprecated",
118929             "description",
118930             "emits",
118931             "enum",
118932             "event",
118933             "example",
118934             "exports",
118935             "extends",
118936             "external",
118937             "field",
118938             "file",
118939             "fileoverview",
118940             "fires",
118941             "function",
118942             "generator",
118943             "global",
118944             "hideconstructor",
118945             "host",
118946             "ignore",
118947             "implements",
118948             "inheritdoc",
118949             "inner",
118950             "instance",
118951             "interface",
118952             "kind",
118953             "lends",
118954             "license",
118955             "listens",
118956             "member",
118957             "memberof",
118958             "method",
118959             "mixes",
118960             "module",
118961             "name",
118962             "namespace",
118963             "override",
118964             "package",
118965             "param",
118966             "private",
118967             "property",
118968             "protected",
118969             "public",
118970             "readonly",
118971             "requires",
118972             "returns",
118973             "see",
118974             "since",
118975             "static",
118976             "summary",
118977             "template",
118978             "this",
118979             "throws",
118980             "todo",
118981             "tutorial",
118982             "type",
118983             "typedef",
118984             "var",
118985             "variation",
118986             "version",
118987             "virtual",
118988             "yields"
118989         ];
118990         var jsDocTagNameCompletionEntries;
118991         var jsDocTagCompletionEntries;
118992         function getJsDocCommentsFromDeclarations(declarations) {
118993             // Only collect doc comments from duplicate declarations once:
118994             // In case of a union property there might be same declaration multiple times
118995             // which only varies in type parameter
118996             // Eg. const a: Array<string> | Array<number>; a.length
118997             // The property length will have two declarations of property length coming
118998             // from Array<T> - Array<string> and Array<number>
118999             var documentationComment = [];
119000             ts.forEachUnique(declarations, function (declaration) {
119001                 for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) {
119002                     var comment = _a[_i].comment;
119003                     if (comment === undefined)
119004                         continue;
119005                     if (documentationComment.length) {
119006                         documentationComment.push(ts.lineBreakPart());
119007                     }
119008                     documentationComment.push(ts.textPart(comment));
119009                 }
119010             });
119011             return documentationComment;
119012         }
119013         JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
119014         function getCommentHavingNodes(declaration) {
119015             switch (declaration.kind) {
119016                 case 317 /* JSDocParameterTag */:
119017                 case 323 /* JSDocPropertyTag */:
119018                     return [declaration];
119019                 case 315 /* JSDocCallbackTag */:
119020                 case 322 /* JSDocTypedefTag */:
119021                     return [declaration, declaration.parent];
119022                 default:
119023                     return ts.getJSDocCommentsAndTags(declaration);
119024             }
119025         }
119026         function getJsDocTagsFromDeclarations(declarations) {
119027             // Only collect doc comments from duplicate declarations once.
119028             var tags = [];
119029             ts.forEachUnique(declarations, function (declaration) {
119030                 for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) {
119031                     var tag = _a[_i];
119032                     tags.push({ name: tag.tagName.text, text: getCommentText(tag) });
119033                 }
119034             });
119035             return tags;
119036         }
119037         JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations;
119038         function getCommentText(tag) {
119039             var comment = tag.comment;
119040             switch (tag.kind) {
119041                 case 308 /* JSDocImplementsTag */:
119042                     return withNode(tag.class);
119043                 case 307 /* JSDocAugmentsTag */:
119044                     return withNode(tag.class);
119045                 case 321 /* JSDocTemplateTag */:
119046                     return withList(tag.typeParameters);
119047                 case 320 /* JSDocTypeTag */:
119048                     return withNode(tag.typeExpression);
119049                 case 322 /* JSDocTypedefTag */:
119050                 case 315 /* JSDocCallbackTag */:
119051                 case 323 /* JSDocPropertyTag */:
119052                 case 317 /* JSDocParameterTag */:
119053                     var name = tag.name;
119054                     return name ? withNode(name) : comment;
119055                 default:
119056                     return comment;
119057             }
119058             function withNode(node) {
119059                 return addComment(node.getText());
119060             }
119061             function withList(list) {
119062                 return addComment(list.map(function (x) { return x.getText(); }).join(", "));
119063             }
119064             function addComment(s) {
119065                 return comment === undefined ? s : s + " " + comment;
119066             }
119067         }
119068         function getJSDocTagNameCompletions() {
119069             return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
119070                 return {
119071                     name: tagName,
119072                     kind: "keyword" /* keyword */,
119073                     kindModifiers: "",
119074                     sortText: "0",
119075                 };
119076             }));
119077         }
119078         JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions;
119079         JsDoc.getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
119080         function getJSDocTagCompletions() {
119081             return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
119082                 return {
119083                     name: "@" + tagName,
119084                     kind: "keyword" /* keyword */,
119085                     kindModifiers: "",
119086                     sortText: "0"
119087                 };
119088             }));
119089         }
119090         JsDoc.getJSDocTagCompletions = getJSDocTagCompletions;
119091         function getJSDocTagCompletionDetails(name) {
119092             return {
119093                 name: name,
119094                 kind: "" /* unknown */,
119095                 kindModifiers: "",
119096                 displayParts: [ts.textPart(name)],
119097                 documentation: ts.emptyArray,
119098                 tags: undefined,
119099                 codeActions: undefined,
119100             };
119101         }
119102         JsDoc.getJSDocTagCompletionDetails = getJSDocTagCompletionDetails;
119103         function getJSDocParameterNameCompletions(tag) {
119104             if (!ts.isIdentifier(tag.name)) {
119105                 return ts.emptyArray;
119106             }
119107             var nameThusFar = tag.name.text;
119108             var jsdoc = tag.parent;
119109             var fn = jsdoc.parent;
119110             if (!ts.isFunctionLike(fn))
119111                 return [];
119112             return ts.mapDefined(fn.parameters, function (param) {
119113                 if (!ts.isIdentifier(param.name))
119114                     return undefined;
119115                 var name = param.name.text;
119116                 if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217
119117                     || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) {
119118                     return undefined;
119119                 }
119120                 return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" };
119121             });
119122         }
119123         JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions;
119124         function getJSDocParameterNameCompletionDetails(name) {
119125             return {
119126                 name: name,
119127                 kind: "parameter" /* parameterElement */,
119128                 kindModifiers: "",
119129                 displayParts: [ts.textPart(name)],
119130                 documentation: ts.emptyArray,
119131                 tags: undefined,
119132                 codeActions: undefined,
119133             };
119134         }
119135         JsDoc.getJSDocParameterNameCompletionDetails = getJSDocParameterNameCompletionDetails;
119136         /**
119137          * Checks if position points to a valid position to add JSDoc comments, and if so,
119138          * returns the appropriate template. Otherwise returns an empty string.
119139          * Valid positions are
119140          *      - outside of comments, statements, and expressions, and
119141          *      - preceding a:
119142          *          - function/constructor/method declaration
119143          *          - class declarations
119144          *          - variable statements
119145          *          - namespace declarations
119146          *          - interface declarations
119147          *          - method signatures
119148          *          - type alias declarations
119149          *
119150          * Hosts should ideally check that:
119151          * - The line is all whitespace up to 'position' before performing the insertion.
119152          * - If the keystroke sequence "/\*\*" induced the call, we also check that the next
119153          * non-whitespace character is '*', which (approximately) indicates whether we added
119154          * the second '*' to complete an existing (JSDoc) comment.
119155          * @param fileName The file in which to perform the check.
119156          * @param position The (character-indexed) position in the file where the check should
119157          * be performed.
119158          */
119159         function getDocCommentTemplateAtPosition(newLine, sourceFile, position) {
119160             var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
119161             var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc);
119162             if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) {
119163                 // Non-empty comment already exists.
119164                 return undefined;
119165             }
119166             var tokenStart = tokenAtPos.getStart(sourceFile);
119167             // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.)
119168             if (!existingDocComment && tokenStart < position) {
119169                 return undefined;
119170             }
119171             var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos);
119172             if (!commentOwnerInfo) {
119173                 return undefined;
119174             }
119175             var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters;
119176             if (commentOwner.getStart(sourceFile) < position) {
119177                 return undefined;
119178             }
119179             if (!parameters || parameters.length === 0) {
119180                 // if there are no parameters, just complete to a single line JSDoc comment
119181                 var singleLineResult = "/** */";
119182                 return { newText: singleLineResult, caretOffset: 3 };
119183             }
119184             var indentationStr = getIndentationStringAtPosition(sourceFile, position);
119185             // A doc comment consists of the following
119186             // * The opening comment line
119187             // * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
119188             // * the '@param'-tagged lines
119189             // * TODO: other tags.
119190             // * the closing comment line
119191             // * if the caret was directly in front of the object, then we add an extra line and indentation.
119192             var preamble = "/**" + newLine + indentationStr + " * ";
119193             var result = preamble + newLine +
119194                 parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) +
119195                 indentationStr + " */" +
119196                 (tokenStart === position ? newLine + indentationStr : "");
119197             return { newText: result, caretOffset: preamble.length };
119198         }
119199         JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition;
119200         function getIndentationStringAtPosition(sourceFile, position) {
119201             var text = sourceFile.text;
119202             var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
119203             var pos = lineStart;
119204             for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++)
119205                 ;
119206             return text.slice(lineStart, pos);
119207         }
119208         function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
119209             return parameters.map(function (_a, i) {
119210                 var name = _a.name, dotDotDotToken = _a.dotDotDotToken;
119211                 var paramName = name.kind === 75 /* Identifier */ ? name.text : "param" + i;
119212                 var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : "";
119213                 return indentationStr + " * @param " + type + paramName + newLine;
119214             }).join("");
119215         }
119216         function getCommentOwnerInfo(tokenAtPos) {
119217             return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker);
119218         }
119219         function getCommentOwnerInfoWorker(commentOwner) {
119220             switch (commentOwner.kind) {
119221                 case 244 /* FunctionDeclaration */:
119222                 case 201 /* FunctionExpression */:
119223                 case 161 /* MethodDeclaration */:
119224                 case 162 /* Constructor */:
119225                 case 160 /* MethodSignature */:
119226                     var parameters = commentOwner.parameters;
119227                     return { commentOwner: commentOwner, parameters: parameters };
119228                 case 281 /* PropertyAssignment */:
119229                     return getCommentOwnerInfoWorker(commentOwner.initializer);
119230                 case 245 /* ClassDeclaration */:
119231                 case 246 /* InterfaceDeclaration */:
119232                 case 158 /* PropertySignature */:
119233                 case 248 /* EnumDeclaration */:
119234                 case 284 /* EnumMember */:
119235                 case 247 /* TypeAliasDeclaration */:
119236                     return { commentOwner: commentOwner };
119237                 case 225 /* VariableStatement */: {
119238                     var varStatement = commentOwner;
119239                     var varDeclarations = varStatement.declarationList.declarations;
119240                     var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
119241                         ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer)
119242                         : undefined;
119243                     return { commentOwner: commentOwner, parameters: parameters_1 };
119244                 }
119245                 case 290 /* SourceFile */:
119246                     return "quit";
119247                 case 249 /* ModuleDeclaration */:
119248                     // If in walking up the tree, we hit a a nested namespace declaration,
119249                     // then we must be somewhere within a dotted namespace name; however we don't
119250                     // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
119251                     return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
119252                 case 226 /* ExpressionStatement */:
119253                     return getCommentOwnerInfoWorker(commentOwner.expression);
119254                 case 209 /* BinaryExpression */: {
119255                     var be = commentOwner;
119256                     if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) {
119257                         return "quit";
119258                     }
119259                     var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray;
119260                     return { commentOwner: commentOwner, parameters: parameters_2 };
119261                 }
119262                 case 159 /* PropertyDeclaration */:
119263                     var init = commentOwner.initializer;
119264                     if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) {
119265                         return { commentOwner: commentOwner, parameters: init.parameters };
119266                     }
119267             }
119268         }
119269         /**
119270          * Digs into an an initializer or RHS operand of an assignment operation
119271          * to get the parameters of an apt signature corresponding to a
119272          * function expression or a class expression.
119273          *
119274          * @param rightHandSide the expression which may contain an appropriate set of parameters
119275          * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
119276          */
119277         function getParametersFromRightHandSideOfAssignment(rightHandSide) {
119278             while (rightHandSide.kind === 200 /* ParenthesizedExpression */) {
119279                 rightHandSide = rightHandSide.expression;
119280             }
119281             switch (rightHandSide.kind) {
119282                 case 201 /* FunctionExpression */:
119283                 case 202 /* ArrowFunction */:
119284                     return rightHandSide.parameters;
119285                 case 214 /* ClassExpression */: {
119286                     var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration);
119287                     return ctr ? ctr.parameters : ts.emptyArray;
119288                 }
119289             }
119290             return ts.emptyArray;
119291         }
119292     })(JsDoc = ts.JsDoc || (ts.JsDoc = {}));
119293 })(ts || (ts = {}));
119294 /* @internal */
119295 var ts;
119296 (function (ts) {
119297     var NavigateTo;
119298     (function (NavigateTo) {
119299         function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
119300             var patternMatcher = ts.createPatternMatcher(searchValue);
119301             if (!patternMatcher)
119302                 return ts.emptyArray;
119303             var rawItems = [];
119304             var _loop_5 = function (sourceFile) {
119305                 cancellationToken.throwIfCancellationRequested();
119306                 if (excludeDtsFiles && sourceFile.isDeclarationFile) {
119307                     return "continue";
119308                 }
119309                 sourceFile.getNamedDeclarations().forEach(function (declarations, name) {
119310                     getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems);
119311                 });
119312             };
119313             // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
119314             for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
119315                 var sourceFile = sourceFiles_4[_i];
119316                 _loop_5(sourceFile);
119317             }
119318             rawItems.sort(compareNavigateToItems);
119319             return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
119320         }
119321         NavigateTo.getNavigateToItems = getNavigateToItems;
119322         function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) {
119323             // First do a quick check to see if the name of the declaration matches the
119324             // last portion of the (possibly) dotted name they're searching for.
119325             var match = patternMatcher.getMatchForLastSegmentOfPattern(name);
119326             if (!match) {
119327                 return; // continue to next named declarations
119328             }
119329             for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
119330                 var declaration = declarations_3[_i];
119331                 if (!shouldKeepItem(declaration, checker))
119332                     continue;
119333                 if (patternMatcher.patternContainsDots) {
119334                     // If the pattern has dots in it, then also see if the declaration container matches as well.
119335                     var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
119336                     if (fullMatch) {
119337                         rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration });
119338                     }
119339                 }
119340                 else {
119341                     rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration });
119342                 }
119343             }
119344         }
119345         function shouldKeepItem(declaration, checker) {
119346             switch (declaration.kind) {
119347                 case 255 /* ImportClause */:
119348                 case 258 /* ImportSpecifier */:
119349                 case 253 /* ImportEqualsDeclaration */:
119350                     var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217
119351                     var imported = checker.getAliasedSymbol(importer);
119352                     return importer.escapedName !== imported.escapedName;
119353                 default:
119354                     return true;
119355             }
119356         }
119357         function tryAddSingleDeclarationName(declaration, containers) {
119358             var name = ts.getNameOfDeclaration(declaration);
119359             return !!name && (pushLiteral(name, containers) || name.kind === 154 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers));
119360         }
119361         // Only added the names of computed properties if they're simple dotted expressions, like:
119362         //
119363         //      [X.Y.Z]() { }
119364         function tryAddComputedPropertyName(expression, containers) {
119365             return pushLiteral(expression, containers)
119366                 || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers);
119367         }
119368         function pushLiteral(node, containers) {
119369             return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true);
119370         }
119371         function getContainers(declaration) {
119372             var containers = [];
119373             // First, if we started with a computed property name, then add all but the last
119374             // portion into the container array.
119375             var name = ts.getNameOfDeclaration(declaration);
119376             if (name && name.kind === 154 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) {
119377                 return ts.emptyArray;
119378             }
119379             // Don't include the last portion.
119380             containers.shift();
119381             // Now, walk up our containers, adding all their names to the container array.
119382             var container = ts.getContainerNode(declaration);
119383             while (container) {
119384                 if (!tryAddSingleDeclarationName(container, containers)) {
119385                     return ts.emptyArray;
119386                 }
119387                 container = ts.getContainerNode(container);
119388             }
119389             return containers.reverse();
119390         }
119391         function compareNavigateToItems(i1, i2) {
119392             // TODO(cyrusn): get the gamut of comparisons that VS already uses here.
119393             return ts.compareValues(i1.matchKind, i2.matchKind)
119394                 || ts.compareStringsCaseSensitiveUI(i1.name, i2.name);
119395         }
119396         function createNavigateToItem(rawItem) {
119397             var declaration = rawItem.declaration;
119398             var container = ts.getContainerNode(declaration);
119399             var containerName = container && ts.getNameOfDeclaration(container);
119400             return {
119401                 name: rawItem.name,
119402                 kind: ts.getNodeKind(declaration),
119403                 kindModifiers: ts.getNodeModifiers(declaration),
119404                 matchKind: ts.PatternMatchKind[rawItem.matchKind],
119405                 isCaseSensitive: rawItem.isCaseSensitive,
119406                 fileName: rawItem.fileName,
119407                 textSpan: ts.createTextSpanFromNode(declaration),
119408                 // TODO(jfreeman): What should be the containerName when the container has a computed name?
119409                 containerName: containerName ? containerName.text : "",
119410                 containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */,
119411             };
119412         }
119413     })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {}));
119414 })(ts || (ts = {}));
119415 /* @internal */
119416 var ts;
119417 (function (ts) {
119418     var NavigationBar;
119419     (function (NavigationBar) {
119420         var _a;
119421         /**
119422          * Matches all whitespace characters in a string. Eg:
119423          *
119424          * "app.
119425          *
119426          * onactivated"
119427          *
119428          * matches because of the newline, whereas
119429          *
119430          * "app.onactivated"
119431          *
119432          * does not match.
119433          */
119434         var whiteSpaceRegex = /\s+/g;
119435         /**
119436          * Maximum amount of characters to return
119437          * The amount was chosen arbitrarily.
119438          */
119439         var maxLength = 150;
119440         // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
119441         var curCancellationToken;
119442         var curSourceFile;
119443         /**
119444          * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion.
119445          * `parent` is the current parent and is *not* stored in parentsStack.
119446          * `startNode` sets a new parent and `endNode` returns to the previous parent.
119447          */
119448         var parentsStack = [];
119449         var parent;
119450         var trackedEs5ClassesStack = [];
119451         var trackedEs5Classes;
119452         // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
119453         var emptyChildItemArray = [];
119454         function getNavigationBarItems(sourceFile, cancellationToken) {
119455             curCancellationToken = cancellationToken;
119456             curSourceFile = sourceFile;
119457             try {
119458                 return ts.map(primaryNavBarMenuItems(rootNavigationBarNode(sourceFile)), convertToPrimaryNavBarMenuItem);
119459             }
119460             finally {
119461                 reset();
119462             }
119463         }
119464         NavigationBar.getNavigationBarItems = getNavigationBarItems;
119465         function getNavigationTree(sourceFile, cancellationToken) {
119466             curCancellationToken = cancellationToken;
119467             curSourceFile = sourceFile;
119468             try {
119469                 return convertToTree(rootNavigationBarNode(sourceFile));
119470             }
119471             finally {
119472                 reset();
119473             }
119474         }
119475         NavigationBar.getNavigationTree = getNavigationTree;
119476         function reset() {
119477             curSourceFile = undefined;
119478             curCancellationToken = undefined;
119479             parentsStack = [];
119480             parent = undefined;
119481             emptyChildItemArray = [];
119482         }
119483         function nodeText(node) {
119484             return cleanText(node.getText(curSourceFile));
119485         }
119486         function navigationBarNodeKind(n) {
119487             return n.node.kind;
119488         }
119489         function pushChild(parent, child) {
119490             if (parent.children) {
119491                 parent.children.push(child);
119492             }
119493             else {
119494                 parent.children = [child];
119495             }
119496         }
119497         function rootNavigationBarNode(sourceFile) {
119498             ts.Debug.assert(!parentsStack.length);
119499             var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 };
119500             parent = root;
119501             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
119502                 var statement = _a[_i];
119503                 addChildrenRecursively(statement);
119504             }
119505             endNode();
119506             ts.Debug.assert(!parent && !parentsStack.length);
119507             return root;
119508         }
119509         function addLeafNode(node, name) {
119510             pushChild(parent, emptyNavigationBarNode(node, name));
119511         }
119512         function emptyNavigationBarNode(node, name) {
119513             return {
119514                 node: node,
119515                 name: name || (ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined),
119516                 additionalNodes: undefined,
119517                 parent: parent,
119518                 children: undefined,
119519                 indent: parent.indent + 1
119520             };
119521         }
119522         function addTrackedEs5Class(name) {
119523             if (!trackedEs5Classes) {
119524                 trackedEs5Classes = ts.createMap();
119525             }
119526             trackedEs5Classes.set(name, true);
119527         }
119528         function endNestedNodes(depth) {
119529             for (var i = 0; i < depth; i++)
119530                 endNode();
119531         }
119532         function startNestedNodes(targetNode, entityName) {
119533             var names = [];
119534             while (!ts.isPropertyNameLiteral(entityName)) {
119535                 var name = ts.getNameOrArgument(entityName);
119536                 var nameText = ts.getElementOrPropertyAccessName(entityName);
119537                 entityName = entityName.expression;
119538                 if (nameText === "prototype" || ts.isPrivateIdentifier(name))
119539                     continue;
119540                 names.push(name);
119541             }
119542             names.push(entityName);
119543             for (var i = names.length - 1; i > 0; i--) {
119544                 var name = names[i];
119545                 startNode(targetNode, name);
119546             }
119547             return [names.length - 1, names[0]];
119548         }
119549         /**
119550          * Add a new level of NavigationBarNodes.
119551          * This pushes to the stack, so you must call `endNode` when you are done adding to this node.
119552          */
119553         function startNode(node, name) {
119554             var navNode = emptyNavigationBarNode(node, name);
119555             pushChild(parent, navNode);
119556             // Save the old parent
119557             parentsStack.push(parent);
119558             trackedEs5ClassesStack.push(trackedEs5Classes);
119559             parent = navNode;
119560         }
119561         /** Call after calling `startNode` and adding children to it. */
119562         function endNode() {
119563             if (parent.children) {
119564                 mergeChildren(parent.children, parent);
119565                 sortChildren(parent.children);
119566             }
119567             parent = parentsStack.pop();
119568             trackedEs5Classes = trackedEs5ClassesStack.pop();
119569         }
119570         function addNodeWithRecursiveChild(node, child, name) {
119571             startNode(node, name);
119572             addChildrenRecursively(child);
119573             endNode();
119574         }
119575         /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */
119576         function addChildrenRecursively(node) {
119577             var _a;
119578             curCancellationToken.throwIfCancellationRequested();
119579             if (!node || ts.isToken(node)) {
119580                 return;
119581             }
119582             switch (node.kind) {
119583                 case 162 /* Constructor */:
119584                     // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it.
119585                     var ctr = node;
119586                     addNodeWithRecursiveChild(ctr, ctr.body);
119587                     // Parameter properties are children of the class, not the constructor.
119588                     for (var _i = 0, _b = ctr.parameters; _i < _b.length; _i++) {
119589                         var param = _b[_i];
119590                         if (ts.isParameterPropertyDeclaration(param, ctr)) {
119591                             addLeafNode(param);
119592                         }
119593                     }
119594                     break;
119595                 case 161 /* MethodDeclaration */:
119596                 case 163 /* GetAccessor */:
119597                 case 164 /* SetAccessor */:
119598                 case 160 /* MethodSignature */:
119599                     if (!ts.hasDynamicName(node)) {
119600                         addNodeWithRecursiveChild(node, node.body);
119601                     }
119602                     break;
119603                 case 159 /* PropertyDeclaration */:
119604                 case 158 /* PropertySignature */:
119605                     if (!ts.hasDynamicName(node)) {
119606                         addLeafNode(node);
119607                     }
119608                     break;
119609                 case 255 /* ImportClause */:
119610                     var importClause = node;
119611                     // Handle default import case e.g.:
119612                     //    import d from "mod";
119613                     if (importClause.name) {
119614                         addLeafNode(importClause.name);
119615                     }
119616                     // Handle named bindings in imports e.g.:
119617                     //    import * as NS from "mod";
119618                     //    import {a, b as B} from "mod";
119619                     var namedBindings = importClause.namedBindings;
119620                     if (namedBindings) {
119621                         if (namedBindings.kind === 256 /* NamespaceImport */) {
119622                             addLeafNode(namedBindings);
119623                         }
119624                         else {
119625                             for (var _c = 0, _d = namedBindings.elements; _c < _d.length; _c++) {
119626                                 var element = _d[_c];
119627                                 addLeafNode(element);
119628                             }
119629                         }
119630                     }
119631                     break;
119632                 case 282 /* ShorthandPropertyAssignment */:
119633                     addNodeWithRecursiveChild(node, node.name);
119634                     break;
119635                 case 283 /* SpreadAssignment */:
119636                     var expression = node.expression;
119637                     // Use the expression as the name of the SpreadAssignment, otherwise show as <unknown>.
119638                     ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node);
119639                     break;
119640                 case 191 /* BindingElement */:
119641                 case 281 /* PropertyAssignment */:
119642                 case 242 /* VariableDeclaration */:
119643                     var _e = node, name = _e.name, initializer = _e.initializer;
119644                     if (ts.isBindingPattern(name)) {
119645                         addChildrenRecursively(name);
119646                     }
119647                     else if (initializer && isFunctionOrClassExpression(initializer)) {
119648                         // Add a node for the VariableDeclaration, but not for the initializer.
119649                         startNode(node);
119650                         ts.forEachChild(initializer, addChildrenRecursively);
119651                         endNode();
119652                     }
119653                     else {
119654                         addNodeWithRecursiveChild(node, initializer);
119655                     }
119656                     break;
119657                 case 244 /* FunctionDeclaration */:
119658                     var nameNode = node.name;
119659                     // If we see a function declaration track as a possible ES5 class
119660                     if (nameNode && ts.isIdentifier(nameNode)) {
119661                         addTrackedEs5Class(nameNode.text);
119662                     }
119663                     addNodeWithRecursiveChild(node, node.body);
119664                     break;
119665                 case 202 /* ArrowFunction */:
119666                 case 201 /* FunctionExpression */:
119667                     addNodeWithRecursiveChild(node, node.body);
119668                     break;
119669                 case 248 /* EnumDeclaration */:
119670                     startNode(node);
119671                     for (var _f = 0, _g = node.members; _f < _g.length; _f++) {
119672                         var member = _g[_f];
119673                         if (!isComputedProperty(member)) {
119674                             addLeafNode(member);
119675                         }
119676                     }
119677                     endNode();
119678                     break;
119679                 case 245 /* ClassDeclaration */:
119680                 case 214 /* ClassExpression */:
119681                 case 246 /* InterfaceDeclaration */:
119682                     startNode(node);
119683                     for (var _h = 0, _j = node.members; _h < _j.length; _h++) {
119684                         var member = _j[_h];
119685                         addChildrenRecursively(member);
119686                     }
119687                     endNode();
119688                     break;
119689                 case 249 /* ModuleDeclaration */:
119690                     addNodeWithRecursiveChild(node, getInteriorModule(node).body);
119691                     break;
119692                 case 259 /* ExportAssignment */:
119693                 case 263 /* ExportSpecifier */:
119694                 case 253 /* ImportEqualsDeclaration */:
119695                 case 167 /* IndexSignature */:
119696                 case 165 /* CallSignature */:
119697                 case 166 /* ConstructSignature */:
119698                 case 247 /* TypeAliasDeclaration */:
119699                     addLeafNode(node);
119700                     break;
119701                 case 196 /* CallExpression */:
119702                 case 209 /* BinaryExpression */: {
119703                     var special = ts.getAssignmentDeclarationKind(node);
119704                     switch (special) {
119705                         case 1 /* ExportsProperty */:
119706                         case 2 /* ModuleExports */:
119707                             addNodeWithRecursiveChild(node, node.right);
119708                             return;
119709                         case 6 /* Prototype */:
119710                         case 3 /* PrototypeProperty */: {
119711                             var binaryExpression = node;
119712                             var assignmentTarget = binaryExpression.left;
119713                             var prototypeAccess = special === 3 /* PrototypeProperty */ ?
119714                                 assignmentTarget.expression :
119715                                 assignmentTarget;
119716                             var depth = 0;
119717                             var className = void 0;
119718                             // If we see a prototype assignment, start tracking the target as a class
119719                             // This is only done for simple classes not nested assignments.
119720                             if (ts.isIdentifier(prototypeAccess.expression)) {
119721                                 addTrackedEs5Class(prototypeAccess.expression.text);
119722                                 className = prototypeAccess.expression;
119723                             }
119724                             else {
119725                                 _a = startNestedNodes(binaryExpression, prototypeAccess.expression), depth = _a[0], className = _a[1];
119726                             }
119727                             if (special === 6 /* Prototype */) {
119728                                 if (ts.isObjectLiteralExpression(binaryExpression.right)) {
119729                                     if (binaryExpression.right.properties.length > 0) {
119730                                         startNode(binaryExpression, className);
119731                                         ts.forEachChild(binaryExpression.right, addChildrenRecursively);
119732                                         endNode();
119733                                     }
119734                                 }
119735                             }
119736                             else if (ts.isFunctionExpression(binaryExpression.right) || ts.isArrowFunction(binaryExpression.right)) {
119737                                 addNodeWithRecursiveChild(node, binaryExpression.right, className);
119738                             }
119739                             else {
119740                                 startNode(binaryExpression, className);
119741                                 addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name);
119742                                 endNode();
119743                             }
119744                             endNestedNodes(depth);
119745                             return;
119746                         }
119747                         case 7 /* ObjectDefinePropertyValue */:
119748                         case 9 /* ObjectDefinePrototypeProperty */: {
119749                             var defineCall = node;
119750                             var className = special === 7 /* ObjectDefinePropertyValue */ ?
119751                                 defineCall.arguments[0] :
119752                                 defineCall.arguments[0].expression;
119753                             var memberName = defineCall.arguments[1];
119754                             var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1];
119755                             startNode(node, classNameIdentifier);
119756                             startNode(node, ts.setTextRange(ts.createIdentifier(memberName.text), memberName));
119757                             addChildrenRecursively(node.arguments[2]);
119758                             endNode();
119759                             endNode();
119760                             endNestedNodes(depth);
119761                             return;
119762                         }
119763                         case 5 /* Property */: {
119764                             var binaryExpression = node;
119765                             var assignmentTarget = binaryExpression.left;
119766                             var targetFunction = assignmentTarget.expression;
119767                             if (ts.isIdentifier(targetFunction) && ts.getElementOrPropertyAccessName(assignmentTarget) !== "prototype" &&
119768                                 trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) {
119769                                 if (ts.isFunctionExpression(binaryExpression.right) || ts.isArrowFunction(binaryExpression.right)) {
119770                                     addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction);
119771                                 }
119772                                 else if (ts.isBindableStaticAccessExpression(assignmentTarget)) {
119773                                     startNode(binaryExpression, targetFunction);
119774                                     addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, ts.getNameOrArgument(assignmentTarget));
119775                                     endNode();
119776                                 }
119777                                 return;
119778                             }
119779                             break;
119780                         }
119781                         case 4 /* ThisProperty */:
119782                         case 0 /* None */:
119783                         case 8 /* ObjectDefinePropertyExports */:
119784                             break;
119785                         default:
119786                             ts.Debug.assertNever(special);
119787                     }
119788                 }
119789                 // falls through
119790                 default:
119791                     if (ts.hasJSDocNodes(node)) {
119792                         ts.forEach(node.jsDoc, function (jsDoc) {
119793                             ts.forEach(jsDoc.tags, function (tag) {
119794                                 if (ts.isJSDocTypeAlias(tag)) {
119795                                     addLeafNode(tag);
119796                                 }
119797                             });
119798                         });
119799                     }
119800                     ts.forEachChild(node, addChildrenRecursively);
119801             }
119802         }
119803         /** Merge declarations of the same kind. */
119804         function mergeChildren(children, node) {
119805             var nameToItems = ts.createMap();
119806             ts.filterMutate(children, function (child, index) {
119807                 var declName = child.name || ts.getNameOfDeclaration(child.node);
119808                 var name = declName && nodeText(declName);
119809                 if (!name) {
119810                     // Anonymous items are never merged.
119811                     return true;
119812                 }
119813                 var itemsWithSameName = nameToItems.get(name);
119814                 if (!itemsWithSameName) {
119815                     nameToItems.set(name, child);
119816                     return true;
119817                 }
119818                 if (itemsWithSameName instanceof Array) {
119819                     for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) {
119820                         var itemWithSameName = itemsWithSameName_1[_i];
119821                         if (tryMerge(itemWithSameName, child, index, node)) {
119822                             return false;
119823                         }
119824                     }
119825                     itemsWithSameName.push(child);
119826                     return true;
119827                 }
119828                 else {
119829                     var itemWithSameName = itemsWithSameName;
119830                     if (tryMerge(itemWithSameName, child, index, node)) {
119831                         return false;
119832                     }
119833                     nameToItems.set(name, [itemWithSameName, child]);
119834                     return true;
119835                 }
119836             });
119837         }
119838         var isEs5ClassMember = (_a = {},
119839             _a[5 /* Property */] = true,
119840             _a[3 /* PrototypeProperty */] = true,
119841             _a[7 /* ObjectDefinePropertyValue */] = true,
119842             _a[9 /* ObjectDefinePrototypeProperty */] = true,
119843             _a[0 /* None */] = false,
119844             _a[1 /* ExportsProperty */] = false,
119845             _a[2 /* ModuleExports */] = false,
119846             _a[8 /* ObjectDefinePropertyExports */] = false,
119847             _a[6 /* Prototype */] = true,
119848             _a[4 /* ThisProperty */] = false,
119849             _a);
119850         function tryMergeEs5Class(a, b, bIndex, parent) {
119851             function isPossibleConstructor(node) {
119852                 return ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node);
119853             }
119854             var bAssignmentDeclarationKind = ts.isBinaryExpression(b.node) || ts.isCallExpression(b.node) ?
119855                 ts.getAssignmentDeclarationKind(b.node) :
119856                 0 /* None */;
119857             var aAssignmentDeclarationKind = ts.isBinaryExpression(a.node) || ts.isCallExpression(a.node) ?
119858                 ts.getAssignmentDeclarationKind(a.node) :
119859                 0 /* None */;
119860             // We treat this as an es5 class and merge the nodes in in one of several cases
119861             if ((isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind]) // merge two class elements
119862                 || (isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // ctor function & member
119863                 || (isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & ctor function
119864                 || (ts.isClassDeclaration(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // class (generated) & member
119865                 || (ts.isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & class (generated)
119866                 || (ts.isClassDeclaration(a.node) && isPossibleConstructor(b.node)) // class (generated) & ctor
119867                 || (ts.isClassDeclaration(b.node) && isPossibleConstructor(a.node)) // ctor & class (generated)
119868             ) {
119869                 var lastANode = a.additionalNodes && ts.lastOrUndefined(a.additionalNodes) || a.node;
119870                 if ((!ts.isClassDeclaration(a.node) && !ts.isClassDeclaration(b.node)) // If neither outline node is a class
119871                     || isPossibleConstructor(a.node) || isPossibleConstructor(b.node) // If either function is a constructor function
119872                 ) {
119873                     var ctorFunction = isPossibleConstructor(a.node) ? a.node :
119874                         isPossibleConstructor(b.node) ? b.node :
119875                             undefined;
119876                     if (ctorFunction !== undefined) {
119877                         var ctorNode = ts.setTextRange(ts.createConstructor(/* decorators */ undefined, /* modifiers */ undefined, [], /* body */ undefined), ctorFunction);
119878                         var ctor = emptyNavigationBarNode(ctorNode);
119879                         ctor.indent = a.indent + 1;
119880                         ctor.children = a.node === ctorFunction ? a.children : b.children;
119881                         a.children = a.node === ctorFunction ? ts.concatenate([ctor], b.children || [b]) : ts.concatenate(a.children || [a], [ctor]);
119882                     }
119883                     else {
119884                         if (a.children || b.children) {
119885                             a.children = ts.concatenate(a.children || [a], b.children || [b]);
119886                             if (a.children) {
119887                                 mergeChildren(a.children, a);
119888                                 sortChildren(a.children);
119889                             }
119890                         }
119891                     }
119892                     lastANode = a.node = ts.setTextRange(ts.createClassDeclaration(
119893                     /* decorators */ undefined, 
119894                     /* modifiers */ undefined, a.name || ts.createIdentifier("__class__"), 
119895                     /* typeParameters */ undefined, 
119896                     /* heritageClauses */ undefined, []), a.node);
119897                 }
119898                 else {
119899                     a.children = ts.concatenate(a.children, b.children);
119900                     if (a.children) {
119901                         mergeChildren(a.children, a);
119902                     }
119903                 }
119904                 var bNode = b.node;
119905                 // We merge if the outline node previous to b (bIndex - 1) is already part of the current class
119906                 // We do this so that statements between class members that do not generate outline nodes do not split up the class outline:
119907                 // Ex This should produce one outline node C:
119908                 //    function C() {}; a = 1; C.prototype.m = function () {}
119909                 // Ex This will produce 3 outline nodes: C, a, C
119910                 //    function C() {}; let a = 1; C.prototype.m = function () {}
119911                 if (parent.children[bIndex - 1].node.end === lastANode.end) {
119912                     ts.setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end });
119913                 }
119914                 else {
119915                     if (!a.additionalNodes)
119916                         a.additionalNodes = [];
119917                     a.additionalNodes.push(ts.setTextRange(ts.createClassDeclaration(
119918                     /* decorators */ undefined, 
119919                     /* modifiers */ undefined, a.name || ts.createIdentifier("__class__"), 
119920                     /* typeParameters */ undefined, 
119921                     /* heritageClauses */ undefined, []), b.node));
119922                 }
119923                 return true;
119924             }
119925             return bAssignmentDeclarationKind === 0 /* None */ ? false : true;
119926         }
119927         function tryMerge(a, b, bIndex, parent) {
119928             // const v = false as boolean;
119929             if (tryMergeEs5Class(a, b, bIndex, parent)) {
119930                 return true;
119931             }
119932             if (shouldReallyMerge(a.node, b.node, parent)) {
119933                 merge(a, b);
119934                 return true;
119935             }
119936             return false;
119937         }
119938         /** a and b have the same name, but they may not be mergeable. */
119939         function shouldReallyMerge(a, b, parent) {
119940             if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) {
119941                 return false;
119942             }
119943             switch (a.kind) {
119944                 case 159 /* PropertyDeclaration */:
119945                 case 161 /* MethodDeclaration */:
119946                 case 163 /* GetAccessor */:
119947                 case 164 /* SetAccessor */:
119948                     return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */);
119949                 case 249 /* ModuleDeclaration */:
119950                     return areSameModule(a, b);
119951                 default:
119952                     return true;
119953             }
119954         }
119955         // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }`
119956         // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };`
119957         function isOwnChild(n, parent) {
119958             var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent;
119959             return par === parent.node || ts.contains(parent.additionalNodes, par);
119960         }
119961         // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes.
119962         // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
119963         function areSameModule(a, b) {
119964             // TODO: GH#18217
119965             return a.body.kind === b.body.kind && (a.body.kind !== 249 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
119966         }
119967         /** Merge source into target. Source should be thrown away after this is called. */
119968         function merge(target, source) {
119969             var _a;
119970             target.additionalNodes = target.additionalNodes || [];
119971             target.additionalNodes.push(source.node);
119972             if (source.additionalNodes) {
119973                 (_a = target.additionalNodes).push.apply(_a, source.additionalNodes);
119974             }
119975             target.children = ts.concatenate(target.children, source.children);
119976             if (target.children) {
119977                 mergeChildren(target.children, target);
119978                 sortChildren(target.children);
119979             }
119980         }
119981         /** Recursively ensure that each NavNode's children are in sorted order. */
119982         function sortChildren(children) {
119983             children.sort(compareChildren);
119984         }
119985         function compareChildren(child1, child2) {
119986             return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217
119987                 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2));
119988         }
119989         /**
119990          * This differs from getItemName because this is just used for sorting.
119991          * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like.
119992          * So `new()` can still come before an `aardvark` method.
119993          */
119994         function tryGetName(node) {
119995             if (node.kind === 249 /* ModuleDeclaration */) {
119996                 return getModuleName(node);
119997             }
119998             var declName = ts.getNameOfDeclaration(node);
119999             if (declName && ts.isPropertyName(declName)) {
120000                 var propertyName = ts.getPropertyNameForPropertyNameNode(declName);
120001                 return propertyName && ts.unescapeLeadingUnderscores(propertyName);
120002             }
120003             switch (node.kind) {
120004                 case 201 /* FunctionExpression */:
120005                 case 202 /* ArrowFunction */:
120006                 case 214 /* ClassExpression */:
120007                     return getFunctionOrClassName(node);
120008                 default:
120009                     return undefined;
120010             }
120011         }
120012         function getItemName(node, name) {
120013             if (node.kind === 249 /* ModuleDeclaration */) {
120014                 return cleanText(getModuleName(node));
120015             }
120016             if (name) {
120017                 var text = ts.isIdentifier(name) ? name.text
120018                     : ts.isElementAccessExpression(name) ? "[" + nodeText(name.argumentExpression) + "]"
120019                         : nodeText(name);
120020                 if (text.length > 0) {
120021                     return cleanText(text);
120022                 }
120023             }
120024             switch (node.kind) {
120025                 case 290 /* SourceFile */:
120026                     var sourceFile = node;
120027                     return ts.isExternalModule(sourceFile)
120028                         ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
120029                         : "<global>";
120030                 case 259 /* ExportAssignment */:
120031                     return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
120032                 case 202 /* ArrowFunction */:
120033                 case 244 /* FunctionDeclaration */:
120034                 case 201 /* FunctionExpression */:
120035                 case 245 /* ClassDeclaration */:
120036                 case 214 /* ClassExpression */:
120037                     if (ts.getModifierFlags(node) & 512 /* Default */) {
120038                         return "default";
120039                     }
120040                     // We may get a string with newlines or other whitespace in the case of an object dereference
120041                     // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
120042                     // navigation bar.
120043                     return getFunctionOrClassName(node);
120044                 case 162 /* Constructor */:
120045                     return "constructor";
120046                 case 166 /* ConstructSignature */:
120047                     return "new()";
120048                 case 165 /* CallSignature */:
120049                     return "()";
120050                 case 167 /* IndexSignature */:
120051                     return "[]";
120052                 default:
120053                     return "<unknown>";
120054             }
120055         }
120056         /** Flattens the NavNode tree to a list of items to appear in the primary navbar menu. */
120057         function primaryNavBarMenuItems(root) {
120058             // The primary (middle) navbar menu displays the general code navigation hierarchy, similar to the navtree.
120059             // The secondary (right) navbar menu displays the child items of whichever primary item is selected.
120060             // Some less interesting items without their own child navigation items (e.g. a local variable declaration) only show up in the secondary menu.
120061             var primaryNavBarMenuItems = [];
120062             function recur(item) {
120063                 if (shouldAppearInPrimaryNavBarMenu(item)) {
120064                     primaryNavBarMenuItems.push(item);
120065                     if (item.children) {
120066                         for (var _i = 0, _a = item.children; _i < _a.length; _i++) {
120067                             var child = _a[_i];
120068                             recur(child);
120069                         }
120070                     }
120071                 }
120072             }
120073             recur(root);
120074             return primaryNavBarMenuItems;
120075             /** Determines if a node should appear in the primary navbar menu. */
120076             function shouldAppearInPrimaryNavBarMenu(item) {
120077                 // Items with children should always appear in the primary navbar menu.
120078                 if (item.children) {
120079                     return true;
120080                 }
120081                 // Some nodes are otherwise important enough to always include in the primary navigation menu.
120082                 switch (navigationBarNodeKind(item)) {
120083                     case 245 /* ClassDeclaration */:
120084                     case 214 /* ClassExpression */:
120085                     case 248 /* EnumDeclaration */:
120086                     case 246 /* InterfaceDeclaration */:
120087                     case 249 /* ModuleDeclaration */:
120088                     case 290 /* SourceFile */:
120089                     case 247 /* TypeAliasDeclaration */:
120090                     case 322 /* JSDocTypedefTag */:
120091                     case 315 /* JSDocCallbackTag */:
120092                         return true;
120093                     case 202 /* ArrowFunction */:
120094                     case 244 /* FunctionDeclaration */:
120095                     case 201 /* FunctionExpression */:
120096                         return isTopLevelFunctionDeclaration(item);
120097                     default:
120098                         return false;
120099                 }
120100                 function isTopLevelFunctionDeclaration(item) {
120101                     if (!item.node.body) {
120102                         return false;
120103                     }
120104                     switch (navigationBarNodeKind(item.parent)) {
120105                         case 250 /* ModuleBlock */:
120106                         case 290 /* SourceFile */:
120107                         case 161 /* MethodDeclaration */:
120108                         case 162 /* Constructor */:
120109                             return true;
120110                         default:
120111                             return false;
120112                     }
120113                 }
120114             }
120115         }
120116         function convertToTree(n) {
120117             return {
120118                 text: getItemName(n.node, n.name),
120119                 kind: ts.getNodeKind(n.node),
120120                 kindModifiers: getModifiers(n.node),
120121                 spans: getSpans(n),
120122                 nameSpan: n.name && getNodeSpan(n.name),
120123                 childItems: ts.map(n.children, convertToTree)
120124             };
120125         }
120126         function convertToPrimaryNavBarMenuItem(n) {
120127             return {
120128                 text: getItemName(n.node, n.name),
120129                 kind: ts.getNodeKind(n.node),
120130                 kindModifiers: getModifiers(n.node),
120131                 spans: getSpans(n),
120132                 childItems: ts.map(n.children, convertToSecondaryNavBarMenuItem) || emptyChildItemArray,
120133                 indent: n.indent,
120134                 bolded: false,
120135                 grayed: false
120136             };
120137             function convertToSecondaryNavBarMenuItem(n) {
120138                 return {
120139                     text: getItemName(n.node, n.name),
120140                     kind: ts.getNodeKind(n.node),
120141                     kindModifiers: ts.getNodeModifiers(n.node),
120142                     spans: getSpans(n),
120143                     childItems: emptyChildItemArray,
120144                     indent: 0,
120145                     bolded: false,
120146                     grayed: false
120147                 };
120148             }
120149         }
120150         function getSpans(n) {
120151             var spans = [getNodeSpan(n.node)];
120152             if (n.additionalNodes) {
120153                 for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) {
120154                     var node = _a[_i];
120155                     spans.push(getNodeSpan(node));
120156                 }
120157             }
120158             return spans;
120159         }
120160         function getModuleName(moduleDeclaration) {
120161             // We want to maintain quotation marks.
120162             if (ts.isAmbientModule(moduleDeclaration)) {
120163                 return ts.getTextOfNode(moduleDeclaration.name);
120164             }
120165             // Otherwise, we need to aggregate each identifier to build up the qualified name.
120166             var result = [];
120167             result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
120168             while (moduleDeclaration.body && moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
120169                 moduleDeclaration = moduleDeclaration.body;
120170                 result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
120171             }
120172             return result.join(".");
120173         }
120174         /**
120175          * For 'module A.B.C', we want to get the node for 'C'.
120176          * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again.
120177          */
120178         function getInteriorModule(decl) {
120179             return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl;
120180         }
120181         function isComputedProperty(member) {
120182             return !member.name || member.name.kind === 154 /* ComputedPropertyName */;
120183         }
120184         function getNodeSpan(node) {
120185             return node.kind === 290 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
120186         }
120187         function getModifiers(node) {
120188             if (node.parent && node.parent.kind === 242 /* VariableDeclaration */) {
120189                 node = node.parent;
120190             }
120191             return ts.getNodeModifiers(node);
120192         }
120193         function getFunctionOrClassName(node) {
120194             var parent = node.parent;
120195             if (node.name && ts.getFullWidth(node.name) > 0) {
120196                 return cleanText(ts.declarationNameToString(node.name));
120197             }
120198             // See if it is a var initializer. If so, use the var name.
120199             else if (ts.isVariableDeclaration(parent)) {
120200                 return cleanText(ts.declarationNameToString(parent.name));
120201             }
120202             // See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
120203             else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */) {
120204                 return nodeText(parent.left).replace(whiteSpaceRegex, "");
120205             }
120206             // See if it is a property assignment, and if so use the property name
120207             else if (ts.isPropertyAssignment(parent)) {
120208                 return nodeText(parent.name);
120209             }
120210             // Default exports are named "default"
120211             else if (ts.getModifierFlags(node) & 512 /* Default */) {
120212                 return "default";
120213             }
120214             else if (ts.isClassLike(node)) {
120215                 return "<class>";
120216             }
120217             else if (ts.isCallExpression(parent)) {
120218                 var name = getCalledExpressionName(parent.expression);
120219                 if (name !== undefined) {
120220                     name = cleanText(name);
120221                     if (name.length > maxLength) {
120222                         return name + " callback";
120223                     }
120224                     var args = cleanText(ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "));
120225                     return name + "(" + args + ") callback";
120226                 }
120227             }
120228             return "<function>";
120229         }
120230         // See also 'tryGetPropertyAccessOrIdentifierToString'
120231         function getCalledExpressionName(expr) {
120232             if (ts.isIdentifier(expr)) {
120233                 return expr.text;
120234             }
120235             else if (ts.isPropertyAccessExpression(expr)) {
120236                 var left = getCalledExpressionName(expr.expression);
120237                 var right = expr.name.text;
120238                 return left === undefined ? right : left + "." + right;
120239             }
120240             else {
120241                 return undefined;
120242             }
120243         }
120244         function isFunctionOrClassExpression(node) {
120245             switch (node.kind) {
120246                 case 202 /* ArrowFunction */:
120247                 case 201 /* FunctionExpression */:
120248                 case 214 /* ClassExpression */:
120249                     return true;
120250                 default:
120251                     return false;
120252             }
120253         }
120254         function cleanText(text) {
120255             // Truncate to maximum amount of characters as we don't want to do a big replace operation.
120256             text = text.length > maxLength ? text.substring(0, maxLength) + "..." : text;
120257             // Replaces ECMAScript line terminators and removes the trailing `\` from each line:
120258             // \n - Line Feed
120259             // \r - Carriage Return
120260             // \u2028 - Line separator
120261             // \u2029 - Paragraph separator
120262             return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, "");
120263         }
120264     })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {}));
120265 })(ts || (ts = {}));
120266 /* @internal */
120267 var ts;
120268 (function (ts) {
120269     var OrganizeImports;
120270     (function (OrganizeImports) {
120271         /**
120272          * Organize imports by:
120273          *   1) Removing unused imports
120274          *   2) Coalescing imports from the same module
120275          *   3) Sorting imports
120276          */
120277         function organizeImports(sourceFile, formatContext, host, program, preferences) {
120278             var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences });
120279             var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
120280             // All of the old ImportDeclarations in the file, in syntactic order.
120281             var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
120282             organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
120283             // All of the old ExportDeclarations in the file, in syntactic order.
120284             var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
120285             organizeImportsWorker(topLevelExportDecls, coalesceExports);
120286             for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
120287                 var ambientModule = _a[_i];
120288                 if (!ambientModule.body) {
120289                     continue;
120290                 }
120291                 var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration);
120292                 organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
120293                 var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration);
120294                 organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
120295             }
120296             return changeTracker.getChanges();
120297             function organizeImportsWorker(oldImportDecls, coalesce) {
120298                 if (ts.length(oldImportDecls) === 0) {
120299                     return;
120300                 }
120301                 // Special case: normally, we'd expect leading and trailing trivia to follow each import
120302                 // around as it's sorted.  However, we do not want this to happen for leading trivia
120303                 // on the first import because it is probably the header comment for the file.
120304                 // Consider: we could do a more careful check that this trivia is actually a header,
120305                 // but the consequences of being wrong are very minor.
120306                 ts.suppressLeadingTrivia(oldImportDecls[0]);
120307                 var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); });
120308                 var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
120309                 var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
120310                     return getExternalModuleName(importGroup[0].moduleSpecifier)
120311                         ? coalesce(importGroup)
120312                         : importGroup;
120313                 });
120314                 // Delete or replace the first import.
120315                 if (newImportDecls.length === 0) {
120316                     changeTracker.delete(sourceFile, oldImportDecls[0]);
120317                 }
120318                 else {
120319                     // Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
120320                     changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
120321                         leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
120322                         trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
120323                         suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
120324                     });
120325                 }
120326                 // Delete any subsequent imports.
120327                 for (var i = 1; i < oldImportDecls.length; i++) {
120328                     changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
120329                 }
120330             }
120331         }
120332         OrganizeImports.organizeImports = organizeImports;
120333         function removeUnusedImports(oldImports, sourceFile, program) {
120334             var typeChecker = program.getTypeChecker();
120335             var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
120336             var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
120337             var usedImports = [];
120338             for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
120339                 var importDecl = oldImports_1[_i];
120340                 var importClause = importDecl.importClause, moduleSpecifier = importDecl.moduleSpecifier;
120341                 if (!importClause) {
120342                     // Imports without import clauses are assumed to be included for their side effects and are not removed.
120343                     usedImports.push(importDecl);
120344                     continue;
120345                 }
120346                 var name = importClause.name, namedBindings = importClause.namedBindings;
120347                 // Default import
120348                 if (name && !isDeclarationUsed(name)) {
120349                     name = undefined;
120350                 }
120351                 if (namedBindings) {
120352                     if (ts.isNamespaceImport(namedBindings)) {
120353                         // Namespace import
120354                         if (!isDeclarationUsed(namedBindings.name)) {
120355                             namedBindings = undefined;
120356                         }
120357                     }
120358                     else {
120359                         // List of named imports
120360                         var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); });
120361                         if (newElements.length < namedBindings.elements.length) {
120362                             namedBindings = newElements.length
120363                                 ? ts.updateNamedImports(namedBindings, newElements)
120364                                 : undefined;
120365                         }
120366                     }
120367                 }
120368                 if (name || namedBindings) {
120369                     usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
120370                 }
120371                 // If a module is imported to be augmented, it’s used
120372                 else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
120373                     // If we’re in a declaration file, it’s safe to remove the import clause from it
120374                     if (sourceFile.isDeclarationFile) {
120375                         usedImports.push(ts.createImportDeclaration(importDecl.decorators, importDecl.modifiers, 
120376                         /*importClause*/ undefined, moduleSpecifier));
120377                     }
120378                     // If we’re not in a declaration file, we can’t remove the import clause even though
120379                     // the imported symbols are unused, because removing them makes it look like the import
120380                     // declaration has side effects, which will cause it to be preserved in the JS emit.
120381                     else {
120382                         usedImports.push(importDecl);
120383                     }
120384                 }
120385             }
120386             return usedImports;
120387             function isDeclarationUsed(identifier) {
120388                 // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
120389                 return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
120390             }
120391         }
120392         function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) {
120393             var moduleSpecifierText = ts.isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
120394             return ts.isString(moduleSpecifierText) && ts.some(sourceFile.moduleAugmentations, function (moduleName) {
120395                 return ts.isStringLiteral(moduleName)
120396                     && moduleName.text === moduleSpecifierText;
120397             });
120398         }
120399         function getExternalModuleName(specifier) {
120400             return specifier !== undefined && ts.isStringLiteralLike(specifier)
120401                 ? specifier.text
120402                 : undefined;
120403         }
120404         // Internal for testing
120405         /**
120406          * @param importGroup a list of ImportDeclarations, all with the same module name.
120407          */
120408         function coalesceImports(importGroup) {
120409             var _a;
120410             if (importGroup.length === 0) {
120411                 return importGroup;
120412             }
120413             var _b = getCategorizedImports(importGroup), importWithoutClause = _b.importWithoutClause, typeOnlyImports = _b.typeOnlyImports, regularImports = _b.regularImports;
120414             var coalescedImports = [];
120415             if (importWithoutClause) {
120416                 coalescedImports.push(importWithoutClause);
120417             }
120418             for (var _i = 0, _c = [regularImports, typeOnlyImports]; _i < _c.length; _i++) {
120419                 var group_2 = _c[_i];
120420                 var isTypeOnly = group_2 === typeOnlyImports;
120421                 var defaultImports = group_2.defaultImports, namespaceImports = group_2.namespaceImports, namedImports = group_2.namedImports;
120422                 // Normally, we don't combine default and namespace imports, but it would be silly to
120423                 // produce two import declarations in this special case.
120424                 if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
120425                     // Add the namespace import to the existing default ImportDeclaration.
120426                     var defaultImport = defaultImports[0];
120427                     coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217
120428                     continue;
120429                 }
120430                 var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) {
120431                     return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name);
120432                 }); // TODO: GH#18217
120433                 for (var _d = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _d < sortedNamespaceImports_1.length; _d++) {
120434                     var namespaceImport = sortedNamespaceImports_1[_d];
120435                     // Drop the name, if any
120436                     coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217
120437                 }
120438                 if (defaultImports.length === 0 && namedImports.length === 0) {
120439                     continue;
120440                 }
120441                 var newDefaultImport = void 0;
120442                 var newImportSpecifiers = [];
120443                 if (defaultImports.length === 1) {
120444                     newDefaultImport = defaultImports[0].importClause.name;
120445                 }
120446                 else {
120447                     for (var _e = 0, defaultImports_1 = defaultImports; _e < defaultImports_1.length; _e++) {
120448                         var defaultImport = defaultImports_1[_e];
120449                         newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217
120450                     }
120451                 }
120452                 newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217
120453                 var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
120454                 var importDecl = defaultImports.length > 0
120455                     ? defaultImports[0]
120456                     : namedImports[0];
120457                 var newNamedImports = sortedImportSpecifiers.length === 0
120458                     ? newDefaultImport
120459                         ? undefined
120460                         : ts.createNamedImports(ts.emptyArray)
120461                     : namedImports.length === 0
120462                         ? ts.createNamedImports(sortedImportSpecifiers)
120463                         : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217
120464                 // Type-only imports are not allowed to mix default, namespace, and named imports in any combination.
120465                 // We could rewrite a default import as a named import (`import { default as name }`), but we currently
120466                 // choose not to as a stylistic preference.
120467                 if (isTypeOnly && newDefaultImport && newNamedImports) {
120468                     coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined));
120469                     coalescedImports.push(updateImportDeclarationAndClause((_a = namedImports[0]) !== null && _a !== void 0 ? _a : importDecl, /*name*/ undefined, newNamedImports));
120470                 }
120471                 else {
120472                     coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
120473                 }
120474             }
120475             return coalescedImports;
120476         }
120477         OrganizeImports.coalesceImports = coalesceImports;
120478         /*
120479          * Returns entire import declarations because they may already have been rewritten and
120480          * may lack parent pointers.  The desired parts can easily be recovered based on the
120481          * categorization.
120482          *
120483          * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
120484          */
120485         function getCategorizedImports(importGroup) {
120486             var importWithoutClause;
120487             var typeOnlyImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
120488             var regularImports = { defaultImports: [], namespaceImports: [], namedImports: [] };
120489             for (var _i = 0, importGroup_1 = importGroup; _i < importGroup_1.length; _i++) {
120490                 var importDeclaration = importGroup_1[_i];
120491                 if (importDeclaration.importClause === undefined) {
120492                     // Only the first such import is interesting - the others are redundant.
120493                     // Note: Unfortunately, we will lose trivia that was on this node.
120494                     importWithoutClause = importWithoutClause || importDeclaration;
120495                     continue;
120496                 }
120497                 var group_3 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports;
120498                 var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
120499                 if (name) {
120500                     group_3.defaultImports.push(importDeclaration);
120501                 }
120502                 if (namedBindings) {
120503                     if (ts.isNamespaceImport(namedBindings)) {
120504                         group_3.namespaceImports.push(importDeclaration);
120505                     }
120506                     else {
120507                         group_3.namedImports.push(importDeclaration);
120508                     }
120509                 }
120510             }
120511             return {
120512                 importWithoutClause: importWithoutClause,
120513                 typeOnlyImports: typeOnlyImports,
120514                 regularImports: regularImports,
120515             };
120516         }
120517         // Internal for testing
120518         /**
120519          * @param exportGroup a list of ExportDeclarations, all with the same module name.
120520          */
120521         function coalesceExports(exportGroup) {
120522             if (exportGroup.length === 0) {
120523                 return exportGroup;
120524             }
120525             var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports, typeOnlyExports = _a.typeOnlyExports;
120526             var coalescedExports = [];
120527             if (exportWithoutClause) {
120528                 coalescedExports.push(exportWithoutClause);
120529             }
120530             for (var _i = 0, _b = [namedExports, typeOnlyExports]; _i < _b.length; _i++) {
120531                 var exportGroup_1 = _b[_i];
120532                 if (exportGroup_1.length === 0) {
120533                     continue;
120534                 }
120535                 var newExportSpecifiers = [];
120536                 newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(exportGroup_1, function (i) { return i.exportClause && ts.isNamedExports(i.exportClause) ? i.exportClause.elements : ts.emptyArray; }));
120537                 var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
120538                 var exportDecl = exportGroup_1[0];
120539                 coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.exportClause && (ts.isNamedExports(exportDecl.exportClause) ?
120540                     ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) :
120541                     ts.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.isTypeOnly));
120542             }
120543             return coalescedExports;
120544             /*
120545              * Returns entire export declarations because they may already have been rewritten and
120546              * may lack parent pointers.  The desired parts can easily be recovered based on the
120547              * categorization.
120548              */
120549             function getCategorizedExports(exportGroup) {
120550                 var exportWithoutClause;
120551                 var namedExports = [];
120552                 var typeOnlyExports = [];
120553                 for (var _i = 0, exportGroup_2 = exportGroup; _i < exportGroup_2.length; _i++) {
120554                     var exportDeclaration = exportGroup_2[_i];
120555                     if (exportDeclaration.exportClause === undefined) {
120556                         // Only the first such export is interesting - the others are redundant.
120557                         // Note: Unfortunately, we will lose trivia that was on this node.
120558                         exportWithoutClause = exportWithoutClause || exportDeclaration;
120559                     }
120560                     else if (exportDeclaration.isTypeOnly) {
120561                         typeOnlyExports.push(exportDeclaration);
120562                     }
120563                     else {
120564                         namedExports.push(exportDeclaration);
120565                     }
120566                 }
120567                 return {
120568                     exportWithoutClause: exportWithoutClause,
120569                     namedExports: namedExports,
120570                     typeOnlyExports: typeOnlyExports,
120571                 };
120572             }
120573         }
120574         OrganizeImports.coalesceExports = coalesceExports;
120575         function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
120576             return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings, importDeclaration.importClause.isTypeOnly), // TODO: GH#18217
120577             importDeclaration.moduleSpecifier);
120578         }
120579         function sortSpecifiers(specifiers) {
120580             return ts.stableSort(specifiers, function (s1, s2) {
120581                 return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
120582                     compareIdentifiers(s1.name, s2.name);
120583             });
120584         }
120585         /* internal */ // Exported for testing
120586         function compareModuleSpecifiers(m1, m2) {
120587             var name1 = getExternalModuleName(m1);
120588             var name2 = getExternalModuleName(m2);
120589             return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
120590                 ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
120591                 ts.compareStringsCaseInsensitive(name1, name2);
120592         }
120593         OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
120594         function compareIdentifiers(s1, s2) {
120595             return ts.compareStringsCaseInsensitive(s1.text, s2.text);
120596         }
120597     })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
120598 })(ts || (ts = {}));
120599 /* @internal */
120600 var ts;
120601 (function (ts) {
120602     var OutliningElementsCollector;
120603     (function (OutliningElementsCollector) {
120604         function collectElements(sourceFile, cancellationToken) {
120605             var res = [];
120606             addNodeOutliningSpans(sourceFile, cancellationToken, res);
120607             addRegionOutliningSpans(sourceFile, res);
120608             return res.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; });
120609         }
120610         OutliningElementsCollector.collectElements = collectElements;
120611         function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
120612             var depthRemaining = 40;
120613             var current = 0;
120614             // Includes the EOF Token so that comments which aren't attached to statements are included
120615             var statements = __spreadArrays(sourceFile.statements, [sourceFile.endOfFileToken]);
120616             var n = statements.length;
120617             while (current < n) {
120618                 while (current < n && !ts.isAnyImportSyntax(statements[current])) {
120619                     visitNonImportNode(statements[current]);
120620                     current++;
120621                 }
120622                 if (current === n)
120623                     break;
120624                 var firstImport = current;
120625                 while (current < n && ts.isAnyImportSyntax(statements[current])) {
120626                     addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
120627                     current++;
120628                 }
120629                 var lastImport = current - 1;
120630                 if (lastImport !== firstImport) {
120631                     out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 96 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
120632                 }
120633             }
120634             function visitNonImportNode(n) {
120635                 var _a;
120636                 if (depthRemaining === 0)
120637                     return;
120638                 cancellationToken.throwIfCancellationRequested();
120639                 if (ts.isDeclaration(n) || n.kind === 1 /* EndOfFileToken */) {
120640                     addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out);
120641                 }
120642                 if (isFunctionExpressionAssignedToVariable(n)) {
120643                     addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out);
120644                 }
120645                 var span = getOutliningSpanForNode(n, sourceFile);
120646                 if (span)
120647                     out.push(span);
120648                 depthRemaining--;
120649                 if (ts.isCallExpression(n)) {
120650                     depthRemaining++;
120651                     visitNonImportNode(n.expression);
120652                     depthRemaining--;
120653                     n.arguments.forEach(visitNonImportNode);
120654                     (_a = n.typeArguments) === null || _a === void 0 ? void 0 : _a.forEach(visitNonImportNode);
120655                 }
120656                 else if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
120657                     // Consider an 'else if' to be on the same depth as the 'if'.
120658                     visitNonImportNode(n.expression);
120659                     visitNonImportNode(n.thenStatement);
120660                     depthRemaining++;
120661                     visitNonImportNode(n.elseStatement);
120662                     depthRemaining--;
120663                 }
120664                 else {
120665                     n.forEachChild(visitNonImportNode);
120666                 }
120667                 depthRemaining++;
120668             }
120669             function isFunctionExpressionAssignedToVariable(n) {
120670                 if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) {
120671                     return false;
120672                 }
120673                 var ancestor = ts.findAncestor(n, ts.isVariableStatement);
120674                 return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n;
120675             }
120676         }
120677         function addRegionOutliningSpans(sourceFile, out) {
120678             var regions = [];
120679             var lineStarts = sourceFile.getLineStarts();
120680             for (var _i = 0, lineStarts_1 = lineStarts; _i < lineStarts_1.length; _i++) {
120681                 var currentLineStart = lineStarts_1[_i];
120682                 var lineEnd = sourceFile.getLineEndOfPosition(currentLineStart);
120683                 var lineText = sourceFile.text.substring(currentLineStart, lineEnd);
120684                 var result = isRegionDelimiter(lineText);
120685                 if (!result || ts.isInComment(sourceFile, currentLineStart)) {
120686                     continue;
120687                 }
120688                 if (!result[1]) {
120689                     var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
120690                     regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
120691                 }
120692                 else {
120693                     var region = regions.pop();
120694                     if (region) {
120695                         region.textSpan.length = lineEnd - region.textSpan.start;
120696                         region.hintSpan.length = lineEnd - region.textSpan.start;
120697                         out.push(region);
120698                     }
120699                 }
120700             }
120701         }
120702         var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/;
120703         function isRegionDelimiter(lineText) {
120704             return regionDelimiterRegExp.exec(lineText);
120705         }
120706         function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
120707             var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
120708             if (!comments)
120709                 return;
120710             var firstSingleLineCommentStart = -1;
120711             var lastSingleLineCommentEnd = -1;
120712             var singleLineCommentCount = 0;
120713             var sourceText = sourceFile.getFullText();
120714             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
120715                 var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
120716                 cancellationToken.throwIfCancellationRequested();
120717                 switch (kind) {
120718                     case 2 /* SingleLineCommentTrivia */:
120719                         // never fold region delimiters into single-line comment regions
120720                         var commentText = sourceText.slice(pos, end);
120721                         if (isRegionDelimiter(commentText)) {
120722                             combineAndAddMultipleSingleLineComments();
120723                             singleLineCommentCount = 0;
120724                             break;
120725                         }
120726                         // For single line comments, combine consecutive ones (2 or more) into
120727                         // a single span from the start of the first till the end of the last
120728                         if (singleLineCommentCount === 0) {
120729                             firstSingleLineCommentStart = pos;
120730                         }
120731                         lastSingleLineCommentEnd = end;
120732                         singleLineCommentCount++;
120733                         break;
120734                     case 3 /* MultiLineCommentTrivia */:
120735                         combineAndAddMultipleSingleLineComments();
120736                         out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
120737                         singleLineCommentCount = 0;
120738                         break;
120739                     default:
120740                         ts.Debug.assertNever(kind);
120741                 }
120742             }
120743             combineAndAddMultipleSingleLineComments();
120744             function combineAndAddMultipleSingleLineComments() {
120745                 // Only outline spans of two or more consecutive single line comments
120746                 if (singleLineCommentCount > 1) {
120747                     out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
120748                 }
120749             }
120750         }
120751         function createOutliningSpanFromBounds(pos, end, kind) {
120752             return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
120753         }
120754         function getOutliningSpanForNode(n, sourceFile) {
120755             switch (n.kind) {
120756                 case 223 /* Block */:
120757                     if (ts.isFunctionLike(n.parent)) {
120758                         return functionSpan(n.parent, n, sourceFile);
120759                     }
120760                     // Check if the block is standalone, or 'attached' to some parent statement.
120761                     // If the latter, we want to collapse the block, but consider its hint span
120762                     // to be the entire span of the parent.
120763                     switch (n.parent.kind) {
120764                         case 228 /* DoStatement */:
120765                         case 231 /* ForInStatement */:
120766                         case 232 /* ForOfStatement */:
120767                         case 230 /* ForStatement */:
120768                         case 227 /* IfStatement */:
120769                         case 229 /* WhileStatement */:
120770                         case 236 /* WithStatement */:
120771                         case 280 /* CatchClause */:
120772                             return spanForNode(n.parent);
120773                         case 240 /* TryStatement */:
120774                             // Could be the try-block, or the finally-block.
120775                             var tryStatement = n.parent;
120776                             if (tryStatement.tryBlock === n) {
120777                                 return spanForNode(n.parent);
120778                             }
120779                             else if (tryStatement.finallyBlock === n) {
120780                                 var node = ts.findChildOfKind(tryStatement, 92 /* FinallyKeyword */, sourceFile);
120781                                 if (node)
120782                                     return spanForNode(node);
120783                             }
120784                         // falls through
120785                         default:
120786                             // Block was a standalone block.  In this case we want to only collapse
120787                             // the span of the block, independent of any parent span.
120788                             return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
120789                     }
120790                 case 250 /* ModuleBlock */:
120791                     return spanForNode(n.parent);
120792                 case 245 /* ClassDeclaration */:
120793                 case 214 /* ClassExpression */:
120794                 case 246 /* InterfaceDeclaration */:
120795                 case 248 /* EnumDeclaration */:
120796                 case 251 /* CaseBlock */:
120797                 case 173 /* TypeLiteral */:
120798                     return spanForNode(n);
120799                 case 277 /* CaseClause */:
120800                 case 278 /* DefaultClause */:
120801                     return spanForNodeArray(n.statements);
120802                 case 193 /* ObjectLiteralExpression */:
120803                     return spanForObjectOrArrayLiteral(n);
120804                 case 192 /* ArrayLiteralExpression */:
120805                     return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */);
120806                 case 266 /* JsxElement */:
120807                     return spanForJSXElement(n);
120808                 case 270 /* JsxFragment */:
120809                     return spanForJSXFragment(n);
120810                 case 267 /* JsxSelfClosingElement */:
120811                 case 268 /* JsxOpeningElement */:
120812                     return spanForJSXAttributes(n.attributes);
120813                 case 211 /* TemplateExpression */:
120814                 case 14 /* NoSubstitutionTemplateLiteral */:
120815                     return spanForTemplateLiteral(n);
120816             }
120817             function spanForJSXElement(node) {
120818                 var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd());
120819                 var tagName = node.openingElement.tagName.getText(sourceFile);
120820                 var bannerText = "<" + tagName + ">...</" + tagName + ">";
120821                 return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
120822             }
120823             function spanForJSXFragment(node) {
120824                 var textSpan = ts.createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd());
120825                 var bannerText = "<>...</>";
120826                 return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText);
120827             }
120828             function spanForJSXAttributes(node) {
120829                 if (node.properties.length === 0) {
120830                     return undefined;
120831                 }
120832                 return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
120833             }
120834             function spanForTemplateLiteral(node) {
120835                 if (node.kind === 14 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) {
120836                     return undefined;
120837                 }
120838                 return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */);
120839             }
120840             function spanForObjectOrArrayLiteral(node, open) {
120841                 if (open === void 0) { open = 18 /* OpenBraceToken */; }
120842                 // If the block has no leading keywords and is inside an array literal or call expression,
120843                 // we only want to collapse the span of the block.
120844                 // Otherwise, the collapsed section will include the end of the previous line.
120845                 return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open);
120846             }
120847             function spanForNode(hintSpanNode, autoCollapse, useFullStart, open, close) {
120848                 if (autoCollapse === void 0) { autoCollapse = false; }
120849                 if (useFullStart === void 0) { useFullStart = true; }
120850                 if (open === void 0) { open = 18 /* OpenBraceToken */; }
120851                 if (close === void 0) { close = open === 18 /* OpenBraceToken */ ? 19 /* CloseBraceToken */ : 23 /* CloseBracketToken */; }
120852                 var openToken = ts.findChildOfKind(n, open, sourceFile);
120853                 var closeToken = ts.findChildOfKind(n, close, sourceFile);
120854                 return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart);
120855             }
120856             function spanForNodeArray(nodeArray) {
120857                 return nodeArray.length ? createOutliningSpan(ts.createTextSpanFromRange(nodeArray), "code" /* Code */) : undefined;
120858             }
120859         }
120860         function functionSpan(node, body, sourceFile) {
120861             var openToken = ts.isNodeArrayMultiLine(node.parameters, sourceFile)
120862                 ? ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile)
120863                 : ts.findChildOfKind(body, 18 /* OpenBraceToken */, sourceFile);
120864             var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile);
120865             return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 202 /* ArrowFunction */);
120866         }
120867         function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) {
120868             if (autoCollapse === void 0) { autoCollapse = false; }
120869             if (useFullStart === void 0) { useFullStart = true; }
120870             var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
120871             return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
120872         }
120873         function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
120874             if (hintSpan === void 0) { hintSpan = textSpan; }
120875             if (autoCollapse === void 0) { autoCollapse = false; }
120876             if (bannerText === void 0) { bannerText = "..."; }
120877             return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
120878         }
120879     })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
120880 })(ts || (ts = {}));
120881 /* @internal */
120882 var ts;
120883 (function (ts) {
120884     // Note(cyrusn): this enum is ordered from strongest match type to weakest match type.
120885     var PatternMatchKind;
120886     (function (PatternMatchKind) {
120887         PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact";
120888         PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix";
120889         PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring";
120890         PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase";
120891     })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {}));
120892     function createPatternMatch(kind, isCaseSensitive) {
120893         return {
120894             kind: kind,
120895             isCaseSensitive: isCaseSensitive
120896         };
120897     }
120898     function createPatternMatcher(pattern) {
120899         // We'll often see the same candidate string many times when searching (For example, when
120900         // we see the name of a module that is used everywhere, or the name of an overload).  As
120901         // such, we cache the information we compute about the candidate for the life of this
120902         // pattern matcher so we don't have to compute it multiple times.
120903         var stringToWordSpans = ts.createMap();
120904         var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); });
120905         // A segment is considered invalid if we couldn't find any words in it.
120906         if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; }))
120907             return undefined;
120908         return {
120909             getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); },
120910             getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); },
120911             patternContainsDots: dotSeparatedSegments.length > 1
120912         };
120913     }
120914     ts.createPatternMatcher = createPatternMatcher;
120915     function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) {
120916         // First, check that the last part of the dot separated pattern matches the name of the
120917         // candidate.  If not, then there's no point in proceeding and doing the more
120918         // expensive work.
120919         var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans);
120920         if (!candidateMatch) {
120921             return undefined;
120922         }
120923         // -1 because the last part was checked against the name, and only the rest
120924         // of the parts are checked against the container.
120925         if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
120926             // There weren't enough container parts to match against the pattern parts.
120927             // So this definitely doesn't match.
120928             return undefined;
120929         }
120930         var bestMatch;
120931         for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) {
120932             bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans));
120933         }
120934         return bestMatch;
120935     }
120936     function getWordSpans(word, stringToWordSpans) {
120937         var spans = stringToWordSpans.get(word);
120938         if (!spans) {
120939             stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
120940         }
120941         return spans;
120942     }
120943     function matchTextChunk(candidate, chunk, stringToWordSpans) {
120944         var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
120945         if (index === 0) {
120946             // a) Check if the word is a prefix of the candidate, in a case insensitive or
120947             //    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.
120948             return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
120949         }
120950         if (chunk.isLowerCase) {
120951             if (index === -1)
120952                 return undefined;
120953             // b) If the part is entirely lowercase, then check if it is contained anywhere in the
120954             //    candidate in a case insensitive manner.  If so, return that there was a substring
120955             //    match.
120956             //
120957             //    Note: We only have a substring match if the lowercase part is prefix match of some
120958             //    word part. That way we don't match something like 'Class' when the user types 'a'.
120959             //    But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
120960             var wordSpans = getWordSpans(candidate, stringToWordSpans);
120961             for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
120962                 var span = wordSpans_1[_i];
120963                 if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) {
120964                     return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false));
120965                 }
120966             }
120967             // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
120968             // We could check every character boundary start of the candidate for the pattern. However, that's
120969             // an m * n operation in the wost case. Instead, find the first instance of the pattern
120970             // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
120971             // filter the list based on a substring that starts on a capital letter and also with a lowercase one.
120972             // (Pattern: fogbar, Candidate: quuxfogbarFogBar).
120973             if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) {
120974                 return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false);
120975             }
120976         }
120977         else {
120978             // d) If the part was not entirely lowercase, then check if it is contained in the
120979             //    candidate in a case *sensitive* manner. If so, return that there was a substring
120980             //    match.
120981             if (candidate.indexOf(chunk.text) > 0) {
120982                 return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true);
120983             }
120984             // e) If the part was not entirely lowercase, then attempt a camel cased match as well.
120985             if (chunk.characterSpans.length > 0) {
120986                 var candidateParts = getWordSpans(candidate, stringToWordSpans);
120987                 var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true
120988                     : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined;
120989                 if (isCaseSensitive !== undefined) {
120990                     return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive);
120991                 }
120992             }
120993         }
120994     }
120995     function matchSegment(candidate, segment, stringToWordSpans) {
120996         // First check if the segment matches as is.  This is also useful if the segment contains
120997         // characters we would normally strip when splitting into parts that we also may want to
120998         // match in the candidate.  For example if the segment is "@int" and the candidate is
120999         // "@int", then that will show up as an exact match here.
121000         //
121001         // Note: if the segment contains a space or an asterisk then we must assume that it's a
121002         // multi-word segment.
121003         if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) {
121004             var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans);
121005             if (match)
121006                 return match;
121007         }
121008         // The logic for pattern matching is now as follows:
121009         //
121010         // 1) Break the segment passed in into words.  Breaking is rather simple and a
121011         //    good way to think about it that if gives you all the individual alphanumeric words
121012         //    of the pattern.
121013         //
121014         // 2) For each word try to match the word against the candidate value.
121015         //
121016         // 3) Matching is as follows:
121017         //
121018         //   a) Check if the word is a prefix of the candidate, in a case insensitive or
121019         //      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.
121020         //
121021         //   If the word is entirely lowercase:
121022         //      b) Then check if it is contained anywhere in the
121023         //          candidate in a case insensitive manner.  If so, return that there was a substring
121024         //          match.
121025         //
121026         //          Note: We only have a substring match if the lowercase part is prefix match of
121027         //          some word part. That way we don't match something like 'Class' when the user
121028         //          types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
121029         //          'a').
121030         //
121031         //       c) The word is all lower case. Is it a case insensitive substring of the candidate starting
121032         //          on a part boundary of the candidate?
121033         //
121034         //   Else:
121035         //       d) If the word was not entirely lowercase, then check if it is contained in the
121036         //          candidate in a case *sensitive* manner. If so, return that there was a substring
121037         //          match.
121038         //
121039         //       e) If the word was not entirely lowercase, then attempt a camel cased match as
121040         //          well.
121041         //
121042         // Only if all words have some sort of match is the pattern considered matched.
121043         var subWordTextChunks = segment.subWordTextChunks;
121044         var bestMatch;
121045         for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) {
121046             var subWordTextChunk = subWordTextChunks_1[_i];
121047             bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans));
121048         }
121049         return bestMatch;
121050     }
121051     function betterMatch(a, b) {
121052         return ts.min(a, b, compareMatches);
121053     }
121054     function compareMatches(a, b) {
121055         return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */
121056             : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive);
121057     }
121058     function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) {
121059         if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; }
121060         return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match.
121061             && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); });
121062     }
121063     function equalChars(ch1, ch2, ignoreCase) {
121064         return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2;
121065     }
121066     function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) {
121067         var chunkCharacterSpans = chunk.characterSpans;
121068         // Note: we may have more pattern parts than candidate parts.  This is because multiple
121069         // pattern parts may match a candidate part.  For example "SiUI" against "SimpleUI".
121070         // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI.  However, U
121071         // and I will both match in UI.
121072         var currentCandidate = 0;
121073         var currentChunkSpan = 0;
121074         var firstMatch;
121075         var contiguous;
121076         while (true) {
121077             // Let's consider our termination cases
121078             if (currentChunkSpan === chunkCharacterSpans.length) {
121079                 return true;
121080             }
121081             else if (currentCandidate === candidateParts.length) {
121082                 // No match, since we still have more of the pattern to hit
121083                 return false;
121084             }
121085             var candidatePart = candidateParts[currentCandidate];
121086             var gotOneMatchThisCandidate = false;
121087             // Consider the case of matching SiUI against SimpleUIElement. The candidate parts
121088             // will be Simple/UI/Element, and the pattern parts will be Si/U/I.  We'll match 'Si'
121089             // against 'Simple' first.  Then we'll match 'U' against 'UI'. However, we want to
121090             // still keep matching pattern parts against that candidate part.
121091             for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
121092                 var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
121093                 if (gotOneMatchThisCandidate) {
121094                     // We've already gotten one pattern part match in this candidate.  We will
121095                     // only continue trying to consumer pattern parts if the last part and this
121096                     // part are both upper case.
121097                     if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) ||
121098                         !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
121099                         break;
121100                     }
121101                 }
121102                 if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) {
121103                     break;
121104                 }
121105                 gotOneMatchThisCandidate = true;
121106                 firstMatch = firstMatch === undefined ? currentCandidate : firstMatch;
121107                 // If we were contiguous, then keep that value.  If we weren't, then keep that
121108                 // value.  If we don't know, then set the value to 'true' as an initial match is
121109                 // obviously contiguous.
121110                 contiguous = contiguous === undefined ? true : contiguous;
121111                 candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length);
121112             }
121113             // Check if we matched anything at all.  If we didn't, then we need to unset the
121114             // contiguous bit if we currently had it set.
121115             // If we haven't set the bit yet, then that means we haven't matched anything so
121116             // far, and we don't want to change that.
121117             if (!gotOneMatchThisCandidate && contiguous !== undefined) {
121118                 contiguous = false;
121119             }
121120             // Move onto the next candidate.
121121             currentCandidate++;
121122         }
121123     }
121124     function createSegment(text) {
121125         return {
121126             totalTextChunk: createTextChunk(text),
121127             subWordTextChunks: breakPatternIntoTextChunks(text)
121128         };
121129     }
121130     function isUpperCaseLetter(ch) {
121131         // Fast check for the ascii range.
121132         if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
121133             return true;
121134         }
121135         if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
121136             return false;
121137         }
121138         // TODO: find a way to determine this for any unicode characters in a
121139         // non-allocating manner.
121140         var str = String.fromCharCode(ch);
121141         return str === str.toUpperCase();
121142     }
121143     function isLowerCaseLetter(ch) {
121144         // Fast check for the ascii range.
121145         if (ch >= 97 /* a */ && ch <= 122 /* z */) {
121146             return true;
121147         }
121148         if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 99 /* Latest */)) {
121149             return false;
121150         }
121151         // TODO: find a way to determine this for any unicode characters in a
121152         // non-allocating manner.
121153         var str = String.fromCharCode(ch);
121154         return str === str.toLowerCase();
121155     }
121156     // Assumes 'value' is already lowercase.
121157     function indexOfIgnoringCase(str, value) {
121158         var n = str.length - value.length;
121159         var _loop_6 = function (start) {
121160             if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
121161                 return { value: start };
121162             }
121163         };
121164         for (var start = 0; start <= n; start++) {
121165             var state_1 = _loop_6(start);
121166             if (typeof state_1 === "object")
121167                 return state_1.value;
121168         }
121169         return -1;
121170     }
121171     function toLowerCase(ch) {
121172         // Fast convert for the ascii range.
121173         if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
121174             return 97 /* a */ + (ch - 65 /* A */);
121175         }
121176         if (ch < 127 /* maxAsciiCharacter */) {
121177             return ch;
121178         }
121179         // TODO: find a way to compute this for any unicode characters in a
121180         // non-allocating manner.
121181         return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
121182     }
121183     function isDigit(ch) {
121184         // TODO(cyrusn): Find a way to support this for unicode digits.
121185         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
121186     }
121187     function isWordChar(ch) {
121188         return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */;
121189     }
121190     function breakPatternIntoTextChunks(pattern) {
121191         var result = [];
121192         var wordStart = 0;
121193         var wordLength = 0;
121194         for (var i = 0; i < pattern.length; i++) {
121195             var ch = pattern.charCodeAt(i);
121196             if (isWordChar(ch)) {
121197                 if (wordLength === 0) {
121198                     wordStart = i;
121199                 }
121200                 wordLength++;
121201             }
121202             else {
121203                 if (wordLength > 0) {
121204                     result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
121205                     wordLength = 0;
121206                 }
121207             }
121208         }
121209         if (wordLength > 0) {
121210             result.push(createTextChunk(pattern.substr(wordStart, wordLength)));
121211         }
121212         return result;
121213     }
121214     function createTextChunk(text) {
121215         var textLowerCase = text.toLowerCase();
121216         return {
121217             text: text,
121218             textLowerCase: textLowerCase,
121219             isLowerCase: text === textLowerCase,
121220             characterSpans: breakIntoCharacterSpans(text)
121221         };
121222     }
121223     function breakIntoCharacterSpans(identifier) {
121224         return breakIntoSpans(identifier, /*word:*/ false);
121225     }
121226     ts.breakIntoCharacterSpans = breakIntoCharacterSpans;
121227     function breakIntoWordSpans(identifier) {
121228         return breakIntoSpans(identifier, /*word:*/ true);
121229     }
121230     ts.breakIntoWordSpans = breakIntoWordSpans;
121231     function breakIntoSpans(identifier, word) {
121232         var result = [];
121233         var wordStart = 0;
121234         for (var i = 1; i < identifier.length; i++) {
121235             var lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
121236             var currentIsDigit = isDigit(identifier.charCodeAt(i));
121237             var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
121238             var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart);
121239             if (charIsPunctuation(identifier.charCodeAt(i - 1)) ||
121240                 charIsPunctuation(identifier.charCodeAt(i)) ||
121241                 lastIsDigit !== currentIsDigit ||
121242                 hasTransitionFromLowerToUpper ||
121243                 hasTransitionFromUpperToLower) {
121244                 if (!isAllPunctuation(identifier, wordStart, i)) {
121245                     result.push(ts.createTextSpan(wordStart, i - wordStart));
121246                 }
121247                 wordStart = i;
121248             }
121249         }
121250         if (!isAllPunctuation(identifier, wordStart, identifier.length)) {
121251             result.push(ts.createTextSpan(wordStart, identifier.length - wordStart));
121252         }
121253         return result;
121254     }
121255     function charIsPunctuation(ch) {
121256         switch (ch) {
121257             case 33 /* exclamation */:
121258             case 34 /* doubleQuote */:
121259             case 35 /* hash */:
121260             case 37 /* percent */:
121261             case 38 /* ampersand */:
121262             case 39 /* singleQuote */:
121263             case 40 /* openParen */:
121264             case 41 /* closeParen */:
121265             case 42 /* asterisk */:
121266             case 44 /* comma */:
121267             case 45 /* minus */:
121268             case 46 /* dot */:
121269             case 47 /* slash */:
121270             case 58 /* colon */:
121271             case 59 /* semicolon */:
121272             case 63 /* question */:
121273             case 64 /* at */:
121274             case 91 /* openBracket */:
121275             case 92 /* backslash */:
121276             case 93 /* closeBracket */:
121277             case 95 /* _ */:
121278             case 123 /* openBrace */:
121279             case 125 /* closeBrace */:
121280                 return true;
121281         }
121282         return false;
121283     }
121284     function isAllPunctuation(identifier, start, end) {
121285         return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end);
121286     }
121287     function transitionFromUpperToLower(identifier, index, wordStart) {
121288         // Cases this supports:
121289         // 1) IDisposable -> I, Disposable
121290         // 2) UIElement -> UI, Element
121291         // 3) HTMLDocument -> HTML, Document
121292         //
121293         // etc.
121294         // We have a transition from an upper to a lower letter here.  But we only
121295         // want to break if all the letters that preceded are uppercase.  i.e. if we
121296         // have "Foo" we don't want to break that into "F, oo".  But if we have
121297         // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI,
121298         // Foo".  i.e. the last uppercase letter belongs to the lowercase letters
121299         // that follows.  Note: this will make the following not split properly:
121300         // "HELLOthere".  However, these sorts of names do not show up in .Net
121301         // programs.
121302         return index !== wordStart
121303             && index + 1 < identifier.length
121304             && isUpperCaseLetter(identifier.charCodeAt(index))
121305             && isLowerCaseLetter(identifier.charCodeAt(index + 1))
121306             && every(identifier, isUpperCaseLetter, wordStart, index);
121307     }
121308     function transitionFromLowerToUpper(identifier, word, index) {
121309         var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
121310         var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
121311         // See if the casing indicates we're starting a new word. Note: if we're breaking on
121312         // words, then just seeing an upper case character isn't enough.  Instead, it has to
121313         // be uppercase and the previous character can't be uppercase.
121314         //
121315         // For example, breaking "AddMetadata" on words would make: Add Metadata
121316         //
121317         // on characters would be: A dd M etadata
121318         //
121319         // Break "AM" on words would be: AM
121320         //
121321         // on characters would be: A M
121322         //
121323         // We break the search string on characters.  But we break the symbol name on words.
121324         return currentIsUpper && (!word || !lastIsUpper);
121325     }
121326     function everyInRange(start, end, pred) {
121327         for (var i = start; i < end; i++) {
121328             if (!pred(i)) {
121329                 return false;
121330             }
121331         }
121332         return true;
121333     }
121334     function every(s, pred, start, end) {
121335         if (start === void 0) { start = 0; }
121336         if (end === void 0) { end = s.length; }
121337         return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); });
121338     }
121339 })(ts || (ts = {}));
121340 var ts;
121341 (function (ts) {
121342     function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) {
121343         if (readImportFiles === void 0) { readImportFiles = true; }
121344         if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; }
121345         var pragmaContext = {
121346             languageVersion: 1 /* ES5 */,
121347             pragmas: undefined,
121348             checkJsDirective: undefined,
121349             referencedFiles: [],
121350             typeReferenceDirectives: [],
121351             libReferenceDirectives: [],
121352             amdDependencies: [],
121353             hasNoDefaultLib: undefined,
121354             moduleName: undefined
121355         };
121356         var importedFiles = [];
121357         var ambientExternalModules;
121358         var lastToken;
121359         var currentToken;
121360         var braceNesting = 0;
121361         // assume that text represent an external module if it contains at least one top level import/export
121362         // ambient modules that are found inside external modules are interpreted as module augmentations
121363         var externalModule = false;
121364         function nextToken() {
121365             lastToken = currentToken;
121366             currentToken = ts.scanner.scan();
121367             if (currentToken === 18 /* OpenBraceToken */) {
121368                 braceNesting++;
121369             }
121370             else if (currentToken === 19 /* CloseBraceToken */) {
121371                 braceNesting--;
121372             }
121373             return currentToken;
121374         }
121375         function getFileReference() {
121376             var fileName = ts.scanner.getTokenValue();
121377             var pos = ts.scanner.getTokenPos();
121378             return { fileName: fileName, pos: pos, end: pos + fileName.length };
121379         }
121380         function recordAmbientExternalModule() {
121381             if (!ambientExternalModules) {
121382                 ambientExternalModules = [];
121383             }
121384             ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
121385         }
121386         function recordModuleName() {
121387             importedFiles.push(getFileReference());
121388             markAsExternalModuleIfTopLevel();
121389         }
121390         function markAsExternalModuleIfTopLevel() {
121391             if (braceNesting === 0) {
121392                 externalModule = true;
121393             }
121394         }
121395         /**
121396          * Returns true if at least one token was consumed from the stream
121397          */
121398         function tryConsumeDeclare() {
121399             var token = ts.scanner.getToken();
121400             if (token === 130 /* DeclareKeyword */) {
121401                 // declare module "mod"
121402                 token = nextToken();
121403                 if (token === 135 /* ModuleKeyword */) {
121404                     token = nextToken();
121405                     if (token === 10 /* StringLiteral */) {
121406                         recordAmbientExternalModule();
121407                     }
121408                 }
121409                 return true;
121410             }
121411             return false;
121412         }
121413         /**
121414          * Returns true if at least one token was consumed from the stream
121415          */
121416         function tryConsumeImport() {
121417             if (lastToken === 24 /* DotToken */) {
121418                 return false;
121419             }
121420             var token = ts.scanner.getToken();
121421             if (token === 96 /* ImportKeyword */) {
121422                 token = nextToken();
121423                 if (token === 20 /* OpenParenToken */) {
121424                     token = nextToken();
121425                     if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) {
121426                         // import("mod");
121427                         recordModuleName();
121428                         return true;
121429                     }
121430                 }
121431                 else if (token === 10 /* StringLiteral */) {
121432                     // import "mod";
121433                     recordModuleName();
121434                     return true;
121435                 }
121436                 else {
121437                     if (token === 145 /* TypeKeyword */) {
121438                         var skipTypeKeyword = ts.scanner.lookAhead(function () {
121439                             var token = ts.scanner.scan();
121440                             return token !== 149 /* FromKeyword */ && (token === 41 /* AsteriskToken */ ||
121441                                 token === 18 /* OpenBraceToken */ ||
121442                                 token === 75 /* Identifier */ ||
121443                                 ts.isKeyword(token));
121444                         });
121445                         if (skipTypeKeyword) {
121446                             token = nextToken();
121447                         }
121448                     }
121449                     if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
121450                         token = nextToken();
121451                         if (token === 149 /* FromKeyword */) {
121452                             token = nextToken();
121453                             if (token === 10 /* StringLiteral */) {
121454                                 // import d from "mod";
121455                                 recordModuleName();
121456                                 return true;
121457                             }
121458                         }
121459                         else if (token === 62 /* EqualsToken */) {
121460                             if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
121461                                 return true;
121462                             }
121463                         }
121464                         else if (token === 27 /* CommaToken */) {
121465                             // consume comma and keep going
121466                             token = nextToken();
121467                         }
121468                         else {
121469                             // unknown syntax
121470                             return true;
121471                         }
121472                     }
121473                     if (token === 18 /* OpenBraceToken */) {
121474                         token = nextToken();
121475                         // consume "{ a as B, c, d as D}" clauses
121476                         // make sure that it stops on EOF
121477                         while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
121478                             token = nextToken();
121479                         }
121480                         if (token === 19 /* CloseBraceToken */) {
121481                             token = nextToken();
121482                             if (token === 149 /* FromKeyword */) {
121483                                 token = nextToken();
121484                                 if (token === 10 /* StringLiteral */) {
121485                                     // import {a as A} from "mod";
121486                                     // import d, {a, b as B} from "mod"
121487                                     recordModuleName();
121488                                 }
121489                             }
121490                         }
121491                     }
121492                     else if (token === 41 /* AsteriskToken */) {
121493                         token = nextToken();
121494                         if (token === 123 /* AsKeyword */) {
121495                             token = nextToken();
121496                             if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
121497                                 token = nextToken();
121498                                 if (token === 149 /* FromKeyword */) {
121499                                     token = nextToken();
121500                                     if (token === 10 /* StringLiteral */) {
121501                                         // import * as NS from "mod"
121502                                         // import d, * as NS from "mod"
121503                                         recordModuleName();
121504                                     }
121505                                 }
121506                             }
121507                         }
121508                     }
121509                 }
121510                 return true;
121511             }
121512             return false;
121513         }
121514         function tryConsumeExport() {
121515             var token = ts.scanner.getToken();
121516             if (token === 89 /* ExportKeyword */) {
121517                 markAsExternalModuleIfTopLevel();
121518                 token = nextToken();
121519                 if (token === 145 /* TypeKeyword */) {
121520                     var skipTypeKeyword = ts.scanner.lookAhead(function () {
121521                         var token = ts.scanner.scan();
121522                         return token === 41 /* AsteriskToken */ ||
121523                             token === 18 /* OpenBraceToken */;
121524                     });
121525                     if (skipTypeKeyword) {
121526                         token = nextToken();
121527                     }
121528                 }
121529                 if (token === 18 /* OpenBraceToken */) {
121530                     token = nextToken();
121531                     // consume "{ a as B, c, d as D}" clauses
121532                     // make sure it stops on EOF
121533                     while (token !== 19 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) {
121534                         token = nextToken();
121535                     }
121536                     if (token === 19 /* CloseBraceToken */) {
121537                         token = nextToken();
121538                         if (token === 149 /* FromKeyword */) {
121539                             token = nextToken();
121540                             if (token === 10 /* StringLiteral */) {
121541                                 // export {a as A} from "mod";
121542                                 // export {a, b as B} from "mod"
121543                                 recordModuleName();
121544                             }
121545                         }
121546                     }
121547                 }
121548                 else if (token === 41 /* AsteriskToken */) {
121549                     token = nextToken();
121550                     if (token === 149 /* FromKeyword */) {
121551                         token = nextToken();
121552                         if (token === 10 /* StringLiteral */) {
121553                             // export * from "mod"
121554                             recordModuleName();
121555                         }
121556                     }
121557                 }
121558                 else if (token === 96 /* ImportKeyword */) {
121559                     token = nextToken();
121560                     if (token === 145 /* TypeKeyword */) {
121561                         var skipTypeKeyword = ts.scanner.lookAhead(function () {
121562                             var token = ts.scanner.scan();
121563                             return token === 75 /* Identifier */ ||
121564                                 ts.isKeyword(token);
121565                         });
121566                         if (skipTypeKeyword) {
121567                             token = nextToken();
121568                         }
121569                     }
121570                     if (token === 75 /* Identifier */ || ts.isKeyword(token)) {
121571                         token = nextToken();
121572                         if (token === 62 /* EqualsToken */) {
121573                             if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
121574                                 return true;
121575                             }
121576                         }
121577                     }
121578                 }
121579                 return true;
121580             }
121581             return false;
121582         }
121583         function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals) {
121584             if (allowTemplateLiterals === void 0) { allowTemplateLiterals = false; }
121585             var token = skipCurrentToken ? nextToken() : ts.scanner.getToken();
121586             if (token === 139 /* RequireKeyword */) {
121587                 token = nextToken();
121588                 if (token === 20 /* OpenParenToken */) {
121589                     token = nextToken();
121590                     if (token === 10 /* StringLiteral */ ||
121591                         allowTemplateLiterals && token === 14 /* NoSubstitutionTemplateLiteral */) {
121592                         //  require("mod");
121593                         recordModuleName();
121594                     }
121595                 }
121596                 return true;
121597             }
121598             return false;
121599         }
121600         function tryConsumeDefine() {
121601             var token = ts.scanner.getToken();
121602             if (token === 75 /* Identifier */ && ts.scanner.getTokenValue() === "define") {
121603                 token = nextToken();
121604                 if (token !== 20 /* OpenParenToken */) {
121605                     return true;
121606                 }
121607                 token = nextToken();
121608                 if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) {
121609                     // looks like define ("modname", ... - skip string literal and comma
121610                     token = nextToken();
121611                     if (token === 27 /* CommaToken */) {
121612                         token = nextToken();
121613                     }
121614                     else {
121615                         // unexpected token
121616                         return true;
121617                     }
121618                 }
121619                 // should be start of dependency list
121620                 if (token !== 22 /* OpenBracketToken */) {
121621                     return true;
121622                 }
121623                 // skip open bracket
121624                 token = nextToken();
121625                 // scan until ']' or EOF
121626                 while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) {
121627                     // record string literals as module names
121628                     if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) {
121629                         recordModuleName();
121630                     }
121631                     token = nextToken();
121632                 }
121633                 return true;
121634             }
121635             return false;
121636         }
121637         function processImports() {
121638             ts.scanner.setText(sourceText);
121639             nextToken();
121640             // Look for:
121641             //    import "mod";
121642             //    import d from "mod"
121643             //    import {a as A } from "mod";
121644             //    import * as NS from "mod"
121645             //    import d, {a, b as B} from "mod"
121646             //    import i = require("mod");
121647             //    import("mod");
121648             //    export * from "mod"
121649             //    export {a as b} from "mod"
121650             //    export import i = require("mod")
121651             //    (for JavaScript files) require("mod")
121652             // Do not look for:
121653             //    AnySymbol.import("mod")
121654             //    AnySymbol.nested.import("mod")
121655             while (true) {
121656                 if (ts.scanner.getToken() === 1 /* EndOfFileToken */) {
121657                     break;
121658                 }
121659                 // check if at least one of alternative have moved scanner forward
121660                 if (tryConsumeDeclare() ||
121661                     tryConsumeImport() ||
121662                     tryConsumeExport() ||
121663                     (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false, /*allowTemplateLiterals*/ true) ||
121664                         tryConsumeDefine()))) {
121665                     continue;
121666                 }
121667                 else {
121668                     nextToken();
121669                 }
121670             }
121671             ts.scanner.setText(undefined);
121672         }
121673         if (readImportFiles) {
121674             processImports();
121675         }
121676         ts.processCommentPragmas(pragmaContext, sourceText);
121677         ts.processPragmasIntoFields(pragmaContext, ts.noop);
121678         if (externalModule) {
121679             // for external modules module all nested ambient modules are augmentations
121680             if (ambientExternalModules) {
121681                 // move all detected ambient modules to imported files since they need to be resolved
121682                 for (var _i = 0, ambientExternalModules_1 = ambientExternalModules; _i < ambientExternalModules_1.length; _i++) {
121683                     var decl = ambientExternalModules_1[_i];
121684                     importedFiles.push(decl.ref);
121685                 }
121686             }
121687             return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined };
121688         }
121689         else {
121690             // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
121691             var ambientModuleNames = void 0;
121692             if (ambientExternalModules) {
121693                 for (var _a = 0, ambientExternalModules_2 = ambientExternalModules; _a < ambientExternalModules_2.length; _a++) {
121694                     var decl = ambientExternalModules_2[_a];
121695                     if (decl.depth === 0) {
121696                         if (!ambientModuleNames) {
121697                             ambientModuleNames = [];
121698                         }
121699                         ambientModuleNames.push(decl.ref.fileName);
121700                     }
121701                     else {
121702                         importedFiles.push(decl.ref);
121703                     }
121704                 }
121705             }
121706             return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames };
121707         }
121708     }
121709     ts.preProcessFile = preProcessFile;
121710 })(ts || (ts = {}));
121711 /* @internal */
121712 var ts;
121713 (function (ts) {
121714     var Rename;
121715     (function (Rename) {
121716         function getRenameInfo(program, sourceFile, position, options) {
121717             var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position));
121718             if (nodeIsEligibleForRename(node)) {
121719                 var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options);
121720                 if (renameInfo) {
121721                     return renameInfo;
121722                 }
121723             }
121724             return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
121725         }
121726         Rename.getRenameInfo = getRenameInfo;
121727         function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) {
121728             var symbol = typeChecker.getSymbolAtLocation(node);
121729             if (!symbol)
121730                 return;
121731             // Only allow a symbol to be renamed if it actually has at least one declaration.
121732             var declarations = symbol.declarations;
121733             if (!declarations || declarations.length === 0)
121734                 return;
121735             // Disallow rename for elements that are defined in the standard TypeScript library.
121736             if (declarations.some(isDefinedInLibraryFile)) {
121737                 return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
121738             }
121739             // Cannot rename `default` as in `import { default as foo } from "./someModule";
121740             if (ts.isIdentifier(node) && node.originalKeywordKind === 84 /* DefaultKeyword */ && symbol.parent && symbol.parent.flags & 1536 /* Module */) {
121741                 return undefined;
121742             }
121743             if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) {
121744                 return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined;
121745             }
121746             var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
121747             var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 154 /* ComputedPropertyName */)
121748                 ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
121749                 : undefined;
121750             var displayName = specifierName || typeChecker.symbolToString(symbol);
121751             var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
121752             return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile);
121753         }
121754         function getRenameInfoForModule(node, sourceFile, moduleSymbol) {
121755             if (!ts.isExternalModuleNameRelative(node.text)) {
121756                 return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import);
121757             }
121758             var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile);
121759             if (!moduleSourceFile)
121760                 return undefined;
121761             var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index");
121762             var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;
121763             var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */;
121764             var indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
121765             // Span should only be the last component of the path. + 1 to account for the quote character.
121766             var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
121767             return {
121768                 canRename: true,
121769                 fileToRename: name,
121770                 kind: kind,
121771                 displayName: name,
121772                 fullDisplayName: name,
121773                 kindModifiers: "" /* none */,
121774                 triggerSpan: triggerSpan,
121775             };
121776         }
121777         function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
121778             return {
121779                 canRename: true,
121780                 fileToRename: undefined,
121781                 kind: kind,
121782                 displayName: displayName,
121783                 fullDisplayName: fullDisplayName,
121784                 kindModifiers: kindModifiers,
121785                 triggerSpan: createTriggerSpanForNode(node, sourceFile)
121786             };
121787         }
121788         function getRenameInfoError(diagnostic) {
121789             return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) };
121790         }
121791         function createTriggerSpanForNode(node, sourceFile) {
121792             var start = node.getStart(sourceFile);
121793             var width = node.getWidth(sourceFile);
121794             if (ts.isStringLiteralLike(node)) {
121795                 // Exclude the quotes
121796                 start += 1;
121797                 width -= 2;
121798             }
121799             return ts.createTextSpan(start, width);
121800         }
121801         function nodeIsEligibleForRename(node) {
121802             switch (node.kind) {
121803                 case 75 /* Identifier */:
121804                 case 76 /* PrivateIdentifier */:
121805                 case 10 /* StringLiteral */:
121806                 case 14 /* NoSubstitutionTemplateLiteral */:
121807                 case 104 /* ThisKeyword */:
121808                     return true;
121809                 case 8 /* NumericLiteral */:
121810                     return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node);
121811                 default:
121812                     return false;
121813             }
121814         }
121815     })(Rename = ts.Rename || (ts.Rename = {}));
121816 })(ts || (ts = {}));
121817 /* @internal */
121818 var ts;
121819 (function (ts) {
121820     var SmartSelectionRange;
121821     (function (SmartSelectionRange) {
121822         function getSmartSelectionRange(pos, sourceFile) {
121823             var selectionRange = {
121824                 textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd())
121825             };
121826             var parentNode = sourceFile;
121827             outer: while (true) {
121828                 var children = getSelectionChildren(parentNode);
121829                 if (!children.length)
121830                     break;
121831                 for (var i = 0; i < children.length; i++) {
121832                     var prevNode = children[i - 1];
121833                     var node = children[i];
121834                     var nextNode = children[i + 1];
121835                     if (node.getStart(sourceFile) > pos) {
121836                         break outer;
121837                     }
121838                     if (positionShouldSnapToNode(sourceFile, pos, node)) {
121839                         // 1. Blocks are effectively redundant with SyntaxLists.
121840                         // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping
121841                         //    of things that should be considered independently.
121842                         // 3. A VariableStatement’s children are just a VaraiableDeclarationList and a semicolon.
121843                         // 4. A lone VariableDeclaration in a VaraibleDeclaration feels redundant with the VariableStatement.
121844                         //
121845                         // Dive in without pushing a selection range.
121846                         if (ts.isBlock(node)
121847                             || ts.isTemplateSpan(node) || ts.isTemplateHead(node) || ts.isTemplateTail(node)
121848                             || prevNode && ts.isTemplateHead(prevNode)
121849                             || ts.isVariableDeclarationList(node) && ts.isVariableStatement(parentNode)
121850                             || ts.isSyntaxList(node) && ts.isVariableDeclarationList(parentNode)
121851                             || ts.isVariableDeclaration(node) && ts.isSyntaxList(parentNode) && children.length === 1) {
121852                             parentNode = node;
121853                             break;
121854                         }
121855                         // Synthesize a stop for '${ ... }' since '${' and '}' actually belong to siblings.
121856                         if (ts.isTemplateSpan(parentNode) && nextNode && ts.isTemplateMiddleOrTemplateTail(nextNode)) {
121857                             var start_2 = node.getFullStart() - "${".length;
121858                             var end_2 = nextNode.getStart() + "}".length;
121859                             pushSelectionRange(start_2, end_2);
121860                         }
121861                         // Blocks with braces, brackets, parens, or JSX tags on separate lines should be
121862                         // selected from open to close, including whitespace but not including the braces/etc. themselves.
121863                         var isBetweenMultiLineBookends = ts.isSyntaxList(node)
121864                             && isListOpener(prevNode)
121865                             && isListCloser(nextNode)
121866                             && !ts.positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
121867                         var jsDocCommentStart = ts.hasJSDocNodes(node) && node.jsDoc[0].getStart();
121868                         var start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
121869                         var end = isBetweenMultiLineBookends ? nextNode.getStart() : node.getEnd();
121870                         if (ts.isNumber(jsDocCommentStart)) {
121871                             pushSelectionRange(jsDocCommentStart, end);
121872                         }
121873                         pushSelectionRange(start, end);
121874                         // String literals should have a stop both inside and outside their quotes.
121875                         if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) {
121876                             pushSelectionRange(start + 1, end - 1);
121877                         }
121878                         parentNode = node;
121879                         break;
121880                     }
121881                     // If we made it to the end of the for loop, we’re done.
121882                     // In practice, I’ve only seen this happen at the very end
121883                     // of a SourceFile.
121884                     if (i === children.length - 1) {
121885                         break outer;
121886                     }
121887                 }
121888             }
121889             return selectionRange;
121890             function pushSelectionRange(start, end) {
121891                 // Skip empty ranges
121892                 if (start !== end) {
121893                     var textSpan = ts.createTextSpanFromBounds(start, end);
121894                     if (!selectionRange || (
121895                     // Skip ranges that are identical to the parent
121896                     !ts.textSpansEqual(textSpan, selectionRange.textSpan) &&
121897                         // Skip ranges that don’t contain the original position
121898                         ts.textSpanIntersectsWithPosition(textSpan, pos))) {
121899                         selectionRange = __assign({ textSpan: textSpan }, selectionRange && { parent: selectionRange });
121900                     }
121901                 }
121902             }
121903         }
121904         SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange;
121905         /**
121906          * Like `ts.positionBelongsToNode`, except positions immediately after nodes
121907          * count too, unless that position belongs to the next node. In effect, makes
121908          * selections able to snap to preceding tokens when the cursor is on the tail
121909          * end of them with only whitespace ahead.
121910          * @param sourceFile The source file containing the nodes.
121911          * @param pos The position to check.
121912          * @param node The candidate node to snap to.
121913          */
121914         function positionShouldSnapToNode(sourceFile, pos, node) {
121915             // Can’t use 'ts.positionBelongsToNode()' here because it cleverly accounts
121916             // for missing nodes, which can’t really be considered when deciding what
121917             // to select.
121918             ts.Debug.assert(node.pos <= pos);
121919             if (pos < node.end) {
121920                 return true;
121921             }
121922             var nodeEnd = node.getEnd();
121923             if (nodeEnd === pos) {
121924                 return ts.getTouchingPropertyName(sourceFile, pos).pos < node.end;
121925             }
121926             return false;
121927         }
121928         var isImport = ts.or(ts.isImportDeclaration, ts.isImportEqualsDeclaration);
121929         /**
121930          * Gets the children of a node to be considered for selection ranging,
121931          * transforming them into an artificial tree according to their intuitive
121932          * grouping where no grouping actually exists in the parse tree. For example,
121933          * top-level imports are grouped into their own SyntaxList so they can be
121934          * selected all together, even though in the AST they’re just siblings of each
121935          * other as well as of other top-level statements and declarations.
121936          */
121937         function getSelectionChildren(node) {
121938             // Group top-level imports
121939             if (ts.isSourceFile(node)) {
121940                 return groupChildren(node.getChildAt(0).getChildren(), isImport);
121941             }
121942             // Mapped types _look_ like ObjectTypes with a single member,
121943             // but in fact don’t contain a SyntaxList or a node containing
121944             // the “key/value” pair like ObjectTypes do, but it seems intuitive
121945             // that the selection would snap to those points. The philosophy
121946             // of choosing a selection range is not so much about what the
121947             // syntax currently _is_ as what the syntax might easily become
121948             // if the user is making a selection; e.g., we synthesize a selection
121949             // around the “key/value” pair not because there’s a node there, but
121950             // because it allows the mapped type to become an object type with a
121951             // few keystrokes.
121952             if (ts.isMappedTypeNode(node)) {
121953                 var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1);
121954                 var closeBraceToken = ts.Debug.checkDefined(children.pop());
121955                 ts.Debug.assertEqual(openBraceToken.kind, 18 /* OpenBraceToken */);
121956                 ts.Debug.assertEqual(closeBraceToken.kind, 19 /* CloseBraceToken */);
121957                 // Group `-/+readonly` and `-/+?`
121958                 var groupedWithPlusMinusTokens = groupChildren(children, function (child) {
121959                     return child === node.readonlyToken || child.kind === 138 /* ReadonlyKeyword */ ||
121960                         child === node.questionToken || child.kind === 57 /* QuestionToken */;
121961                 });
121962                 // Group type parameter with surrounding brackets
121963                 var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) {
121964                     var kind = _a.kind;
121965                     return kind === 22 /* OpenBracketToken */ ||
121966                         kind === 155 /* TypeParameter */ ||
121967                         kind === 23 /* CloseBracketToken */;
121968                 });
121969                 return [
121970                     openBraceToken,
121971                     // Pivot on `:`
121972                     createSyntaxList(splitChildren(groupedWithBrackets, function (_a) {
121973                         var kind = _a.kind;
121974                         return kind === 58 /* ColonToken */;
121975                     })),
121976                     closeBraceToken,
121977                 ];
121978             }
121979             // Group modifiers and property name, then pivot on `:`.
121980             if (ts.isPropertySignature(node)) {
121981                 var children = groupChildren(node.getChildren(), function (child) {
121982                     return child === node.name || ts.contains(node.modifiers, child);
121983                 });
121984                 return splitChildren(children, function (_a) {
121985                     var kind = _a.kind;
121986                     return kind === 58 /* ColonToken */;
121987                 });
121988             }
121989             // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`.
121990             if (ts.isParameter(node)) {
121991                 var groupedDotDotDotAndName_1 = groupChildren(node.getChildren(), function (child) {
121992                     return child === node.dotDotDotToken || child === node.name;
121993                 });
121994                 var groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName_1, function (child) {
121995                     return child === groupedDotDotDotAndName_1[0] || child === node.questionToken;
121996                 });
121997                 return splitChildren(groupedWithQuestionToken, function (_a) {
121998                     var kind = _a.kind;
121999                     return kind === 62 /* EqualsToken */;
122000                 });
122001             }
122002             // Pivot on '='
122003             if (ts.isBindingElement(node)) {
122004                 return splitChildren(node.getChildren(), function (_a) {
122005                     var kind = _a.kind;
122006                     return kind === 62 /* EqualsToken */;
122007                 });
122008             }
122009             return node.getChildren();
122010         }
122011         /**
122012          * Groups sibling nodes together into their own SyntaxList if they
122013          * a) are adjacent, AND b) match a predicate function.
122014          */
122015         function groupChildren(children, groupOn) {
122016             var result = [];
122017             var group;
122018             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
122019                 var child = children_1[_i];
122020                 if (groupOn(child)) {
122021                     group = group || [];
122022                     group.push(child);
122023                 }
122024                 else {
122025                     if (group) {
122026                         result.push(createSyntaxList(group));
122027                         group = undefined;
122028                     }
122029                     result.push(child);
122030                 }
122031             }
122032             if (group) {
122033                 result.push(createSyntaxList(group));
122034             }
122035             return result;
122036         }
122037         /**
122038          * Splits sibling nodes into up to four partitions:
122039          * 1) everything left of the first node matched by `pivotOn`,
122040          * 2) the first node matched by `pivotOn`,
122041          * 3) everything right of the first node matched by `pivotOn`,
122042          * 4) a trailing semicolon, if `separateTrailingSemicolon` is enabled.
122043          * The left and right groups, if not empty, will each be grouped into their own containing SyntaxList.
122044          * @param children The sibling nodes to split.
122045          * @param pivotOn The predicate function to match the node to be the pivot. The first node that matches
122046          * the predicate will be used; any others that may match will be included into the right-hand group.
122047          * @param separateTrailingSemicolon If the last token is a semicolon, it will be returned as a separate
122048          * child rather than be included in the right-hand group.
122049          */
122050         function splitChildren(children, pivotOn, separateTrailingSemicolon) {
122051             if (separateTrailingSemicolon === void 0) { separateTrailingSemicolon = true; }
122052             if (children.length < 2) {
122053                 return children;
122054             }
122055             var splitTokenIndex = ts.findIndex(children, pivotOn);
122056             if (splitTokenIndex === -1) {
122057                 return children;
122058             }
122059             var leftChildren = children.slice(0, splitTokenIndex);
122060             var splitToken = children[splitTokenIndex];
122061             var lastToken = ts.last(children);
122062             var separateLastToken = separateTrailingSemicolon && lastToken.kind === 26 /* SemicolonToken */;
122063             var rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : undefined);
122064             var result = ts.compact([
122065                 leftChildren.length ? createSyntaxList(leftChildren) : undefined,
122066                 splitToken,
122067                 rightChildren.length ? createSyntaxList(rightChildren) : undefined,
122068             ]);
122069             return separateLastToken ? result.concat(lastToken) : result;
122070         }
122071         function createSyntaxList(children) {
122072             ts.Debug.assertGreaterThanOrEqual(children.length, 1);
122073             var syntaxList = ts.createNode(324 /* SyntaxList */, children[0].pos, ts.last(children).end);
122074             syntaxList._children = children;
122075             return syntaxList;
122076         }
122077         function isListOpener(token) {
122078             var kind = token && token.kind;
122079             return kind === 18 /* OpenBraceToken */
122080                 || kind === 22 /* OpenBracketToken */
122081                 || kind === 20 /* OpenParenToken */
122082                 || kind === 268 /* JsxOpeningElement */;
122083         }
122084         function isListCloser(token) {
122085             var kind = token && token.kind;
122086             return kind === 19 /* CloseBraceToken */
122087                 || kind === 23 /* CloseBracketToken */
122088                 || kind === 21 /* CloseParenToken */
122089                 || kind === 269 /* JsxClosingElement */;
122090         }
122091     })(SmartSelectionRange = ts.SmartSelectionRange || (ts.SmartSelectionRange = {}));
122092 })(ts || (ts = {}));
122093 /* @internal */
122094 var ts;
122095 (function (ts) {
122096     var SignatureHelp;
122097     (function (SignatureHelp) {
122098         var InvocationKind;
122099         (function (InvocationKind) {
122100             InvocationKind[InvocationKind["Call"] = 0] = "Call";
122101             InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs";
122102             InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual";
122103         })(InvocationKind || (InvocationKind = {}));
122104         function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
122105             var typeChecker = program.getTypeChecker();
122106             // Decide whether to show signature help
122107             var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position);
122108             if (!startingToken) {
122109                 // We are at the beginning of the file
122110                 return undefined;
122111             }
122112             // Only need to be careful if the user typed a character and signature help wasn't showing.
122113             var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped";
122114             // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it.
122115             if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) {
122116                 return undefined;
122117             }
122118             var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked";
122119             var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked);
122120             if (!argumentInfo)
122121                 return undefined;
122122             cancellationToken.throwIfCancellationRequested();
122123             // Extra syntactic and semantic filtering of signature help
122124             var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners);
122125             cancellationToken.throwIfCancellationRequested();
122126             if (!candidateInfo) {
122127                 // We didn't have any sig help items produced by the TS compiler.  If this is a JS
122128                 // file, then see if we can figure out anything better.
122129                 return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined;
122130             }
122131             return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
122132                 return candidateInfo.kind === 0 /* Candidate */
122133                     ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker)
122134                     : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker);
122135             });
122136         }
122137         SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
122138         var CandidateOrTypeKind;
122139         (function (CandidateOrTypeKind) {
122140             CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate";
122141             CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type";
122142         })(CandidateOrTypeKind || (CandidateOrTypeKind = {}));
122143         function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) {
122144             var invocation = _a.invocation, argumentCount = _a.argumentCount;
122145             switch (invocation.kind) {
122146                 case 0 /* Call */: {
122147                     if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) {
122148                         return undefined;
122149                     }
122150                     var candidates = [];
122151                     var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217
122152                     return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature };
122153                 }
122154                 case 1 /* TypeArgs */: {
122155                     var called = invocation.called;
122156                     if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) {
122157                         return undefined;
122158                     }
122159                     var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker);
122160                     if (candidates.length !== 0)
122161                         return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) };
122162                     var symbol = checker.getSymbolAtLocation(called);
122163                     return symbol && { kind: 1 /* Type */, symbol: symbol };
122164                 }
122165                 case 2 /* Contextual */:
122166                     return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature };
122167                 default:
122168                     return ts.Debug.assertNever(invocation);
122169             }
122170         }
122171         function isSyntacticOwner(startingToken, node, sourceFile) {
122172             if (!ts.isCallOrNewExpression(node))
122173                 return false;
122174             var invocationChildren = node.getChildren(sourceFile);
122175             switch (startingToken.kind) {
122176                 case 20 /* OpenParenToken */:
122177                     return ts.contains(invocationChildren, startingToken);
122178                 case 27 /* CommaToken */: {
122179                     var containingList = ts.findContainingList(startingToken);
122180                     return !!containingList && ts.contains(invocationChildren, containingList);
122181                 }
122182                 case 29 /* LessThanToken */:
122183                     return containsPrecedingToken(startingToken, sourceFile, node.expression);
122184                 default:
122185                     return false;
122186             }
122187         }
122188         function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) {
122189             if (argumentInfo.invocation.kind === 2 /* Contextual */)
122190                 return undefined;
122191             // See if we can find some symbol with the call expression name that has call signatures.
122192             var expression = getExpressionFromInvocation(argumentInfo.invocation);
122193             var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined;
122194             var typeChecker = program.getTypeChecker();
122195             return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) {
122196                 return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) {
122197                     var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration);
122198                     var callSignatures = type && type.getCallSignatures();
122199                     if (callSignatures && callSignatures.length) {
122200                         return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); });
122201                     }
122202                 });
122203             });
122204         }
122205         function containsPrecedingToken(startingToken, sourceFile, container) {
122206             var pos = startingToken.getFullStart();
122207             // There’s a possibility that `startingToken.parent` contains only `startingToken` and
122208             // missing nodes, none of which are valid to be returned by `findPrecedingToken`. In that
122209             // case, the preceding token we want is actually higher up the tree—almost definitely the
122210             // next parent, but theoretically the situation with missing nodes might be happening on
122211             // multiple nested levels.
122212             var currentParent = startingToken.parent;
122213             while (currentParent) {
122214                 var precedingToken = ts.findPrecedingToken(pos, sourceFile, currentParent, /*excludeJsdoc*/ true);
122215                 if (precedingToken) {
122216                     return ts.rangeContainsRange(container, precedingToken);
122217                 }
122218                 currentParent = currentParent.parent;
122219             }
122220             return ts.Debug.fail("Could not find preceding token");
122221         }
122222         function getArgumentInfoForCompletions(node, position, sourceFile) {
122223             var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile);
122224             return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined
122225                 : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex };
122226         }
122227         SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions;
122228         function getArgumentOrParameterListInfo(node, sourceFile) {
122229             var info = getArgumentOrParameterListAndIndex(node, sourceFile);
122230             if (!info)
122231                 return undefined;
122232             var list = info.list, argumentIndex = info.argumentIndex;
122233             var argumentCount = getArgumentCount(list);
122234             if (argumentIndex !== 0) {
122235                 ts.Debug.assertLessThan(argumentIndex, argumentCount);
122236             }
122237             var argumentsSpan = getApplicableSpanForArguments(list, sourceFile);
122238             return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
122239         }
122240         function getArgumentOrParameterListAndIndex(node, sourceFile) {
122241             if (node.kind === 29 /* LessThanToken */ || node.kind === 20 /* OpenParenToken */) {
122242                 // Find the list that starts right *after* the < or ( token.
122243                 // If the user has just opened a list, consider this item 0.
122244                 return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 };
122245             }
122246             else {
122247                 // findListItemInfo can return undefined if we are not in parent's argument list
122248                 // or type argument list. This includes cases where the cursor is:
122249                 //   - To the right of the closing parenthesis, non-substitution template, or template tail.
122250                 //   - Between the type arguments and the arguments (greater than token)
122251                 //   - On the target of the call (parent.func)
122252                 //   - On the 'new' keyword in a 'new' expression
122253                 var list = ts.findContainingList(node);
122254                 return list && { list: list, argumentIndex: getArgumentIndex(list, node) };
122255             }
122256         }
122257         /**
122258          * Returns relevant information for the argument list and the current argument if we are
122259          * in the argument of an invocation; returns undefined otherwise.
122260          */
122261         function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
122262             var parent = node.parent;
122263             if (ts.isCallOrNewExpression(parent)) {
122264                 var invocation = parent;
122265                 // There are 3 cases to handle:
122266                 //   1. The token introduces a list, and should begin a signature help session
122267                 //   2. The token is either not associated with a list, or ends a list, so the session should end
122268                 //   3. The token is buried inside a list, and should give signature help
122269                 //
122270                 // The following are examples of each:
122271                 //
122272                 //    Case 1:
122273                 //          foo<#T, U>(#a, b)    -> The token introduces a list, and should begin a signature help session
122274                 //    Case 2:
122275                 //          fo#o<T, U>#(a, b)#   -> The token is either not associated with a list, or ends a list, so the session should end
122276                 //    Case 3:
122277                 //          foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give signature help
122278                 // Find out if 'node' is an argument, a type argument, or neither
122279                 var info = getArgumentOrParameterListInfo(node, sourceFile);
122280                 if (!info)
122281                     return undefined;
122282                 var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
122283                 var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos;
122284                 return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
122285             }
122286             else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) {
122287                 // Check if we're actually inside the template;
122288                 // otherwise we'll fall out and return undefined.
122289                 if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
122290                     return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile);
122291                 }
122292                 return undefined;
122293             }
122294             else if (ts.isTemplateHead(node) && parent.parent.kind === 198 /* TaggedTemplateExpression */) {
122295                 var templateExpression = parent;
122296                 var tagExpression = templateExpression.parent;
122297                 ts.Debug.assert(templateExpression.kind === 211 /* TemplateExpression */);
122298                 var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
122299                 return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
122300             }
122301             else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) {
122302                 var templateSpan = parent;
122303                 var tagExpression = parent.parent.parent;
122304                 // If we're just after a template tail, don't show signature help.
122305                 if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) {
122306                     return undefined;
122307                 }
122308                 var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan);
122309                 var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile);
122310                 return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
122311             }
122312             else if (ts.isJsxOpeningLikeElement(parent)) {
122313                 // Provide a signature help for JSX opening element or JSX self-closing element.
122314                 // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems")
122315                 // i.e
122316                 //      export function MainButton(props: ButtonProps, context: any): JSX.Element { ... }
122317                 //      <MainButton /*signatureHelp*/
122318                 var attributeSpanStart = parent.attributes.pos;
122319                 var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false);
122320                 return {
122321                     isTypeParameterList: false,
122322                     invocation: { kind: 0 /* Call */, node: parent },
122323                     argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
122324                     argumentIndex: 0,
122325                     argumentCount: 1
122326                 };
122327             }
122328             else {
122329                 var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile);
122330                 if (typeArgInfo) {
122331                     var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments;
122332                     var invocation = { kind: 1 /* TypeArgs */, called: called };
122333                     var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end);
122334                     return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 };
122335                 }
122336                 return undefined;
122337             }
122338         }
122339         function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) {
122340             return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile);
122341         }
122342         function getHighestBinary(b) {
122343             return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b;
122344         }
122345         function countBinaryExpressionParameters(b) {
122346             return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2;
122347         }
122348         function tryGetParameterInfo(startingToken, _position, sourceFile, checker) {
122349             var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker);
122350             if (!info)
122351                 return undefined;
122352             var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
122353             var signatures = contextualType.getCallSignatures();
122354             if (signatures.length !== 1)
122355                 return undefined;
122356             var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) };
122357             return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount };
122358         }
122359         function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) {
122360             if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */)
122361                 return undefined;
122362             var parent = startingToken.parent;
122363             switch (parent.kind) {
122364                 case 200 /* ParenthesizedExpression */:
122365                 case 161 /* MethodDeclaration */:
122366                 case 201 /* FunctionExpression */:
122367                 case 202 /* ArrowFunction */:
122368                     var info = getArgumentOrParameterListInfo(startingToken, sourceFile);
122369                     if (!info)
122370                         return undefined;
122371                     var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan;
122372                     var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent);
122373                     return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan };
122374                 case 209 /* BinaryExpression */: {
122375                     var highestBinary = getHighestBinary(parent);
122376                     var contextualType_1 = checker.getContextualType(highestBinary);
122377                     var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1;
122378                     var argumentCount_1 = countBinaryExpressionParameters(highestBinary);
122379                     return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) };
122380                 }
122381                 default:
122382                     return undefined;
122383             }
122384         }
122385         // 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.
122386         function chooseBetterSymbol(s) {
122387             return s.name === "__type" /* Type */
122388                 ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s
122389                 : s;
122390         }
122391         function getArgumentIndex(argumentsList, node) {
122392             // The list we got back can include commas.  In the presence of errors it may
122393             // also just have nodes without commas.  For example "Foo(a b c)" will have 3
122394             // args without commas. We want to find what index we're at.  So we count
122395             // forward until we hit ourselves, only incrementing the index if it isn't a
122396             // comma.
122397             //
122398             // Note: the subtlety around trailing commas (in getArgumentCount) does not apply
122399             // here.  That's because we're only walking forward until we hit the node we're
122400             // on.  In that case, even if we're after the trailing comma, we'll still see
122401             // that trailing comma in the list, and we'll have generated the appropriate
122402             // arg index.
122403             var argumentIndex = 0;
122404             for (var _i = 0, _a = argumentsList.getChildren(); _i < _a.length; _i++) {
122405                 var child = _a[_i];
122406                 if (child === node) {
122407                     break;
122408                 }
122409                 if (child.kind !== 27 /* CommaToken */) {
122410                     argumentIndex++;
122411                 }
122412             }
122413             return argumentIndex;
122414         }
122415         function getArgumentCount(argumentsList) {
122416             // The argument count for a list is normally the number of non-comma children it has.
122417             // For example, if you have "Foo(a,b)" then there will be three children of the arg
122418             // list 'a' '<comma>' 'b'.  So, in this case the arg count will be 2.  However, there
122419             // is a small subtlety.  If you have "Foo(a,)", then the child list will just have
122420             // 'a' '<comma>'.  So, in the case where the last child is a comma, we increase the
122421             // arg count by one to compensate.
122422             //
122423             // Note: this subtlety only applies to the last comma.  If you had "Foo(a,," then
122424             // we'll have: 'a' '<comma>' '<missing>'
122425             // That will give us 2 non-commas.  We then add one for the last comma, giving us an
122426             // arg count of 3.
122427             var listChildren = argumentsList.getChildren();
122428             var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; });
122429             if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) {
122430                 argumentCount++;
122431             }
122432             return argumentCount;
122433         }
122434         // spanIndex is either the index for a given template span.
122435         // This does not give appropriate results for a NoSubstitutionTemplateLiteral
122436         function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) {
122437             // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1.
122438             // There are three cases we can encounter:
122439             //      1. We are precisely in the template literal (argIndex = 0).
122440             //      2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1).
122441             //      3. We are directly to the right of the template literal, but because we look for the token on the left,
122442             //          not enough to put us in the substitution expression; we should consider ourselves part of
122443             //          the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1).
122444             //
122445             /* eslint-disable no-double-space */
122446             // Example: f  `# abcd $#{#  1 + 1#  }# efghi ${ #"#hello"#  }  #  `
122447             //              ^       ^ ^       ^   ^          ^ ^      ^     ^
122448             // Case:        1       1 3       2   1          3 2      2     1
122449             /* eslint-enable no-double-space */
122450             ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node.");
122451             if (ts.isTemplateLiteralToken(node)) {
122452                 if (ts.isInsideTemplateLiteral(node, position, sourceFile)) {
122453                     return 0;
122454                 }
122455                 return spanIndex + 2;
122456             }
122457             return spanIndex + 1;
122458         }
122459         function getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) {
122460             // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument.
122461             var argumentCount = ts.isNoSubstitutionTemplateLiteral(tagExpression.template) ? 1 : tagExpression.template.templateSpans.length + 1;
122462             if (argumentIndex !== 0) {
122463                 ts.Debug.assertLessThan(argumentIndex, argumentCount);
122464             }
122465             return {
122466                 isTypeParameterList: false,
122467                 invocation: { kind: 0 /* Call */, node: tagExpression },
122468                 argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile),
122469                 argumentIndex: argumentIndex,
122470                 argumentCount: argumentCount
122471             };
122472         }
122473         function getApplicableSpanForArguments(argumentsList, sourceFile) {
122474             // We use full start and skip trivia on the end because we want to include trivia on
122475             // both sides. For example,
122476             //
122477             //    foo(   /*comment */     a, b, c      /*comment*/     )
122478             //        |                                               |
122479             //
122480             // The applicable span is from the first bar to the second bar (inclusive,
122481             // but not including parentheses)
122482             var applicableSpanStart = argumentsList.getFullStart();
122483             var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
122484             return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
122485         }
122486         function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) {
122487             var template = taggedTemplate.template;
122488             var applicableSpanStart = template.getStart();
122489             var applicableSpanEnd = template.getEnd();
122490             // We need to adjust the end position for the case where the template does not have a tail.
122491             // Otherwise, we will not show signature help past the expression.
122492             // For example,
122493             //
122494             //      ` ${ 1 + 1 foo(10)
122495             //       |       |
122496             // This is because a Missing node has no width. However, what we actually want is to include trivia
122497             // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
122498             if (template.kind === 211 /* TemplateExpression */) {
122499                 var lastSpan = ts.last(template.templateSpans);
122500                 if (lastSpan.literal.getFullWidth() === 0) {
122501                     applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
122502                 }
122503             }
122504             return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
122505         }
122506         function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
122507             var _loop_7 = function (n) {
122508                 // If the node is not a subspan of its parent, this is a big problem.
122509                 // There have been crashes that might be caused by this violation.
122510                 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); });
122511                 var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker);
122512                 if (argumentInfo) {
122513                     return { value: argumentInfo };
122514                 }
122515             };
122516             for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
122517                 var state_2 = _loop_7(n);
122518                 if (typeof state_2 === "object")
122519                     return state_2.value;
122520             }
122521             return undefined;
122522         }
122523         function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) {
122524             var children = parent.getChildren(sourceFile);
122525             var indexOfOpenerToken = children.indexOf(openerToken);
122526             ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
122527             return children[indexOfOpenerToken + 1];
122528         }
122529         function getExpressionFromInvocation(invocation) {
122530             return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called;
122531         }
122532         function getEnclosingDeclarationFromInvocation(invocation) {
122533             return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node;
122534         }
122535         var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
122536         function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) {
122537             var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
122538             var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation);
122539             var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation));
122540             var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray;
122541             var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); });
122542             if (argumentIndex !== 0) {
122543                 ts.Debug.assertLessThan(argumentIndex, argumentCount);
122544             }
122545             var selectedItemIndex = candidates.indexOf(resolvedSignature);
122546             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.
122547             return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount };
122548         }
122549         function createTypeHelpItems(symbol, _a, sourceFile, checker) {
122550             var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex;
122551             var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
122552             if (!typeParameters)
122553                 return undefined;
122554             var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)];
122555             return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount };
122556         }
122557         function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) {
122558             var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol);
122559             var printer = ts.createPrinter({ removeComments: true });
122560             var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
122561             var documentation = symbol.getDocumentationComment(checker);
122562             var tags = symbol.getJsDocTags();
122563             var prefixDisplayParts = __spreadArrays(typeSymbolDisplay, [ts.punctuationPart(29 /* LessThanToken */)]);
122564             return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
122565         }
122566         var separatorDisplayParts = [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()];
122567         function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) {
122568             var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix;
122569             var prefixDisplayParts = __spreadArrays(callTargetDisplayParts, prefix);
122570             var suffixDisplayParts = __spreadArrays(suffix, returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker));
122571             var documentation = candidateSignature.getDocumentationComment(checker);
122572             var tags = candidateSignature.getJsDocTags();
122573             return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags };
122574         }
122575         function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) {
122576             return ts.mapToDisplayParts(function (writer) {
122577                 writer.writePunctuation(":");
122578                 writer.writeSpace(" ");
122579                 var predicate = checker.getTypePredicateOfSignature(candidateSignature);
122580                 if (predicate) {
122581                     checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer);
122582                 }
122583                 else {
122584                     checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer);
122585                 }
122586             });
122587         }
122588         function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
122589             var typeParameters = (candidateSignature.target || candidateSignature).typeParameters;
122590             var printer = ts.createPrinter({ removeComments: true });
122591             var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); });
122592             var parameterParts = ts.mapToDisplayParts(function (writer) {
122593                 var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : [];
122594                 var params = ts.createNodeArray(__spreadArrays(thisParameter, checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
122595                 printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
122596             });
122597             return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(29 /* LessThanToken */)], suffix: __spreadArrays([ts.punctuationPart(31 /* GreaterThanToken */)], parameterParts) };
122598         }
122599         function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
122600             var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
122601             var printer = ts.createPrinter({ removeComments: true });
122602             var typeParameterParts = ts.mapToDisplayParts(function (writer) {
122603                 if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
122604                     var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); }));
122605                     printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
122606                 }
122607             });
122608             var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
122609             return { isVariadic: isVariadic, parameters: parameters, prefix: __spreadArrays(typeParameterParts, [ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
122610         }
122611         function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
122612             var displayParts = ts.mapToDisplayParts(function (writer) {
122613                 var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
122614                 printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
122615             });
122616             var isOptional = checker.isOptionalParameter(parameter.valueDeclaration);
122617             return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional };
122618         }
122619         function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) {
122620             var displayParts = ts.mapToDisplayParts(function (writer) {
122621                 var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags);
122622                 printer.writeNode(4 /* Unspecified */, param, sourceFile, writer);
122623             });
122624             return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false };
122625         }
122626     })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {}));
122627 })(ts || (ts = {}));
122628 /* @internal */
122629 var ts;
122630 (function (ts) {
122631     var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
122632     function getSourceMapper(host) {
122633         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
122634         var currentDirectory = host.getCurrentDirectory();
122635         var sourceFileLike = ts.createMap();
122636         var documentPositionMappers = ts.createMap();
122637         return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache };
122638         function toPath(fileName) {
122639             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
122640         }
122641         function getDocumentPositionMapper(generatedFileName, sourceFileName) {
122642             var path = toPath(generatedFileName);
122643             var value = documentPositionMappers.get(path);
122644             if (value)
122645                 return value;
122646             var mapper;
122647             if (host.getDocumentPositionMapper) {
122648                 mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName);
122649             }
122650             else if (host.readFile) {
122651                 var file = getSourceFileLike(generatedFileName);
122652                 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; });
122653             }
122654             documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer);
122655             return mapper || ts.identitySourceMapConsumer;
122656         }
122657         function tryGetSourcePosition(info) {
122658             if (!ts.isDeclarationFileName(info.fileName))
122659                 return undefined;
122660             var file = getSourceFile(info.fileName);
122661             if (!file)
122662                 return undefined;
122663             var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info);
122664             return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc;
122665         }
122666         function tryGetGeneratedPosition(info) {
122667             if (ts.isDeclarationFileName(info.fileName))
122668                 return undefined;
122669             var sourceFile = getSourceFile(info.fileName);
122670             if (!sourceFile)
122671                 return undefined;
122672             var program = host.getProgram();
122673             // If this is source file of project reference source (instead of redirect) there is no generated position
122674             if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) {
122675                 return undefined;
122676             }
122677             var options = program.getCompilerOptions();
122678             var outPath = options.outFile || options.out;
122679             var declarationPath = outPath ?
122680                 ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ :
122681                 ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName);
122682             if (declarationPath === undefined)
122683                 return undefined;
122684             var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info);
122685             return newLoc === info ? undefined : newLoc;
122686         }
122687         function getSourceFile(fileName) {
122688             var program = host.getProgram();
122689             if (!program)
122690                 return undefined;
122691             var path = toPath(fileName);
122692             // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file
122693             var file = program.getSourceFileByPath(path);
122694             return file && file.resolvedPath === path ? file : undefined;
122695         }
122696         function getOrCreateSourceFileLike(fileName) {
122697             var path = toPath(fileName);
122698             var fileFromCache = sourceFileLike.get(path);
122699             if (fileFromCache !== undefined)
122700                 return fileFromCache ? fileFromCache : undefined;
122701             if (!host.readFile || host.fileExists && !host.fileExists(path)) {
122702                 sourceFileLike.set(path, false);
122703                 return undefined;
122704             }
122705             // And failing that, check the disk
122706             var text = host.readFile(path);
122707             var file = text ? createSourceFileLike(text) : false;
122708             sourceFileLike.set(path, file);
122709             return file ? file : undefined;
122710         }
122711         // This can be called from source mapper in either source program or program that includes generated file
122712         function getSourceFileLike(fileName) {
122713             return !host.getSourceFileLike ?
122714                 getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) :
122715                 host.getSourceFileLike(fileName);
122716         }
122717         function toLineColumnOffset(fileName, position) {
122718             var file = getSourceFileLike(fileName); // TODO: GH#18217
122719             return file.getLineAndCharacterOfPosition(position);
122720         }
122721         function clearCache() {
122722             sourceFileLike.clear();
122723             documentPositionMappers.clear();
122724         }
122725     }
122726     ts.getSourceMapper = getSourceMapper;
122727     function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) {
122728         var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo);
122729         if (mapFileName) {
122730             var match = base64UrlRegExp.exec(mapFileName);
122731             if (match) {
122732                 if (match[1]) {
122733                     var base64Object = match[1];
122734                     return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName);
122735                 }
122736                 // Not a data URL we can parse, skip it
122737                 mapFileName = undefined;
122738             }
122739         }
122740         var possibleMapLocations = [];
122741         if (mapFileName) {
122742             possibleMapLocations.push(mapFileName);
122743         }
122744         possibleMapLocations.push(generatedFileName + ".map");
122745         var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName));
122746         for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) {
122747             var location = possibleMapLocations_1[_i];
122748             var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName));
122749             var mapFileContents = readMapFile(mapFileName_1, originalMapFileName);
122750             if (ts.isString(mapFileContents)) {
122751                 return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1);
122752             }
122753             if (mapFileContents !== undefined) {
122754                 return mapFileContents || undefined;
122755             }
122756         }
122757         return undefined;
122758     }
122759     ts.getDocumentPositionMapper = getDocumentPositionMapper;
122760     function convertDocumentToSourceMapper(host, contents, mapFileName) {
122761         var map = ts.tryParseRawSourceMap(contents);
122762         if (!map || !map.sources || !map.file || !map.mappings) {
122763             // obviously invalid map
122764             return undefined;
122765         }
122766         // Dont support sourcemaps that contain inlined sources
122767         if (map.sourcesContent && map.sourcesContent.some(ts.isString))
122768             return undefined;
122769         return ts.createDocumentPositionMapper(host, map, mapFileName);
122770     }
122771     function createSourceFileLike(text, lineMap) {
122772         return {
122773             text: text,
122774             lineMap: lineMap,
122775             getLineAndCharacterOfPosition: function (pos) {
122776                 return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos);
122777             }
122778         };
122779     }
122780 })(ts || (ts = {}));
122781 /* @internal */
122782 var ts;
122783 (function (ts) {
122784     var visitedNestedConvertibleFunctions = ts.createMap();
122785     function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
122786         program.getSemanticDiagnostics(sourceFile, cancellationToken);
122787         var diags = [];
122788         var checker = program.getTypeChecker();
122789         if (sourceFile.commonJsModuleIndicator &&
122790             (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
122791             containsTopLevelCommonjs(sourceFile)) {
122792             diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
122793         }
122794         var isJsFile = ts.isSourceFileJS(sourceFile);
122795         visitedNestedConvertibleFunctions.clear();
122796         check(sourceFile);
122797         if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) {
122798             for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
122799                 var moduleSpecifier = _a[_i];
122800                 var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
122801                 var name = importNameForConvertToDefaultImport(importNode);
122802                 if (!name)
122803                     continue;
122804                 var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
122805                 var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName);
122806                 if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
122807                     diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
122808                 }
122809             }
122810         }
122811         ts.addRange(diags, sourceFile.bindSuggestionDiagnostics);
122812         ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
122813         return diags.sort(function (d1, d2) { return d1.start - d2.start; });
122814         function check(node) {
122815             if (isJsFile) {
122816                 if (canBeConvertedToClass(node)) {
122817                     diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
122818                 }
122819             }
122820             else {
122821                 if (ts.isVariableStatement(node) &&
122822                     node.parent === sourceFile &&
122823                     node.declarationList.flags & 2 /* Const */ &&
122824                     node.declarationList.declarations.length === 1) {
122825                     var init = node.declarationList.declarations[0].initializer;
122826                     if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) {
122827                         diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import));
122828                     }
122829                 }
122830                 if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) {
122831                     diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types));
122832                 }
122833             }
122834             if (ts.isFunctionLikeDeclaration(node)) {
122835                 addConvertToAsyncFunctionDiagnostics(node, checker, diags);
122836             }
122837             node.forEachChild(check);
122838         }
122839     }
122840     ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
122841     // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
122842     function containsTopLevelCommonjs(sourceFile) {
122843         return sourceFile.statements.some(function (statement) {
122844             switch (statement.kind) {
122845                 case 225 /* VariableStatement */:
122846                     return statement.declarationList.declarations.some(function (decl) {
122847                         return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
122848                     });
122849                 case 226 /* ExpressionStatement */: {
122850                     var expression = statement.expression;
122851                     if (!ts.isBinaryExpression(expression))
122852                         return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
122853                     var kind = ts.getAssignmentDeclarationKind(expression);
122854                     return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
122855                 }
122856                 default:
122857                     return false;
122858             }
122859         });
122860     }
122861     function propertyAccessLeftHandSide(node) {
122862         return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
122863     }
122864     function importNameForConvertToDefaultImport(node) {
122865         switch (node.kind) {
122866             case 254 /* ImportDeclaration */:
122867                 var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
122868                 return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 256 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
122869                     ? importClause.namedBindings.name
122870                     : undefined;
122871             case 253 /* ImportEqualsDeclaration */:
122872                 return node.name;
122873             default:
122874                 return undefined;
122875         }
122876     }
122877     function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
122878         // need to check function before checking map so that deeper levels of nested callbacks are checked
122879         if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) {
122880             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));
122881         }
122882     }
122883     function isConvertibleFunction(node, checker) {
122884         return !ts.isAsyncFunction(node) &&
122885             node.body &&
122886             ts.isBlock(node.body) &&
122887             hasReturnStatementWithPromiseHandler(node.body) &&
122888             returnsPromise(node, checker);
122889     }
122890     function returnsPromise(node, checker) {
122891         var functionType = checker.getTypeAtLocation(node);
122892         var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */);
122893         var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined;
122894         return !!returnType && !!checker.getPromisedTypeOfPromise(returnType);
122895     }
122896     function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) {
122897         return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator;
122898     }
122899     function hasReturnStatementWithPromiseHandler(body) {
122900         return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler);
122901     }
122902     function isReturnStatementWithFixablePromiseHandler(node) {
122903         return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression);
122904     }
122905     ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler;
122906     // Should be kept up to date with transformExpression in convertToAsyncFunction.ts
122907     function isFixablePromiseHandler(node) {
122908         // ensure outermost call exists and is a promise handler
122909         if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
122910             return false;
122911         }
122912         // ensure all chained calls are valid
122913         var currentNode = node.expression;
122914         while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) {
122915             if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
122916                 return false;
122917             }
122918             currentNode = currentNode.expression;
122919         }
122920         return true;
122921     }
122922     ts.isFixablePromiseHandler = isFixablePromiseHandler;
122923     function isPromiseHandler(node) {
122924         return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) ||
122925             ts.hasPropertyAccessExpressionWithName(node, "catch"));
122926     }
122927     function hasSupportedNumberOfArguments(node) {
122928         if (node.arguments.length > 2)
122929             return false;
122930         if (node.arguments.length < 2)
122931             return true;
122932         return ts.some(node.arguments, function (arg) {
122933             return arg.kind === 100 /* NullKeyword */ ||
122934                 ts.isIdentifier(arg) && arg.text === "undefined";
122935         });
122936     }
122937     // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts
122938     function isFixablePromiseArgument(arg) {
122939         switch (arg.kind) {
122940             case 244 /* FunctionDeclaration */:
122941             case 201 /* FunctionExpression */:
122942             case 202 /* ArrowFunction */:
122943                 visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
122944             // falls through
122945             case 100 /* NullKeyword */:
122946             case 75 /* Identifier */: // identifier includes undefined
122947                 return true;
122948             default:
122949                 return false;
122950         }
122951     }
122952     function getKeyFromNode(exp) {
122953         return exp.pos.toString() + ":" + exp.end.toString();
122954     }
122955     function canBeConvertedToClass(node) {
122956         var _a, _b, _c, _d;
122957         if (node.kind === 201 /* FunctionExpression */) {
122958             if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) {
122959                 return true;
122960             }
122961             var decl = ts.getDeclarationOfExpando(node);
122962             var symbol = decl === null || decl === void 0 ? void 0 : decl.symbol;
122963             return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size)));
122964         }
122965         if (node.kind === 244 /* FunctionDeclaration */) {
122966             return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size);
122967         }
122968         return false;
122969     }
122970 })(ts || (ts = {}));
122971 /* @internal */
122972 var ts;
122973 (function (ts) {
122974     var SymbolDisplay;
122975     (function (SymbolDisplay) {
122976         var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */;
122977         // TODO(drosen): use contextual SemanticMeaning.
122978         function getSymbolKind(typeChecker, symbol, location) {
122979             var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
122980             if (result !== "" /* unknown */) {
122981                 return result;
122982             }
122983             var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
122984             if (flags & 32 /* Class */) {
122985                 return ts.getDeclarationOfKind(symbol, 214 /* ClassExpression */) ?
122986                     "local class" /* localClassElement */ : "class" /* classElement */;
122987             }
122988             if (flags & 384 /* Enum */)
122989                 return "enum" /* enumElement */;
122990             if (flags & 524288 /* TypeAlias */)
122991                 return "type" /* typeElement */;
122992             if (flags & 64 /* Interface */)
122993                 return "interface" /* interfaceElement */;
122994             if (flags & 262144 /* TypeParameter */)
122995                 return "type parameter" /* typeParameterElement */;
122996             if (flags & 8 /* EnumMember */)
122997                 return "enum member" /* enumMemberElement */;
122998             if (flags & 2097152 /* Alias */)
122999                 return "alias" /* alias */;
123000             if (flags & 1536 /* Module */)
123001                 return "module" /* moduleElement */;
123002             return result;
123003         }
123004         SymbolDisplay.getSymbolKind = getSymbolKind;
123005         function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
123006             var roots = typeChecker.getRootSymbols(symbol);
123007             // If this is a method from a mapped type, leave as a method so long as it still has a call signature.
123008             if (roots.length === 1
123009                 && ts.first(roots).flags & 8192 /* Method */
123010                 // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`.
123011                 && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) {
123012                 return "method" /* memberFunctionElement */;
123013             }
123014             if (typeChecker.isUndefinedSymbol(symbol)) {
123015                 return "var" /* variableElement */;
123016             }
123017             if (typeChecker.isArgumentsSymbol(symbol)) {
123018                 return "local var" /* localVariableElement */;
123019             }
123020             if (location.kind === 104 /* ThisKeyword */ && ts.isExpression(location)) {
123021                 return "parameter" /* parameterElement */;
123022             }
123023             var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
123024             if (flags & 3 /* Variable */) {
123025                 if (ts.isFirstDeclarationOfSymbolParameter(symbol)) {
123026                     return "parameter" /* parameterElement */;
123027                 }
123028                 else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) {
123029                     return "const" /* constElement */;
123030                 }
123031                 else if (ts.forEach(symbol.declarations, ts.isLet)) {
123032                     return "let" /* letElement */;
123033                 }
123034                 return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */;
123035             }
123036             if (flags & 16 /* Function */)
123037                 return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */;
123038             if (flags & 32768 /* GetAccessor */)
123039                 return "getter" /* memberGetAccessorElement */;
123040             if (flags & 65536 /* SetAccessor */)
123041                 return "setter" /* memberSetAccessorElement */;
123042             if (flags & 8192 /* Method */)
123043                 return "method" /* memberFunctionElement */;
123044             if (flags & 16384 /* Constructor */)
123045                 return "constructor" /* constructorImplementationElement */;
123046             if (flags & 4 /* Property */) {
123047                 if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) {
123048                     // If union property is result of union of non method (property/accessors/variables), it is labeled as property
123049                     var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) {
123050                         var rootSymbolFlags = rootSymbol.getFlags();
123051                         if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) {
123052                             return "property" /* memberVariableElement */;
123053                         }
123054                         // May be a Function if this was from `typeof N` with `namespace N { function f();. }`.
123055                         ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */)));
123056                     });
123057                     if (!unionPropertyKind) {
123058                         // If this was union of all methods,
123059                         // make sure it has call signatures before we can label it as method
123060                         var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
123061                         if (typeOfUnionProperty.getCallSignatures().length) {
123062                             return "method" /* memberFunctionElement */;
123063                         }
123064                         return "property" /* memberVariableElement */;
123065                     }
123066                     return unionPropertyKind;
123067                 }
123068                 // If we requested completions after `x.` at the top-level, we may be at a source file location.
123069                 switch (location.parent && location.parent.kind) {
123070                     // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'.
123071                     case 268 /* JsxOpeningElement */:
123072                     case 266 /* JsxElement */:
123073                     case 267 /* JsxSelfClosingElement */:
123074                         return location.kind === 75 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */;
123075                     case 273 /* JsxAttribute */:
123076                         return "JSX attribute" /* jsxAttribute */;
123077                     default:
123078                         return "property" /* memberVariableElement */;
123079                 }
123080             }
123081             return "" /* unknown */;
123082         }
123083         function getSymbolModifiers(symbol) {
123084             var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0
123085                 ? ts.getNodeModifiers(symbol.declarations[0])
123086                 : "" /* none */;
123087             var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ?
123088                 "optional" /* optionalModifier */
123089                 : "" /* none */;
123090             return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers;
123091         }
123092         SymbolDisplay.getSymbolModifiers = getSymbolModifiers;
123093         // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location
123094         function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) {
123095             if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); }
123096             var displayParts = [];
123097             var documentation = [];
123098             var tags = [];
123099             var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
123100             var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */;
123101             var hasAddedSymbolInfo = false;
123102             var isThisExpression = location.kind === 104 /* ThisKeyword */ && ts.isInExpressionContext(location);
123103             var type;
123104             var printer;
123105             var documentationFromAlias;
123106             var tagsFromAlias;
123107             var hasMultipleSignatures = false;
123108             if (location.kind === 104 /* ThisKeyword */ && !isThisExpression) {
123109                 return { displayParts: [ts.keywordPart(104 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined };
123110             }
123111             // Class at constructor site need to be shown as constructor apart from property,method, vars
123112             if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) {
123113                 // If it is accessor they are allowed only if location is at name of the accessor
123114                 if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) {
123115                     symbolKind = "property" /* memberVariableElement */;
123116                 }
123117                 var signature = void 0;
123118                 type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location);
123119                 if (location.parent && location.parent.kind === 194 /* PropertyAccessExpression */) {
123120                     var right = location.parent.name;
123121                     // Either the location is on the right of a property access, or on the left and the right is missing
123122                     if (right === location || (right && right.getFullWidth() === 0)) {
123123                         location = location.parent;
123124                     }
123125                 }
123126                 // try get the call/construct signature from the type if it matches
123127                 var callExpressionLike = void 0;
123128                 if (ts.isCallOrNewExpression(location)) {
123129                     callExpressionLike = location;
123130                 }
123131                 else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) {
123132                     callExpressionLike = location.parent;
123133                 }
123134                 else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) {
123135                     callExpressionLike = location.parent;
123136                 }
123137                 if (callExpressionLike) {
123138                     signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217
123139                     var useConstructSignatures = callExpressionLike.kind === 197 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 102 /* SuperKeyword */);
123140                     var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
123141                     if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
123142                         // Get the first signature if there is one -- allSignatures may contain
123143                         // either the original signature or its target, so check for either
123144                         signature = allSignatures.length ? allSignatures[0] : undefined;
123145                     }
123146                     if (signature) {
123147                         if (useConstructSignatures && (symbolFlags & 32 /* Class */)) {
123148                             // Constructor
123149                             symbolKind = "constructor" /* constructorImplementationElement */;
123150                             addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
123151                         }
123152                         else if (symbolFlags & 2097152 /* Alias */) {
123153                             symbolKind = "alias" /* alias */;
123154                             pushSymbolKind(symbolKind);
123155                             displayParts.push(ts.spacePart());
123156                             if (useConstructSignatures) {
123157                                 displayParts.push(ts.keywordPart(99 /* NewKeyword */));
123158                                 displayParts.push(ts.spacePart());
123159                             }
123160                             addFullSymbolName(symbol);
123161                         }
123162                         else {
123163                             addPrefixForAnyFunctionOrVar(symbol, symbolKind);
123164                         }
123165                         switch (symbolKind) {
123166                             case "JSX attribute" /* jsxAttribute */:
123167                             case "property" /* memberVariableElement */:
123168                             case "var" /* variableElement */:
123169                             case "const" /* constElement */:
123170                             case "let" /* letElement */:
123171                             case "parameter" /* parameterElement */:
123172                             case "local var" /* localVariableElement */:
123173                                 // If it is call or construct signature of lambda's write type name
123174                                 displayParts.push(ts.punctuationPart(58 /* ColonToken */));
123175                                 displayParts.push(ts.spacePart());
123176                                 if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) {
123177                                     ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */));
123178                                     displayParts.push(ts.lineBreakPart());
123179                                 }
123180                                 if (useConstructSignatures) {
123181                                     displayParts.push(ts.keywordPart(99 /* NewKeyword */));
123182                                     displayParts.push(ts.spacePart());
123183                                 }
123184                                 addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */);
123185                                 break;
123186                             default:
123187                                 // Just signature
123188                                 addSignatureDisplayParts(signature, allSignatures);
123189                         }
123190                         hasAddedSymbolInfo = true;
123191                         hasMultipleSignatures = allSignatures.length > 1;
123192                     }
123193                 }
123194                 else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration
123195                     (location.kind === 129 /* ConstructorKeyword */ && location.parent.kind === 162 /* Constructor */)) { // At constructor keyword of constructor declaration
123196                     // get the signature from the declaration and write it
123197                     var functionDeclaration_1 = location.parent;
123198                     // Use function declaration to write the signatures only if the symbol corresponding to this declaration
123199                     var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) {
123200                         return declaration === (location.kind === 129 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1);
123201                     });
123202                     if (locationIsSymbolDeclaration) {
123203                         var allSignatures = functionDeclaration_1.kind === 162 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
123204                         if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) {
123205                             signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217
123206                         }
123207                         else {
123208                             signature = allSignatures[0];
123209                         }
123210                         if (functionDeclaration_1.kind === 162 /* Constructor */) {
123211                             // show (constructor) Type(...) signature
123212                             symbolKind = "constructor" /* constructorImplementationElement */;
123213                             addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
123214                         }
123215                         else {
123216                             // (function/method) symbol(..signature)
123217                             addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 165 /* CallSignature */ &&
123218                                 !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind);
123219                         }
123220                         addSignatureDisplayParts(signature, allSignatures);
123221                         hasAddedSymbolInfo = true;
123222                         hasMultipleSignatures = allSignatures.length > 1;
123223                     }
123224                 }
123225             }
123226             if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
123227                 addAliasPrefixIfNecessary();
123228                 if (ts.getDeclarationOfKind(symbol, 214 /* ClassExpression */)) {
123229                     // Special case for class expressions because we would like to indicate that
123230                     // the class name is local to the class body (similar to function expression)
123231                     //      (local class) class <className>
123232                     pushSymbolKind("local class" /* localClassElement */);
123233                 }
123234                 else {
123235                     // Class declaration has name which is not local.
123236                     displayParts.push(ts.keywordPart(80 /* ClassKeyword */));
123237                 }
123238                 displayParts.push(ts.spacePart());
123239                 addFullSymbolName(symbol);
123240                 writeTypeParametersOfSymbol(symbol, sourceFile);
123241             }
123242             if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) {
123243                 prefixNextMeaning();
123244                 displayParts.push(ts.keywordPart(114 /* InterfaceKeyword */));
123245                 displayParts.push(ts.spacePart());
123246                 addFullSymbolName(symbol);
123247                 writeTypeParametersOfSymbol(symbol, sourceFile);
123248             }
123249             if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) {
123250                 prefixNextMeaning();
123251                 displayParts.push(ts.keywordPart(145 /* TypeKeyword */));
123252                 displayParts.push(ts.spacePart());
123253                 addFullSymbolName(symbol);
123254                 writeTypeParametersOfSymbol(symbol, sourceFile);
123255                 displayParts.push(ts.spacePart());
123256                 displayParts.push(ts.operatorPart(62 /* EqualsToken */));
123257                 displayParts.push(ts.spacePart());
123258                 ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */));
123259             }
123260             if (symbolFlags & 384 /* Enum */) {
123261                 prefixNextMeaning();
123262                 if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) {
123263                     displayParts.push(ts.keywordPart(81 /* ConstKeyword */));
123264                     displayParts.push(ts.spacePart());
123265                 }
123266                 displayParts.push(ts.keywordPart(88 /* EnumKeyword */));
123267                 displayParts.push(ts.spacePart());
123268                 addFullSymbolName(symbol);
123269             }
123270             if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
123271                 prefixNextMeaning();
123272                 var declaration = ts.getDeclarationOfKind(symbol, 249 /* ModuleDeclaration */);
123273                 var isNamespace = declaration && declaration.name && declaration.name.kind === 75 /* Identifier */;
123274                 displayParts.push(ts.keywordPart(isNamespace ? 136 /* NamespaceKeyword */ : 135 /* ModuleKeyword */));
123275                 displayParts.push(ts.spacePart());
123276                 addFullSymbolName(symbol);
123277             }
123278             if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) {
123279                 prefixNextMeaning();
123280                 displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
123281                 displayParts.push(ts.textPart("type parameter"));
123282                 displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
123283                 displayParts.push(ts.spacePart());
123284                 addFullSymbolName(symbol);
123285                 if (symbol.parent) {
123286                     // Class/Interface type parameter
123287                     addInPrefix();
123288                     addFullSymbolName(symbol.parent, enclosingDeclaration);
123289                     writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
123290                 }
123291                 else {
123292                     // Method/function type parameter
123293                     var decl = ts.getDeclarationOfKind(symbol, 155 /* TypeParameter */);
123294                     if (decl === undefined)
123295                         return ts.Debug.fail();
123296                     var declaration = decl.parent;
123297                     if (declaration) {
123298                         if (ts.isFunctionLikeKind(declaration.kind)) {
123299                             addInPrefix();
123300                             var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217
123301                             if (declaration.kind === 166 /* ConstructSignature */) {
123302                                 displayParts.push(ts.keywordPart(99 /* NewKeyword */));
123303                                 displayParts.push(ts.spacePart());
123304                             }
123305                             else if (declaration.kind !== 165 /* CallSignature */ && declaration.name) {
123306                                 addFullSymbolName(declaration.symbol);
123307                             }
123308                             ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
123309                         }
123310                         else if (declaration.kind === 247 /* TypeAliasDeclaration */) {
123311                             // Type alias type parameter
123312                             // For example
123313                             //      type list<T> = T[]; // Both T will go through same code path
123314                             addInPrefix();
123315                             displayParts.push(ts.keywordPart(145 /* TypeKeyword */));
123316                             displayParts.push(ts.spacePart());
123317                             addFullSymbolName(declaration.symbol);
123318                             writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
123319                         }
123320                     }
123321                 }
123322             }
123323             if (symbolFlags & 8 /* EnumMember */) {
123324                 symbolKind = "enum member" /* enumMemberElement */;
123325                 addPrefixForAnyFunctionOrVar(symbol, "enum member");
123326                 var declaration = symbol.declarations[0];
123327                 if (declaration.kind === 284 /* EnumMember */) {
123328                     var constantValue = typeChecker.getConstantValue(declaration);
123329                     if (constantValue !== undefined) {
123330                         displayParts.push(ts.spacePart());
123331                         displayParts.push(ts.operatorPart(62 /* EqualsToken */));
123332                         displayParts.push(ts.spacePart());
123333                         displayParts.push(ts.displayPart(ts.getTextOfConstantValue(constantValue), typeof constantValue === "number" ? ts.SymbolDisplayPartKind.numericLiteral : ts.SymbolDisplayPartKind.stringLiteral));
123334                     }
123335                 }
123336             }
123337             if (symbolFlags & 2097152 /* Alias */) {
123338                 prefixNextMeaning();
123339                 if (!hasAddedSymbolInfo) {
123340                     var resolvedSymbol = typeChecker.getAliasedSymbol(symbol);
123341                     if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) {
123342                         var resolvedNode = resolvedSymbol.declarations[0];
123343                         var declarationName = ts.getNameOfDeclaration(resolvedNode);
123344                         if (declarationName) {
123345                             var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) &&
123346                                 ts.hasModifier(resolvedNode, 2 /* Ambient */);
123347                             var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration;
123348                             var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol);
123349                             displayParts.push.apply(displayParts, resolvedInfo.displayParts);
123350                             displayParts.push(ts.lineBreakPart());
123351                             documentationFromAlias = resolvedInfo.documentation;
123352                             tagsFromAlias = resolvedInfo.tags;
123353                         }
123354                     }
123355                 }
123356                 switch (symbol.declarations[0].kind) {
123357                     case 252 /* NamespaceExportDeclaration */:
123358                         displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
123359                         displayParts.push(ts.spacePart());
123360                         displayParts.push(ts.keywordPart(136 /* NamespaceKeyword */));
123361                         break;
123362                     case 259 /* ExportAssignment */:
123363                         displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
123364                         displayParts.push(ts.spacePart());
123365                         displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 84 /* DefaultKeyword */));
123366                         break;
123367                     case 263 /* ExportSpecifier */:
123368                         displayParts.push(ts.keywordPart(89 /* ExportKeyword */));
123369                         break;
123370                     default:
123371                         displayParts.push(ts.keywordPart(96 /* ImportKeyword */));
123372                 }
123373                 displayParts.push(ts.spacePart());
123374                 addFullSymbolName(symbol);
123375                 ts.forEach(symbol.declarations, function (declaration) {
123376                     if (declaration.kind === 253 /* ImportEqualsDeclaration */) {
123377                         var importEqualsDeclaration = declaration;
123378                         if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
123379                             displayParts.push(ts.spacePart());
123380                             displayParts.push(ts.operatorPart(62 /* EqualsToken */));
123381                             displayParts.push(ts.spacePart());
123382                             displayParts.push(ts.keywordPart(139 /* RequireKeyword */));
123383                             displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
123384                             displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), ts.SymbolDisplayPartKind.stringLiteral));
123385                             displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
123386                         }
123387                         else {
123388                             var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference);
123389                             if (internalAliasSymbol) {
123390                                 displayParts.push(ts.spacePart());
123391                                 displayParts.push(ts.operatorPart(62 /* EqualsToken */));
123392                                 displayParts.push(ts.spacePart());
123393                                 addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
123394                             }
123395                         }
123396                         return true;
123397                     }
123398                 });
123399             }
123400             if (!hasAddedSymbolInfo) {
123401                 if (symbolKind !== "" /* unknown */) {
123402                     if (type) {
123403                         if (isThisExpression) {
123404                             prefixNextMeaning();
123405                             displayParts.push(ts.keywordPart(104 /* ThisKeyword */));
123406                         }
123407                         else {
123408                             addPrefixForAnyFunctionOrVar(symbol, symbolKind);
123409                         }
123410                         // For properties, variables and local vars: show the type
123411                         if (symbolKind === "property" /* memberVariableElement */ ||
123412                             symbolKind === "JSX attribute" /* jsxAttribute */ ||
123413                             symbolFlags & 3 /* Variable */ ||
123414                             symbolKind === "local var" /* localVariableElement */ ||
123415                             isThisExpression) {
123416                             displayParts.push(ts.punctuationPart(58 /* ColonToken */));
123417                             displayParts.push(ts.spacePart());
123418                             // If the type is type parameter, format it specially
123419                             if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) {
123420                                 var typeParameterParts = ts.mapToDisplayParts(function (writer) {
123421                                     var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags);
123422                                     getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
123423                                 });
123424                                 ts.addRange(displayParts, typeParameterParts);
123425                             }
123426                             else {
123427                                 ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration));
123428                             }
123429                         }
123430                         else if (symbolFlags & 16 /* Function */ ||
123431                             symbolFlags & 8192 /* Method */ ||
123432                             symbolFlags & 16384 /* Constructor */ ||
123433                             symbolFlags & 131072 /* Signature */ ||
123434                             symbolFlags & 98304 /* Accessor */ ||
123435                             symbolKind === "method" /* memberFunctionElement */) {
123436                             var allSignatures = type.getNonNullableType().getCallSignatures();
123437                             if (allSignatures.length) {
123438                                 addSignatureDisplayParts(allSignatures[0], allSignatures);
123439                                 hasMultipleSignatures = allSignatures.length > 1;
123440                             }
123441                         }
123442                     }
123443                 }
123444                 else {
123445                     symbolKind = getSymbolKind(typeChecker, symbol, location);
123446                 }
123447             }
123448             if (documentation.length === 0 && !hasMultipleSignatures) {
123449                 documentation = symbol.getDocumentationComment(typeChecker);
123450             }
123451             if (documentation.length === 0 && symbolFlags & 4 /* Property */) {
123452                 // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
123453                 // there documentation comments might be attached to the right hand side symbol of their declarations.
123454                 // The pattern of such special property access is that the parent symbol is the symbol of the file.
123455                 if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 290 /* SourceFile */; })) {
123456                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
123457                         var declaration = _a[_i];
123458                         if (!declaration.parent || declaration.parent.kind !== 209 /* BinaryExpression */) {
123459                             continue;
123460                         }
123461                         var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
123462                         if (!rhsSymbol) {
123463                             continue;
123464                         }
123465                         documentation = rhsSymbol.getDocumentationComment(typeChecker);
123466                         tags = rhsSymbol.getJsDocTags();
123467                         if (documentation.length > 0) {
123468                             break;
123469                         }
123470                     }
123471                 }
123472             }
123473             if (tags.length === 0 && !hasMultipleSignatures) {
123474                 tags = symbol.getJsDocTags();
123475             }
123476             if (documentation.length === 0 && documentationFromAlias) {
123477                 documentation = documentationFromAlias;
123478             }
123479             if (tags.length === 0 && tagsFromAlias) {
123480                 tags = tagsFromAlias;
123481             }
123482             return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags };
123483             function getPrinter() {
123484                 if (!printer) {
123485                     printer = ts.createPrinter({ removeComments: true });
123486                 }
123487                 return printer;
123488             }
123489             function prefixNextMeaning() {
123490                 if (displayParts.length) {
123491                     displayParts.push(ts.lineBreakPart());
123492                 }
123493                 addAliasPrefixIfNecessary();
123494             }
123495             function addAliasPrefixIfNecessary() {
123496                 if (alias) {
123497                     pushSymbolKind("alias" /* alias */);
123498                     displayParts.push(ts.spacePart());
123499                 }
123500             }
123501             function addInPrefix() {
123502                 displayParts.push(ts.spacePart());
123503                 displayParts.push(ts.keywordPart(97 /* InKeyword */));
123504                 displayParts.push(ts.spacePart());
123505             }
123506             function addFullSymbolName(symbolToDisplay, enclosingDeclaration) {
123507                 if (alias && symbolToDisplay === symbol) {
123508                     symbolToDisplay = alias;
123509                 }
123510                 var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */);
123511                 ts.addRange(displayParts, fullSymbolDisplayParts);
123512                 if (symbol.flags & 16777216 /* Optional */) {
123513                     displayParts.push(ts.punctuationPart(57 /* QuestionToken */));
123514                 }
123515             }
123516             function addPrefixForAnyFunctionOrVar(symbol, symbolKind) {
123517                 prefixNextMeaning();
123518                 if (symbolKind) {
123519                     pushSymbolKind(symbolKind);
123520                     if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) {
123521                         displayParts.push(ts.spacePart());
123522                         addFullSymbolName(symbol);
123523                     }
123524                 }
123525             }
123526             function pushSymbolKind(symbolKind) {
123527                 switch (symbolKind) {
123528                     case "var" /* variableElement */:
123529                     case "function" /* functionElement */:
123530                     case "let" /* letElement */:
123531                     case "const" /* constElement */:
123532                     case "constructor" /* constructorImplementationElement */:
123533                         displayParts.push(ts.textOrKeywordPart(symbolKind));
123534                         return;
123535                     default:
123536                         displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
123537                         displayParts.push(ts.textOrKeywordPart(symbolKind));
123538                         displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
123539                         return;
123540                 }
123541             }
123542             function addSignatureDisplayParts(signature, allSignatures, flags) {
123543                 if (flags === void 0) { flags = 0 /* None */; }
123544                 ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */));
123545                 if (allSignatures.length > 1) {
123546                     displayParts.push(ts.spacePart());
123547                     displayParts.push(ts.punctuationPart(20 /* OpenParenToken */));
123548                     displayParts.push(ts.operatorPart(39 /* PlusToken */));
123549                     displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), ts.SymbolDisplayPartKind.numericLiteral));
123550                     displayParts.push(ts.spacePart());
123551                     displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads"));
123552                     displayParts.push(ts.punctuationPart(21 /* CloseParenToken */));
123553                 }
123554                 documentation = signature.getDocumentationComment(typeChecker);
123555                 tags = signature.getJsDocTags();
123556                 if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) {
123557                     documentation = allSignatures[0].getDocumentationComment(typeChecker);
123558                     tags = allSignatures[0].getJsDocTags();
123559                 }
123560             }
123561             function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) {
123562                 var typeParameterParts = ts.mapToDisplayParts(function (writer) {
123563                     var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags);
123564                     getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer);
123565                 });
123566                 ts.addRange(displayParts, typeParameterParts);
123567             }
123568         }
123569         SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind;
123570         function isLocalVariableOrFunction(symbol) {
123571             if (symbol.parent) {
123572                 return false; // This is exported symbol
123573             }
123574             return ts.forEach(symbol.declarations, function (declaration) {
123575                 // Function expressions are local
123576                 if (declaration.kind === 201 /* FunctionExpression */) {
123577                     return true;
123578                 }
123579                 if (declaration.kind !== 242 /* VariableDeclaration */ && declaration.kind !== 244 /* FunctionDeclaration */) {
123580                     return false;
123581                 }
123582                 // If the parent is not sourceFile or module block it is local variable
123583                 for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
123584                     // Reached source file or module block
123585                     if (parent.kind === 290 /* SourceFile */ || parent.kind === 250 /* ModuleBlock */) {
123586                         return false;
123587                     }
123588                 }
123589                 // parent is in function block
123590                 return true;
123591             });
123592         }
123593     })(SymbolDisplay = ts.SymbolDisplay || (ts.SymbolDisplay = {}));
123594 })(ts || (ts = {}));
123595 var ts;
123596 (function (ts) {
123597     /*
123598      * This function will compile source text from 'input' argument using specified compiler options.
123599      * If not options are provided - it will use a set of default compiler options.
123600      * Extra compiler options that will unconditionally be used by this function are:
123601      * - isolatedModules = true
123602      * - allowNonTsExtensions = true
123603      * - noLib = true
123604      * - noResolve = true
123605      */
123606     function transpileModule(input, transpileOptions) {
123607         var diagnostics = [];
123608         var options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : {};
123609         // mix in default options
123610         var defaultOptions = ts.getDefaultCompilerOptions();
123611         for (var key in defaultOptions) {
123612             if (ts.hasProperty(defaultOptions, key) && options[key] === undefined) {
123613                 options[key] = defaultOptions[key];
123614             }
123615         }
123616         for (var _i = 0, transpileOptionValueCompilerOptions_1 = ts.transpileOptionValueCompilerOptions; _i < transpileOptionValueCompilerOptions_1.length; _i++) {
123617             var option = transpileOptionValueCompilerOptions_1[_i];
123618             options[option.name] = option.transpileOptionValue;
123619         }
123620         // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
123621         options.suppressOutputPathCheck = true;
123622         // Filename can be non-ts file.
123623         options.allowNonTsExtensions = true;
123624         // if jsx is specified then treat file as .tsx
123625         var inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts");
123626         var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217
123627         if (transpileOptions.moduleName) {
123628             sourceFile.moduleName = transpileOptions.moduleName;
123629         }
123630         if (transpileOptions.renamedDependencies) {
123631             sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies);
123632         }
123633         var newLine = ts.getNewLineCharacter(options);
123634         // Output
123635         var outputText;
123636         var sourceMapText;
123637         // Create a compilerHost object to allow the compiler to read and write files
123638         var compilerHost = {
123639             getSourceFile: function (fileName) { return fileName === ts.normalizePath(inputFileName) ? sourceFile : undefined; },
123640             writeFile: function (name, text) {
123641                 if (ts.fileExtensionIs(name, ".map")) {
123642                     ts.Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name);
123643                     sourceMapText = text;
123644                 }
123645                 else {
123646                     ts.Debug.assertEqual(outputText, undefined, "Unexpected multiple outputs, file:", name);
123647                     outputText = text;
123648                 }
123649             },
123650             getDefaultLibFileName: function () { return "lib.d.ts"; },
123651             useCaseSensitiveFileNames: function () { return false; },
123652             getCanonicalFileName: function (fileName) { return fileName; },
123653             getCurrentDirectory: function () { return ""; },
123654             getNewLine: function () { return newLine; },
123655             fileExists: function (fileName) { return fileName === inputFileName; },
123656             readFile: function () { return ""; },
123657             directoryExists: function () { return true; },
123658             getDirectories: function () { return []; }
123659         };
123660         var program = ts.createProgram([inputFileName], options, compilerHost);
123661         if (transpileOptions.reportDiagnostics) {
123662             ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
123663             ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
123664         }
123665         // Emit
123666         program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers);
123667         if (outputText === undefined)
123668             return ts.Debug.fail("Output generation failed");
123669         return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText };
123670     }
123671     ts.transpileModule = transpileModule;
123672     /*
123673      * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result.
123674      */
123675     function transpile(input, compilerOptions, fileName, diagnostics, moduleName) {
123676         var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName });
123677         // addRange correctly handles cases when wither 'from' or 'to' argument is missing
123678         ts.addRange(diagnostics, output.diagnostics);
123679         return output.outputText;
123680     }
123681     ts.transpile = transpile;
123682     var commandLineOptionsStringToEnum;
123683     /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */
123684     /*@internal*/
123685     function fixupCompilerOptions(options, diagnostics) {
123686         // Lazily create this value to fix module loading errors.
123687         commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) {
123688             return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
123689         });
123690         options = ts.cloneCompilerOptions(options);
123691         var _loop_8 = function (opt) {
123692             if (!ts.hasProperty(options, opt.name)) {
123693                 return "continue";
123694             }
123695             var value = options[opt.name];
123696             // Value should be a key of opt.type
123697             if (ts.isString(value)) {
123698                 // If value is not a string, this will fail
123699                 options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics);
123700             }
123701             else {
123702                 if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) {
123703                     // Supplied value isn't a valid enum value.
123704                     diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt));
123705                 }
123706             }
123707         };
123708         for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
123709             var opt = commandLineOptionsStringToEnum_1[_i];
123710             _loop_8(opt);
123711         }
123712         return options;
123713     }
123714     ts.fixupCompilerOptions = fixupCompilerOptions;
123715 })(ts || (ts = {}));
123716 /* @internal */
123717 var ts;
123718 (function (ts) {
123719     var formatting;
123720     (function (formatting) {
123721         var FormattingRequestKind;
123722         (function (FormattingRequestKind) {
123723             FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument";
123724             FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection";
123725             FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter";
123726             FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon";
123727             FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace";
123728             FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace";
123729         })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {}));
123730         var FormattingContext = /** @class */ (function () {
123731             function FormattingContext(sourceFile, formattingRequestKind, options) {
123732                 this.sourceFile = sourceFile;
123733                 this.formattingRequestKind = formattingRequestKind;
123734                 this.options = options;
123735             }
123736             FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) {
123737                 this.currentTokenSpan = ts.Debug.checkDefined(currentRange);
123738                 this.currentTokenParent = ts.Debug.checkDefined(currentTokenParent);
123739                 this.nextTokenSpan = ts.Debug.checkDefined(nextRange);
123740                 this.nextTokenParent = ts.Debug.checkDefined(nextTokenParent);
123741                 this.contextNode = ts.Debug.checkDefined(commonParent);
123742                 // drop cached results
123743                 this.contextNodeAllOnSameLine = undefined;
123744                 this.nextNodeAllOnSameLine = undefined;
123745                 this.tokensAreOnSameLine = undefined;
123746                 this.contextNodeBlockIsOnOneLine = undefined;
123747                 this.nextNodeBlockIsOnOneLine = undefined;
123748             };
123749             FormattingContext.prototype.ContextNodeAllOnSameLine = function () {
123750                 if (this.contextNodeAllOnSameLine === undefined) {
123751                     this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode);
123752                 }
123753                 return this.contextNodeAllOnSameLine;
123754             };
123755             FormattingContext.prototype.NextNodeAllOnSameLine = function () {
123756                 if (this.nextNodeAllOnSameLine === undefined) {
123757                     this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent);
123758                 }
123759                 return this.nextNodeAllOnSameLine;
123760             };
123761             FormattingContext.prototype.TokensAreOnSameLine = function () {
123762                 if (this.tokensAreOnSameLine === undefined) {
123763                     var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
123764                     var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
123765                     this.tokensAreOnSameLine = (startLine === endLine);
123766                 }
123767                 return this.tokensAreOnSameLine;
123768             };
123769             FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () {
123770                 if (this.contextNodeBlockIsOnOneLine === undefined) {
123771                     this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode);
123772                 }
123773                 return this.contextNodeBlockIsOnOneLine;
123774             };
123775             FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () {
123776                 if (this.nextNodeBlockIsOnOneLine === undefined) {
123777                     this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent);
123778                 }
123779                 return this.nextNodeBlockIsOnOneLine;
123780             };
123781             FormattingContext.prototype.NodeIsOnOneLine = function (node) {
123782                 var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
123783                 var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
123784                 return startLine === endLine;
123785             };
123786             FormattingContext.prototype.BlockIsOnOneLine = function (node) {
123787                 var openBrace = ts.findChildOfKind(node, 18 /* OpenBraceToken */, this.sourceFile);
123788                 var closeBrace = ts.findChildOfKind(node, 19 /* CloseBraceToken */, this.sourceFile);
123789                 if (openBrace && closeBrace) {
123790                     var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
123791                     var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
123792                     return startLine === endLine;
123793                 }
123794                 return false;
123795             };
123796             return FormattingContext;
123797         }());
123798         formatting.FormattingContext = FormattingContext;
123799     })(formatting = ts.formatting || (ts.formatting = {}));
123800 })(ts || (ts = {}));
123801 /* @internal */
123802 var ts;
123803 (function (ts) {
123804     var formatting;
123805     (function (formatting) {
123806         var standardScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
123807         var jsxScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
123808         var ScanAction;
123809         (function (ScanAction) {
123810             ScanAction[ScanAction["Scan"] = 0] = "Scan";
123811             ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken";
123812             ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
123813             ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
123814             ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
123815             ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
123816             ScanAction[ScanAction["RescanJsxAttributeValue"] = 6] = "RescanJsxAttributeValue";
123817         })(ScanAction || (ScanAction = {}));
123818         function getFormattingScanner(text, languageVariant, startPos, endPos, cb) {
123819             var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
123820             scanner.setText(text);
123821             scanner.setTextPos(startPos);
123822             var wasNewLine = true;
123823             var leadingTrivia;
123824             var trailingTrivia;
123825             var savedPos;
123826             var lastScanAction;
123827             var lastTokenInfo;
123828             var res = cb({
123829                 advance: advance,
123830                 readTokenInfo: readTokenInfo,
123831                 readEOFTokenRange: readEOFTokenRange,
123832                 isOnToken: isOnToken,
123833                 isOnEOF: isOnEOF,
123834                 getCurrentLeadingTrivia: function () { return leadingTrivia; },
123835                 lastTrailingTriviaWasNewLine: function () { return wasNewLine; },
123836                 skipToEndOf: skipToEndOf,
123837             });
123838             lastTokenInfo = undefined;
123839             scanner.setText(undefined);
123840             return res;
123841             function advance() {
123842                 lastTokenInfo = undefined;
123843                 var isStarted = scanner.getStartPos() !== startPos;
123844                 if (isStarted) {
123845                     wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */;
123846                 }
123847                 else {
123848                     scanner.scan();
123849                 }
123850                 leadingTrivia = undefined;
123851                 trailingTrivia = undefined;
123852                 var pos = scanner.getStartPos();
123853                 // Read leading trivia and token
123854                 while (pos < endPos) {
123855                     var t = scanner.getToken();
123856                     if (!ts.isTrivia(t)) {
123857                         break;
123858                     }
123859                     // consume leading trivia
123860                     scanner.scan();
123861                     var item = {
123862                         pos: pos,
123863                         end: scanner.getStartPos(),
123864                         kind: t
123865                     };
123866                     pos = scanner.getStartPos();
123867                     leadingTrivia = ts.append(leadingTrivia, item);
123868                 }
123869                 savedPos = scanner.getStartPos();
123870             }
123871             function shouldRescanGreaterThanToken(node) {
123872                 switch (node.kind) {
123873                     case 33 /* GreaterThanEqualsToken */:
123874                     case 70 /* GreaterThanGreaterThanEqualsToken */:
123875                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
123876                     case 49 /* GreaterThanGreaterThanGreaterThanToken */:
123877                     case 48 /* GreaterThanGreaterThanToken */:
123878                         return true;
123879                 }
123880                 return false;
123881             }
123882             function shouldRescanJsxIdentifier(node) {
123883                 if (node.parent) {
123884                     switch (node.parent.kind) {
123885                         case 273 /* JsxAttribute */:
123886                         case 268 /* JsxOpeningElement */:
123887                         case 269 /* JsxClosingElement */:
123888                         case 267 /* JsxSelfClosingElement */:
123889                             // 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.
123890                             return ts.isKeyword(node.kind) || node.kind === 75 /* Identifier */;
123891                     }
123892                 }
123893                 return false;
123894             }
123895             function shouldRescanJsxText(node) {
123896                 var isJSXText = ts.isJsxText(node);
123897                 if (isJSXText) {
123898                     var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); });
123899                     if (!containingElement)
123900                         return false; // should never happen
123901                     return !ts.isParenthesizedExpression(containingElement.parent);
123902                 }
123903                 return false;
123904             }
123905             function shouldRescanSlashToken(container) {
123906                 return container.kind === 13 /* RegularExpressionLiteral */;
123907             }
123908             function shouldRescanTemplateToken(container) {
123909                 return container.kind === 16 /* TemplateMiddle */ ||
123910                     container.kind === 17 /* TemplateTail */;
123911             }
123912             function shouldRescanJsxAttributeValue(node) {
123913                 return node.parent && ts.isJsxAttribute(node.parent) && node.parent.initializer === node;
123914             }
123915             function startsWithSlashToken(t) {
123916                 return t === 43 /* SlashToken */ || t === 67 /* SlashEqualsToken */;
123917             }
123918             function readTokenInfo(n) {
123919                 ts.Debug.assert(isOnToken());
123920                 // normally scanner returns the smallest available token
123921                 // check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
123922                 var expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ :
123923                     shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ :
123924                         shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ :
123925                             shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ :
123926                                 shouldRescanJsxText(n) ? 5 /* RescanJsxText */ :
123927                                     shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ :
123928                                         0 /* Scan */;
123929                 if (lastTokenInfo && expectedScanAction === lastScanAction) {
123930                     // readTokenInfo was called before with the same expected scan action.
123931                     // No need to re-scan text, return existing 'lastTokenInfo'
123932                     // it is ok to call fixTokenKind here since it does not affect
123933                     // what portion of text is consumed. In contrast rescanning can change it,
123934                     // i.e. for '>=' when originally scanner eats just one character
123935                     // and rescanning forces it to consume more.
123936                     return fixTokenKind(lastTokenInfo, n);
123937                 }
123938                 if (scanner.getStartPos() !== savedPos) {
123939                     ts.Debug.assert(lastTokenInfo !== undefined);
123940                     // readTokenInfo was called before but scan action differs - rescan text
123941                     scanner.setTextPos(savedPos);
123942                     scanner.scan();
123943                 }
123944                 var currentToken = getNextToken(n, expectedScanAction);
123945                 var token = formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), currentToken);
123946                 // consume trailing trivia
123947                 if (trailingTrivia) {
123948                     trailingTrivia = undefined;
123949                 }
123950                 while (scanner.getStartPos() < endPos) {
123951                     currentToken = scanner.scan();
123952                     if (!ts.isTrivia(currentToken)) {
123953                         break;
123954                     }
123955                     var trivia = formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), currentToken);
123956                     if (!trailingTrivia) {
123957                         trailingTrivia = [];
123958                     }
123959                     trailingTrivia.push(trivia);
123960                     if (currentToken === 4 /* NewLineTrivia */) {
123961                         // move past new line
123962                         scanner.scan();
123963                         break;
123964                     }
123965                 }
123966                 lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token };
123967                 return fixTokenKind(lastTokenInfo, n);
123968             }
123969             function getNextToken(n, expectedScanAction) {
123970                 var token = scanner.getToken();
123971                 lastScanAction = 0 /* Scan */;
123972                 switch (expectedScanAction) {
123973                     case 1 /* RescanGreaterThanToken */:
123974                         if (token === 31 /* GreaterThanToken */) {
123975                             lastScanAction = 1 /* RescanGreaterThanToken */;
123976                             var newToken = scanner.reScanGreaterToken();
123977                             ts.Debug.assert(n.kind === newToken);
123978                             return newToken;
123979                         }
123980                         break;
123981                     case 2 /* RescanSlashToken */:
123982                         if (startsWithSlashToken(token)) {
123983                             lastScanAction = 2 /* RescanSlashToken */;
123984                             var newToken = scanner.reScanSlashToken();
123985                             ts.Debug.assert(n.kind === newToken);
123986                             return newToken;
123987                         }
123988                         break;
123989                     case 3 /* RescanTemplateToken */:
123990                         if (token === 19 /* CloseBraceToken */) {
123991                             lastScanAction = 3 /* RescanTemplateToken */;
123992                             return scanner.reScanTemplateToken(/* isTaggedTemplate */ false);
123993                         }
123994                         break;
123995                     case 4 /* RescanJsxIdentifier */:
123996                         lastScanAction = 4 /* RescanJsxIdentifier */;
123997                         return scanner.scanJsxIdentifier();
123998                     case 5 /* RescanJsxText */:
123999                         lastScanAction = 5 /* RescanJsxText */;
124000                         return scanner.reScanJsxToken();
124001                     case 6 /* RescanJsxAttributeValue */:
124002                         lastScanAction = 6 /* RescanJsxAttributeValue */;
124003                         return scanner.reScanJsxAttributeValue();
124004                     case 0 /* Scan */:
124005                         break;
124006                     default:
124007                         ts.Debug.assertNever(expectedScanAction);
124008                 }
124009                 return token;
124010             }
124011             function readEOFTokenRange() {
124012                 ts.Debug.assert(isOnEOF());
124013                 return formatting.createTextRangeWithKind(scanner.getStartPos(), scanner.getTextPos(), 1 /* EndOfFileToken */);
124014             }
124015             function isOnToken() {
124016                 var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
124017                 var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos();
124018                 return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current);
124019             }
124020             function isOnEOF() {
124021                 var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
124022                 return current === 1 /* EndOfFileToken */;
124023             }
124024             // when containing node in the tree is token
124025             // but its kind differs from the kind that was returned by the scanner,
124026             // then kind needs to be fixed. This might happen in cases
124027             // when parser interprets token differently, i.e keyword treated as identifier
124028             function fixTokenKind(tokenInfo, container) {
124029                 if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {
124030                     tokenInfo.token.kind = container.kind;
124031                 }
124032                 return tokenInfo;
124033             }
124034             function skipToEndOf(node) {
124035                 scanner.setTextPos(node.end);
124036                 savedPos = scanner.getStartPos();
124037                 lastScanAction = undefined;
124038                 lastTokenInfo = undefined;
124039                 wasNewLine = false;
124040                 leadingTrivia = undefined;
124041                 trailingTrivia = undefined;
124042             }
124043         }
124044         formatting.getFormattingScanner = getFormattingScanner;
124045     })(formatting = ts.formatting || (ts.formatting = {}));
124046 })(ts || (ts = {}));
124047 /* @internal */
124048 var ts;
124049 (function (ts) {
124050     var formatting;
124051     (function (formatting) {
124052         formatting.anyContext = ts.emptyArray;
124053         var RuleAction;
124054         (function (RuleAction) {
124055             RuleAction[RuleAction["StopProcessingSpaceActions"] = 1] = "StopProcessingSpaceActions";
124056             RuleAction[RuleAction["StopProcessingTokenActions"] = 2] = "StopProcessingTokenActions";
124057             RuleAction[RuleAction["InsertSpace"] = 4] = "InsertSpace";
124058             RuleAction[RuleAction["InsertNewLine"] = 8] = "InsertNewLine";
124059             RuleAction[RuleAction["DeleteSpace"] = 16] = "DeleteSpace";
124060             RuleAction[RuleAction["DeleteToken"] = 32] = "DeleteToken";
124061             RuleAction[RuleAction["InsertTrailingSemicolon"] = 64] = "InsertTrailingSemicolon";
124062             RuleAction[RuleAction["StopAction"] = 3] = "StopAction";
124063             RuleAction[RuleAction["ModifySpaceAction"] = 28] = "ModifySpaceAction";
124064             RuleAction[RuleAction["ModifyTokenAction"] = 96] = "ModifyTokenAction";
124065         })(RuleAction = formatting.RuleAction || (formatting.RuleAction = {}));
124066         var RuleFlags;
124067         (function (RuleFlags) {
124068             RuleFlags[RuleFlags["None"] = 0] = "None";
124069             RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines";
124070         })(RuleFlags = formatting.RuleFlags || (formatting.RuleFlags = {}));
124071     })(formatting = ts.formatting || (ts.formatting = {}));
124072 })(ts || (ts = {}));
124073 /* @internal */
124074 var ts;
124075 (function (ts) {
124076     var formatting;
124077     (function (formatting) {
124078         function getAllRules() {
124079             var allTokens = [];
124080             for (var token = 0 /* FirstToken */; token <= 152 /* LastToken */; token++) {
124081                 if (token !== 1 /* EndOfFileToken */) {
124082                     allTokens.push(token);
124083                 }
124084             }
124085             function anyTokenExcept() {
124086                 var tokens = [];
124087                 for (var _i = 0; _i < arguments.length; _i++) {
124088                     tokens[_i] = arguments[_i];
124089                 }
124090                 return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false };
124091             }
124092             var anyToken = { tokens: allTokens, isSpecific: false };
124093             var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArrays(allTokens, [3 /* MultiLineCommentTrivia */]));
124094             var anyTokenIncludingEOF = tokenRangeFrom(__spreadArrays(allTokens, [1 /* EndOfFileToken */]));
124095             var keywords = tokenRangeFromRange(77 /* FirstKeyword */, 152 /* LastKeyword */);
124096             var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 74 /* LastBinaryOperator */);
124097             var binaryKeywordOperators = [97 /* InKeyword */, 98 /* InstanceOfKeyword */, 152 /* OfKeyword */, 123 /* AsKeyword */, 133 /* IsKeyword */];
124098             var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */];
124099             var unaryPrefixExpressions = [
124100                 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 75 /* Identifier */, 20 /* OpenParenToken */,
124101                 22 /* OpenBracketToken */, 18 /* OpenBraceToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */
124102             ];
124103             var unaryPreincrementExpressions = [75 /* Identifier */, 20 /* OpenParenToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */];
124104             var unaryPostincrementExpressions = [75 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 99 /* NewKeyword */];
124105             var unaryPredecrementExpressions = [75 /* Identifier */, 20 /* OpenParenToken */, 104 /* ThisKeyword */, 99 /* NewKeyword */];
124106             var unaryPostdecrementExpressions = [75 /* Identifier */, 21 /* CloseParenToken */, 23 /* CloseBracketToken */, 99 /* NewKeyword */];
124107             var comments = [2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */];
124108             var typeNames = __spreadArrays([75 /* Identifier */], ts.typeKeywords);
124109             // Place a space before open brace in a function declaration
124110             // TypeScript: Function can have return types, which can be made of tons of different token kinds
124111             var functionOpenBraceLeftTokenRange = anyTokenIncludingMultilineComments;
124112             // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc)
124113             var typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([75 /* Identifier */, 3 /* MultiLineCommentTrivia */, 80 /* ClassKeyword */, 89 /* ExportKeyword */, 96 /* ImportKeyword */]);
124114             // Place a space before open brace in a control flow construct
124115             var controlOpenBraceLeftTokenRange = tokenRangeFrom([21 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 86 /* DoKeyword */, 107 /* TryKeyword */, 92 /* FinallyKeyword */, 87 /* ElseKeyword */]);
124116             // These rules are higher in priority than user-configurable
124117             var highPriorityCommonRules = [
124118                 // Leave comments alone
124119                 rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* StopProcessingSpaceActions */),
124120                 rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* StopProcessingSpaceActions */),
124121                 rule("NotSpaceBeforeColon", anyToken, 58 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */),
124122                 rule("SpaceAfterColon", 58 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 4 /* InsertSpace */),
124123                 rule("NoSpaceBeforeQuestionMark", anyToken, 57 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
124124                 // insert space after '?' only when it is used in conditional operator
124125                 rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */),
124126                 // in other cases there should be no space between '?' and next token
124127                 rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124128                 rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124129                 rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124130                 rule("NoSpaceBetweenImportParenInImportType", 96 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */),
124131                 // Special handling of unary operators.
124132                 // Prefix operators generally shouldn't have a space between
124133                 // them and their target unary expression.
124134                 rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
124135                 rule("NoSpaceAfterUnaryPreincrementOperator", 45 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124136                 rule("NoSpaceAfterUnaryPredecrementOperator", 46 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124137                 rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 45 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
124138                 rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 46 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */),
124139                 // More unary operator special-casing.
124140                 // DevDiv 181814: Be careful when removing leading whitespace
124141                 // around unary operators.  Examples:
124142                 //      1 - -2  --X--> 1--2
124143                 //      a + ++b --X--> a+++b
124144                 rule("SpaceAfterPostincrementWhenFollowedByAdd", 45 /* PlusPlusToken */, 39 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124145                 rule("SpaceAfterAddWhenFollowedByUnaryPlus", 39 /* PlusToken */, 39 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124146                 rule("SpaceAfterAddWhenFollowedByPreincrement", 39 /* PlusToken */, 45 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124147                 rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 46 /* MinusMinusToken */, 40 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124148                 rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 40 /* MinusToken */, 40 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124149                 rule("SpaceAfterSubtractWhenFollowedByPredecrement", 40 /* MinusToken */, 46 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124150                 rule("NoSpaceAfterCloseBrace", 19 /* CloseBraceToken */, [27 /* CommaToken */, 26 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124151                 // For functions and control block place } on a new line [multi-line rule]
124152                 rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 19 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */),
124153                 // Space/new line after }.
124154                 rule("SpaceAfterCloseBrace", 19 /* CloseBraceToken */, anyTokenExcept(21 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */),
124155                 // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
124156                 // Also should not apply to })
124157                 rule("SpaceBetweenCloseBraceAndElse", 19 /* CloseBraceToken */, 87 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124158                 rule("SpaceBetweenCloseBraceAndWhile", 19 /* CloseBraceToken */, 111 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124159                 rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
124160                 // 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];'
124161                 rule("SpaceAfterConditionalClosingParen", 21 /* CloseParenToken */, 22 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */),
124162                 rule("NoSpaceBetweenFunctionKeywordAndStar", 94 /* FunctionKeyword */, 41 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */),
124163                 rule("SpaceAfterStarInGeneratorDeclaration", 41 /* AsteriskToken */, 75 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */),
124164                 rule("SpaceAfterFunctionInFuncDecl", 94 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */),
124165                 // Insert new line after { and before } in multi-line contexts.
124166                 rule("NewLineAfterOpenBraceInBlockContext", 18 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */),
124167                 // 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.
124168                 // Though, we do extra check on the context to make sure we are dealing with get/set node. Example:
124169                 //      get x() {}
124170                 //      set x(val) {}
124171                 rule("SpaceAfterGetSetInMember", [131 /* GetKeyword */, 142 /* SetKeyword */], 75 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */),
124172                 rule("NoSpaceBetweenYieldKeywordAndStar", 121 /* YieldKeyword */, 41 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */),
124173                 rule("SpaceBetweenYieldOrYieldStarAndOperand", [121 /* YieldKeyword */, 41 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */),
124174                 rule("NoSpaceBetweenReturnAndSemicolon", 101 /* ReturnKeyword */, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124175                 rule("SpaceAfterCertainKeywords", [109 /* VarKeyword */, 105 /* ThrowKeyword */, 99 /* NewKeyword */, 85 /* DeleteKeyword */, 101 /* ReturnKeyword */, 108 /* TypeOfKeyword */, 127 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124176                 rule("SpaceAfterLetConstInVariableDeclaration", [115 /* LetKeyword */, 81 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */),
124177                 rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */),
124178                 // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
124179                 rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124180                 rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124181                 rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */),
124182                 // Async-await
124183                 rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124184                 rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124185                 // Template string
124186                 rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124187                 // JSX opening elements
124188                 rule("SpaceBeforeJsxAttribute", anyToken, 75 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124189                 rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 43 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124190                 rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 43 /* SlashToken */, 31 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124191                 rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 62 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124192                 rule("NoSpaceAfterEqualInJsxAttribute", 62 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124193                 // TypeScript-specific rules
124194                 // Use of module as a function call. e.g.: import m2 = module("m2");
124195                 rule("NoSpaceAfterModuleImport", [135 /* ModuleKeyword */, 139 /* RequireKeyword */], 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124196                 // Add a space around certain TypeScript keywords
124197                 rule("SpaceAfterCertainTypeScriptKeywords", [
124198                     122 /* AbstractKeyword */,
124199                     80 /* ClassKeyword */,
124200                     130 /* DeclareKeyword */,
124201                     84 /* DefaultKeyword */,
124202                     88 /* EnumKeyword */,
124203                     89 /* ExportKeyword */,
124204                     90 /* ExtendsKeyword */,
124205                     131 /* GetKeyword */,
124206                     113 /* ImplementsKeyword */,
124207                     96 /* ImportKeyword */,
124208                     114 /* InterfaceKeyword */,
124209                     135 /* ModuleKeyword */,
124210                     136 /* NamespaceKeyword */,
124211                     117 /* PrivateKeyword */,
124212                     119 /* PublicKeyword */,
124213                     118 /* ProtectedKeyword */,
124214                     138 /* ReadonlyKeyword */,
124215                     142 /* SetKeyword */,
124216                     120 /* StaticKeyword */,
124217                     145 /* TypeKeyword */,
124218                     149 /* FromKeyword */,
124219                     134 /* KeyOfKeyword */,
124220                     132 /* InferKeyword */,
124221                 ], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124222                 rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [90 /* ExtendsKeyword */, 113 /* ImplementsKeyword */, 149 /* FromKeyword */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124223                 // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
124224                 rule("SpaceAfterModuleName", 10 /* StringLiteral */, 18 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */),
124225                 // Lambda expressions
124226                 rule("SpaceBeforeArrow", anyToken, 38 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124227                 rule("SpaceAfterArrow", 38 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124228                 // Optional parameters and let args
124229                 rule("NoSpaceAfterEllipsis", 25 /* DotDotDotToken */, 75 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124230                 rule("NoSpaceAfterOptionalParameters", 57 /* QuestionToken */, [21 /* CloseParenToken */, 27 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */),
124231                 // Remove spaces in empty interface literals. e.g.: x: {}
124232                 rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */),
124233                 // generics and type assertions
124234                 rule("NoSpaceBeforeOpenAngularBracket", typeNames, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
124235                 rule("NoSpaceBetweenCloseParenAndAngularBracket", 21 /* CloseParenToken */, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
124236                 rule("NoSpaceAfterOpenAngularBracket", 29 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
124237                 rule("NoSpaceBeforeCloseAngularBracket", anyToken, 31 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */),
124238                 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 */),
124239                 // decorators
124240                 rule("SpaceBeforeAt", [21 /* CloseParenToken */, 75 /* Identifier */], 59 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124241                 rule("NoSpaceAfterAt", 59 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124242                 // Insert space after @ in decorator
124243                 rule("SpaceAfterDecorator", anyToken, [
124244                     122 /* AbstractKeyword */,
124245                     75 /* Identifier */,
124246                     89 /* ExportKeyword */,
124247                     84 /* DefaultKeyword */,
124248                     80 /* ClassKeyword */,
124249                     120 /* StaticKeyword */,
124250                     119 /* PublicKeyword */,
124251                     117 /* PrivateKeyword */,
124252                     118 /* ProtectedKeyword */,
124253                     131 /* GetKeyword */,
124254                     142 /* SetKeyword */,
124255                     22 /* OpenBracketToken */,
124256                     41 /* AsteriskToken */,
124257                 ], [isEndOfDecoratorContextOnSameLine], 4 /* InsertSpace */),
124258                 rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 53 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */),
124259                 rule("NoSpaceAfterNewKeywordOnConstructorSignature", 99 /* NewKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */),
124260                 rule("SpaceLessThanAndNonJSXTypeAnnotation", 29 /* LessThanToken */, 29 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124261             ];
124262             // These rules are applied after high priority
124263             var userConfigurableRules = [
124264                 // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
124265                 rule("SpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124266                 rule("NoSpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124267                 rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */),
124268                 rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */),
124269                 // Insert space after function keyword for anonymous functions
124270                 rule("SpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */),
124271                 rule("NoSpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */),
124272                 // Insert space after keywords in control flow statements
124273                 rule("SpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */),
124274                 rule("NoSpaceAfterKeywordInControl", keywords, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */),
124275                 // Insert space after opening and before closing nonempty parenthesis
124276                 rule("SpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124277                 rule("SpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124278                 rule("SpaceBetweenOpenParens", 20 /* OpenParenToken */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124279                 rule("NoSpaceBetweenParens", 20 /* OpenParenToken */, 21 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124280                 rule("NoSpaceAfterOpenParen", 20 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124281                 rule("NoSpaceBeforeCloseParen", anyToken, 21 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124282                 // Insert space after opening and before closing nonempty brackets
124283                 rule("SpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124284                 rule("SpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124285                 rule("NoSpaceBetweenBrackets", 22 /* OpenBracketToken */, 23 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124286                 rule("NoSpaceAfterOpenBracket", 22 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124287                 rule("NoSpaceBeforeCloseBracket", anyToken, 23 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124288                 // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
124289                 rule("SpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
124290                 rule("SpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */),
124291                 rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */),
124292                 rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124293                 rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124294                 // Insert a space after opening and before closing empty brace brackets
124295                 rule("SpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */),
124296                 rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124297                 // Insert space after opening and before closing template string braces
124298                 rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124299                 rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124300                 rule("NoSpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124301                 rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124302                 // No space after { and before } in JSX expression
124303                 rule("SpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
124304                 rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */),
124305                 rule("NoSpaceAfterOpenBraceInJsxExpression", 18 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
124306                 rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 19 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */),
124307                 // Insert space after semicolon in for statement
124308                 rule("SpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */),
124309                 rule("NoSpaceAfterSemicolonInFor", 26 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */),
124310                 // Insert space before and after binary operators
124311                 rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124312                 rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */),
124313                 rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
124314                 rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */),
124315                 rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */),
124316                 rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */),
124317                 // Open Brace braces after control block
124318                 rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
124319                 // Open Brace braces after function
124320                 // TypeScript: Function can have return types, which can be made of tons of different token kinds
124321                 rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
124322                 // Open Brace braces after TypeScript module/class/interface
124323                 rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */),
124324                 rule("SpaceAfterTypeAssertion", 31 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */),
124325                 rule("NoSpaceAfterTypeAssertion", 31 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */),
124326                 rule("SpaceBeforeTypeAnnotation", anyToken, 58 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */),
124327                 rule("NoSpaceBeforeTypeAnnotation", anyToken, 58 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */),
124328                 rule("NoOptionalSemicolon", 26 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", ts.SemicolonPreference.Remove), isSemicolonDeletionContext], 32 /* DeleteToken */),
124329                 rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", ts.SemicolonPreference.Insert), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */),
124330             ];
124331             // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list.
124332             var lowPriorityCommonRules = [
124333                 // Space after keyword but not before ; or : or ?
124334                 rule("NoSpaceBeforeSemicolon", anyToken, 26 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124335                 rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
124336                 rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
124337                 rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 18 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */),
124338                 rule("NoSpaceBeforeComma", anyToken, 27 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124339                 // No space before and after indexer `x[]`
124340                 rule("NoSpaceBeforeOpenBracket", anyTokenExcept(126 /* AsyncKeyword */, 78 /* CaseKeyword */), 22 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */),
124341                 rule("NoSpaceAfterCloseBracket", 23 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */),
124342                 rule("SpaceAfterSemicolon", 26 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124343                 // Remove extra space between for and await
124344                 rule("SpaceBetweenForAndAwaitKeyword", 93 /* ForKeyword */, 127 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124345                 // Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
124346                 // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
124347                 rule("SpaceBetweenStatements", [21 /* CloseParenToken */, 86 /* DoKeyword */, 87 /* ElseKeyword */, 78 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 4 /* InsertSpace */),
124348                 // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
124349                 rule("SpaceAfterTryFinally", [107 /* TryKeyword */, 92 /* FinallyKeyword */], 18 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */),
124350             ];
124351             return __spreadArrays(highPriorityCommonRules, userConfigurableRules, lowPriorityCommonRules);
124352         }
124353         formatting.getAllRules = getAllRules;
124354         /**
124355          * A rule takes a two tokens (left/right) and a particular context
124356          * for which you're meant to look at them. You then declare what should the
124357          * whitespace annotation be between these tokens via the action param.
124358          *
124359          * @param debugName Name to print
124360          * @param left The left side of the comparison
124361          * @param right The right side of the comparison
124362          * @param context A set of filters to narrow down the space in which this formatter rule applies
124363          * @param action a declaration of the expected whitespace
124364          * @param flags whether the rule deletes a line or not, defaults to no-op
124365          */
124366         function rule(debugName, left, right, context, action, flags) {
124367             if (flags === void 0) { flags = 0 /* None */; }
124368             return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName: debugName, context: context, action: action, flags: flags } };
124369         }
124370         function tokenRangeFrom(tokens) {
124371             return { tokens: tokens, isSpecific: true };
124372         }
124373         function toTokenRange(arg) {
124374             return typeof arg === "number" ? tokenRangeFrom([arg]) : ts.isArray(arg) ? tokenRangeFrom(arg) : arg;
124375         }
124376         function tokenRangeFromRange(from, to, except) {
124377             if (except === void 0) { except = []; }
124378             var tokens = [];
124379             for (var token = from; token <= to; token++) {
124380                 if (!ts.contains(except, token)) {
124381                     tokens.push(token);
124382                 }
124383             }
124384             return tokenRangeFrom(tokens);
124385         }
124386         ///
124387         /// Contexts
124388         ///
124389         function optionEquals(optionName, optionValue) {
124390             return function (context) { return context.options && context.options[optionName] === optionValue; };
124391         }
124392         function isOptionEnabled(optionName) {
124393             return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; };
124394         }
124395         function isOptionDisabled(optionName) {
124396             return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !context.options[optionName]; };
124397         }
124398         function isOptionDisabledOrUndefined(optionName) {
124399             return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; };
124400         }
124401         function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) {
124402             return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); };
124403         }
124404         function isOptionEnabledOrUndefined(optionName) {
124405             return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; };
124406         }
124407         function isForContext(context) {
124408             return context.contextNode.kind === 230 /* ForStatement */;
124409         }
124410         function isNotForContext(context) {
124411             return !isForContext(context);
124412         }
124413         function isBinaryOpContext(context) {
124414             switch (context.contextNode.kind) {
124415                 case 209 /* BinaryExpression */:
124416                     return context.contextNode.operatorToken.kind !== 27 /* CommaToken */;
124417                 case 210 /* ConditionalExpression */:
124418                 case 180 /* ConditionalType */:
124419                 case 217 /* AsExpression */:
124420                 case 263 /* ExportSpecifier */:
124421                 case 258 /* ImportSpecifier */:
124422                 case 168 /* TypePredicate */:
124423                 case 178 /* UnionType */:
124424                 case 179 /* IntersectionType */:
124425                     return true;
124426                 // equals in binding elements: function foo([[x, y] = [1, 2]])
124427                 case 191 /* BindingElement */:
124428                 // equals in type X = ...
124429                 // falls through
124430                 case 247 /* TypeAliasDeclaration */:
124431                 // equal in import a = module('a');
124432                 // falls through
124433                 case 253 /* ImportEqualsDeclaration */:
124434                 // equal in let a = 0
124435                 // falls through
124436                 case 242 /* VariableDeclaration */:
124437                 // equal in p = 0
124438                 // falls through
124439                 case 156 /* Parameter */:
124440                 case 284 /* EnumMember */:
124441                 case 159 /* PropertyDeclaration */:
124442                 case 158 /* PropertySignature */:
124443                     return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */;
124444                 // "in" keyword in for (let x in []) { }
124445                 case 231 /* ForInStatement */:
124446                 // "in" keyword in [P in keyof T]: T[P]
124447                 // falls through
124448                 case 155 /* TypeParameter */:
124449                     return context.currentTokenSpan.kind === 97 /* InKeyword */ || context.nextTokenSpan.kind === 97 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */;
124450                 // Technically, "of" is not a binary operator, but format it the same way as "in"
124451                 case 232 /* ForOfStatement */:
124452                     return context.currentTokenSpan.kind === 152 /* OfKeyword */ || context.nextTokenSpan.kind === 152 /* OfKeyword */;
124453             }
124454             return false;
124455         }
124456         function isNotBinaryOpContext(context) {
124457             return !isBinaryOpContext(context);
124458         }
124459         function isNotTypeAnnotationContext(context) {
124460             return !isTypeAnnotationContext(context);
124461         }
124462         function isTypeAnnotationContext(context) {
124463             var contextKind = context.contextNode.kind;
124464             return contextKind === 159 /* PropertyDeclaration */ ||
124465                 contextKind === 158 /* PropertySignature */ ||
124466                 contextKind === 156 /* Parameter */ ||
124467                 contextKind === 242 /* VariableDeclaration */ ||
124468                 ts.isFunctionLikeKind(contextKind);
124469         }
124470         function isConditionalOperatorContext(context) {
124471             return context.contextNode.kind === 210 /* ConditionalExpression */ ||
124472                 context.contextNode.kind === 180 /* ConditionalType */;
124473         }
124474         function isSameLineTokenOrBeforeBlockContext(context) {
124475             return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
124476         }
124477         function isBraceWrappedContext(context) {
124478             return context.contextNode.kind === 189 /* ObjectBindingPattern */ ||
124479                 context.contextNode.kind === 186 /* MappedType */ ||
124480                 isSingleLineBlockContext(context);
124481         }
124482         // This check is done before an open brace in a control construct, a function, or a typescript block declaration
124483         function isBeforeMultilineBlockContext(context) {
124484             return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
124485         }
124486         function isMultilineBlockContext(context) {
124487             return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
124488         }
124489         function isSingleLineBlockContext(context) {
124490             return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine());
124491         }
124492         function isBlockContext(context) {
124493             return nodeIsBlockContext(context.contextNode);
124494         }
124495         function isBeforeBlockContext(context) {
124496             return nodeIsBlockContext(context.nextTokenParent);
124497         }
124498         // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children
124499         function nodeIsBlockContext(node) {
124500             if (nodeIsTypeScriptDeclWithBlockContext(node)) {
124501                 // 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).
124502                 return true;
124503             }
124504             switch (node.kind) {
124505                 case 223 /* Block */:
124506                 case 251 /* CaseBlock */:
124507                 case 193 /* ObjectLiteralExpression */:
124508                 case 250 /* ModuleBlock */:
124509                     return true;
124510             }
124511             return false;
124512         }
124513         function isFunctionDeclContext(context) {
124514             switch (context.contextNode.kind) {
124515                 case 244 /* FunctionDeclaration */:
124516                 case 161 /* MethodDeclaration */:
124517                 case 160 /* MethodSignature */:
124518                 // case SyntaxKind.MemberFunctionDeclaration:
124519                 // falls through
124520                 case 163 /* GetAccessor */:
124521                 case 164 /* SetAccessor */:
124522                 // case SyntaxKind.MethodSignature:
124523                 // falls through
124524                 case 165 /* CallSignature */:
124525                 case 201 /* FunctionExpression */:
124526                 case 162 /* Constructor */:
124527                 case 202 /* ArrowFunction */:
124528                 // case SyntaxKind.ConstructorDeclaration:
124529                 // case SyntaxKind.SimpleArrowFunctionExpression:
124530                 // case SyntaxKind.ParenthesizedArrowFunctionExpression:
124531                 // falls through
124532                 case 246 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
124533                     return true;
124534             }
124535             return false;
124536         }
124537         function isNotFunctionDeclContext(context) {
124538             return !isFunctionDeclContext(context);
124539         }
124540         function isFunctionDeclarationOrFunctionExpressionContext(context) {
124541             return context.contextNode.kind === 244 /* FunctionDeclaration */ || context.contextNode.kind === 201 /* FunctionExpression */;
124542         }
124543         function isTypeScriptDeclWithBlockContext(context) {
124544             return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
124545         }
124546         function nodeIsTypeScriptDeclWithBlockContext(node) {
124547             switch (node.kind) {
124548                 case 245 /* ClassDeclaration */:
124549                 case 214 /* ClassExpression */:
124550                 case 246 /* InterfaceDeclaration */:
124551                 case 248 /* EnumDeclaration */:
124552                 case 173 /* TypeLiteral */:
124553                 case 249 /* ModuleDeclaration */:
124554                 case 260 /* ExportDeclaration */:
124555                 case 261 /* NamedExports */:
124556                 case 254 /* ImportDeclaration */:
124557                 case 257 /* NamedImports */:
124558                     return true;
124559             }
124560             return false;
124561         }
124562         function isAfterCodeBlockContext(context) {
124563             switch (context.currentTokenParent.kind) {
124564                 case 245 /* ClassDeclaration */:
124565                 case 249 /* ModuleDeclaration */:
124566                 case 248 /* EnumDeclaration */:
124567                 case 280 /* CatchClause */:
124568                 case 250 /* ModuleBlock */:
124569                 case 237 /* SwitchStatement */:
124570                     return true;
124571                 case 223 /* Block */: {
124572                     var blockParent = context.currentTokenParent.parent;
124573                     // In a codefix scenario, we can't rely on parents being set. So just always return true.
124574                     if (!blockParent || blockParent.kind !== 202 /* ArrowFunction */ && blockParent.kind !== 201 /* FunctionExpression */) {
124575                         return true;
124576                     }
124577                 }
124578             }
124579             return false;
124580         }
124581         function isControlDeclContext(context) {
124582             switch (context.contextNode.kind) {
124583                 case 227 /* IfStatement */:
124584                 case 237 /* SwitchStatement */:
124585                 case 230 /* ForStatement */:
124586                 case 231 /* ForInStatement */:
124587                 case 232 /* ForOfStatement */:
124588                 case 229 /* WhileStatement */:
124589                 case 240 /* TryStatement */:
124590                 case 228 /* DoStatement */:
124591                 case 236 /* WithStatement */:
124592                 // TODO
124593                 // case SyntaxKind.ElseClause:
124594                 // falls through
124595                 case 280 /* CatchClause */:
124596                     return true;
124597                 default:
124598                     return false;
124599             }
124600         }
124601         function isObjectContext(context) {
124602             return context.contextNode.kind === 193 /* ObjectLiteralExpression */;
124603         }
124604         function isFunctionCallContext(context) {
124605             return context.contextNode.kind === 196 /* CallExpression */;
124606         }
124607         function isNewContext(context) {
124608             return context.contextNode.kind === 197 /* NewExpression */;
124609         }
124610         function isFunctionCallOrNewContext(context) {
124611             return isFunctionCallContext(context) || isNewContext(context);
124612         }
124613         function isPreviousTokenNotComma(context) {
124614             return context.currentTokenSpan.kind !== 27 /* CommaToken */;
124615         }
124616         function isNextTokenNotCloseBracket(context) {
124617             return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */;
124618         }
124619         function isNextTokenNotCloseParen(context) {
124620             return context.nextTokenSpan.kind !== 21 /* CloseParenToken */;
124621         }
124622         function isArrowFunctionContext(context) {
124623             return context.contextNode.kind === 202 /* ArrowFunction */;
124624         }
124625         function isImportTypeContext(context) {
124626             return context.contextNode.kind === 188 /* ImportType */;
124627         }
124628         function isNonJsxSameLineTokenContext(context) {
124629             return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */;
124630         }
124631         function isNonJsxElementOrFragmentContext(context) {
124632             return context.contextNode.kind !== 266 /* JsxElement */ && context.contextNode.kind !== 270 /* JsxFragment */;
124633         }
124634         function isJsxExpressionContext(context) {
124635             return context.contextNode.kind === 276 /* JsxExpression */ || context.contextNode.kind === 275 /* JsxSpreadAttribute */;
124636         }
124637         function isNextTokenParentJsxAttribute(context) {
124638             return context.nextTokenParent.kind === 273 /* JsxAttribute */;
124639         }
124640         function isJsxAttributeContext(context) {
124641             return context.contextNode.kind === 273 /* JsxAttribute */;
124642         }
124643         function isJsxSelfClosingElementContext(context) {
124644             return context.contextNode.kind === 267 /* JsxSelfClosingElement */;
124645         }
124646         function isNotBeforeBlockInFunctionDeclarationContext(context) {
124647             return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
124648         }
124649         function isEndOfDecoratorContextOnSameLine(context) {
124650             return context.TokensAreOnSameLine() &&
124651                 !!context.contextNode.decorators &&
124652                 nodeIsInDecoratorContext(context.currentTokenParent) &&
124653                 !nodeIsInDecoratorContext(context.nextTokenParent);
124654         }
124655         function nodeIsInDecoratorContext(node) {
124656             while (ts.isExpressionNode(node)) {
124657                 node = node.parent;
124658             }
124659             return node.kind === 157 /* Decorator */;
124660         }
124661         function isStartOfVariableDeclarationList(context) {
124662             return context.currentTokenParent.kind === 243 /* VariableDeclarationList */ &&
124663                 context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
124664         }
124665         function isNotFormatOnEnter(context) {
124666             return context.formattingRequestKind !== 2 /* FormatOnEnter */;
124667         }
124668         function isModuleDeclContext(context) {
124669             return context.contextNode.kind === 249 /* ModuleDeclaration */;
124670         }
124671         function isObjectTypeContext(context) {
124672             return context.contextNode.kind === 173 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
124673         }
124674         function isConstructorSignatureContext(context) {
124675             return context.contextNode.kind === 166 /* ConstructSignature */;
124676         }
124677         function isTypeArgumentOrParameterOrAssertion(token, parent) {
124678             if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) {
124679                 return false;
124680             }
124681             switch (parent.kind) {
124682                 case 169 /* TypeReference */:
124683                 case 199 /* TypeAssertionExpression */:
124684                 case 247 /* TypeAliasDeclaration */:
124685                 case 245 /* ClassDeclaration */:
124686                 case 214 /* ClassExpression */:
124687                 case 246 /* InterfaceDeclaration */:
124688                 case 244 /* FunctionDeclaration */:
124689                 case 201 /* FunctionExpression */:
124690                 case 202 /* ArrowFunction */:
124691                 case 161 /* MethodDeclaration */:
124692                 case 160 /* MethodSignature */:
124693                 case 165 /* CallSignature */:
124694                 case 166 /* ConstructSignature */:
124695                 case 196 /* CallExpression */:
124696                 case 197 /* NewExpression */:
124697                 case 216 /* ExpressionWithTypeArguments */:
124698                     return true;
124699                 default:
124700                     return false;
124701             }
124702         }
124703         function isTypeArgumentOrParameterOrAssertionContext(context) {
124704             return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) ||
124705                 isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
124706         }
124707         function isTypeAssertionContext(context) {
124708             return context.contextNode.kind === 199 /* TypeAssertionExpression */;
124709         }
124710         function isVoidOpContext(context) {
124711             return context.currentTokenSpan.kind === 110 /* VoidKeyword */ && context.currentTokenParent.kind === 205 /* VoidExpression */;
124712         }
124713         function isYieldOrYieldStarWithOperand(context) {
124714             return context.contextNode.kind === 212 /* YieldExpression */ && context.contextNode.expression !== undefined;
124715         }
124716         function isNonNullAssertionContext(context) {
124717             return context.contextNode.kind === 218 /* NonNullExpression */;
124718         }
124719         function isNotStatementConditionContext(context) {
124720             return !isStatementConditionContext(context);
124721         }
124722         function isStatementConditionContext(context) {
124723             switch (context.contextNode.kind) {
124724                 case 227 /* IfStatement */:
124725                 case 230 /* ForStatement */:
124726                 case 231 /* ForInStatement */:
124727                 case 232 /* ForOfStatement */:
124728                 case 228 /* DoStatement */:
124729                 case 229 /* WhileStatement */:
124730                     return true;
124731                 default:
124732                     return false;
124733             }
124734         }
124735         function isSemicolonDeletionContext(context) {
124736             var nextTokenKind = context.nextTokenSpan.kind;
124737             var nextTokenStart = context.nextTokenSpan.pos;
124738             if (ts.isTrivia(nextTokenKind)) {
124739                 var nextRealToken = context.nextTokenParent === context.currentTokenParent
124740                     ? ts.findNextToken(context.currentTokenParent, ts.findAncestor(context.currentTokenParent, function (a) { return !a.parent; }), context.sourceFile)
124741                     : context.nextTokenParent.getFirstToken(context.sourceFile);
124742                 if (!nextRealToken) {
124743                     return true;
124744                 }
124745                 nextTokenKind = nextRealToken.kind;
124746                 nextTokenStart = nextRealToken.getStart(context.sourceFile);
124747             }
124748             var startLine = context.sourceFile.getLineAndCharacterOfPosition(context.currentTokenSpan.pos).line;
124749             var endLine = context.sourceFile.getLineAndCharacterOfPosition(nextTokenStart).line;
124750             if (startLine === endLine) {
124751                 return nextTokenKind === 19 /* CloseBraceToken */
124752                     || nextTokenKind === 1 /* EndOfFileToken */;
124753             }
124754             if (nextTokenKind === 222 /* SemicolonClassElement */ ||
124755                 nextTokenKind === 26 /* SemicolonToken */) {
124756                 return false;
124757             }
124758             if (context.contextNode.kind === 246 /* InterfaceDeclaration */ ||
124759                 context.contextNode.kind === 247 /* TypeAliasDeclaration */) {
124760                 // Can’t remove semicolon after `foo`; it would parse as a method declaration:
124761                 //
124762                 // interface I {
124763                 //   foo;
124764                 //   (): void
124765                 // }
124766                 return !ts.isPropertySignature(context.currentTokenParent)
124767                     || !!context.currentTokenParent.type
124768                     || nextTokenKind !== 20 /* OpenParenToken */;
124769             }
124770             if (ts.isPropertyDeclaration(context.currentTokenParent)) {
124771                 return !context.currentTokenParent.initializer;
124772             }
124773             return context.currentTokenParent.kind !== 230 /* ForStatement */
124774                 && context.currentTokenParent.kind !== 224 /* EmptyStatement */
124775                 && context.currentTokenParent.kind !== 222 /* SemicolonClassElement */
124776                 && nextTokenKind !== 22 /* OpenBracketToken */
124777                 && nextTokenKind !== 20 /* OpenParenToken */
124778                 && nextTokenKind !== 39 /* PlusToken */
124779                 && nextTokenKind !== 40 /* MinusToken */
124780                 && nextTokenKind !== 43 /* SlashToken */
124781                 && nextTokenKind !== 13 /* RegularExpressionLiteral */
124782                 && nextTokenKind !== 27 /* CommaToken */
124783                 && nextTokenKind !== 211 /* TemplateExpression */
124784                 && nextTokenKind !== 15 /* TemplateHead */
124785                 && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */
124786                 && nextTokenKind !== 24 /* DotToken */;
124787         }
124788         function isSemicolonInsertionContext(context) {
124789             return ts.positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile);
124790         }
124791     })(formatting = ts.formatting || (ts.formatting = {}));
124792 })(ts || (ts = {}));
124793 /* @internal */
124794 var ts;
124795 (function (ts) {
124796     var formatting;
124797     (function (formatting) {
124798         function getFormatContext(options, host) {
124799             return { options: options, getRules: getRulesMap(), host: host };
124800         }
124801         formatting.getFormatContext = getFormatContext;
124802         var rulesMapCache;
124803         function getRulesMap() {
124804             if (rulesMapCache === undefined) {
124805                 rulesMapCache = createRulesMap(formatting.getAllRules());
124806             }
124807             return rulesMapCache;
124808         }
124809         /**
124810          * For a given rule action, gets a mask of other rule actions that
124811          * cannot be applied at the same position.
124812          */
124813         function getRuleActionExclusion(ruleAction) {
124814             var mask = 0;
124815             if (ruleAction & 1 /* StopProcessingSpaceActions */) {
124816                 mask |= 28 /* ModifySpaceAction */;
124817             }
124818             if (ruleAction & 2 /* StopProcessingTokenActions */) {
124819                 mask |= 96 /* ModifyTokenAction */;
124820             }
124821             if (ruleAction & 28 /* ModifySpaceAction */) {
124822                 mask |= 28 /* ModifySpaceAction */;
124823             }
124824             if (ruleAction & 96 /* ModifyTokenAction */) {
124825                 mask |= 96 /* ModifyTokenAction */;
124826             }
124827             return mask;
124828         }
124829         function createRulesMap(rules) {
124830             var map = buildMap(rules);
124831             return function (context) {
124832                 var bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)];
124833                 if (bucket) {
124834                     var rules_1 = [];
124835                     var ruleActionMask = 0;
124836                     for (var _i = 0, bucket_1 = bucket; _i < bucket_1.length; _i++) {
124837                         var rule = bucket_1[_i];
124838                         var acceptRuleActions = ~getRuleActionExclusion(ruleActionMask);
124839                         if (rule.action & acceptRuleActions && ts.every(rule.context, function (c) { return c(context); })) {
124840                             rules_1.push(rule);
124841                             ruleActionMask |= rule.action;
124842                         }
124843                     }
124844                     if (rules_1.length) {
124845                         return rules_1;
124846                     }
124847                 }
124848             };
124849         }
124850         function buildMap(rules) {
124851             // Map from bucket index to array of rules
124852             var map = new Array(mapRowLength * mapRowLength);
124853             // This array is used only during construction of the rulesbucket in the map
124854             var rulesBucketConstructionStateList = new Array(map.length);
124855             for (var _i = 0, rules_2 = rules; _i < rules_2.length; _i++) {
124856                 var rule = rules_2[_i];
124857                 var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
124858                 for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
124859                     var left = _b[_a];
124860                     for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
124861                         var right = _d[_c];
124862                         var index = getRuleBucketIndex(left, right);
124863                         var rulesBucket = map[index];
124864                         if (rulesBucket === undefined) {
124865                             rulesBucket = map[index] = [];
124866                         }
124867                         addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
124868                     }
124869                 }
124870             }
124871             return map;
124872         }
124873         function getRuleBucketIndex(row, column) {
124874             ts.Debug.assert(row <= 152 /* LastKeyword */ && column <= 152 /* LastKeyword */, "Must compute formatting context from tokens");
124875             return (row * mapRowLength) + column;
124876         }
124877         var maskBitSize = 5;
124878         var mask = 31; // MaskBitSize bits
124879         var mapRowLength = 152 /* LastToken */ + 1;
124880         var RulesPosition;
124881         (function (RulesPosition) {
124882             RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific";
124883             RulesPosition[RulesPosition["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny";
124884             RulesPosition[RulesPosition["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific";
124885             RulesPosition[RulesPosition["ContextRulesAny"] = maskBitSize * 3] = "ContextRulesAny";
124886             RulesPosition[RulesPosition["NoContextRulesSpecific"] = maskBitSize * 4] = "NoContextRulesSpecific";
124887             RulesPosition[RulesPosition["NoContextRulesAny"] = maskBitSize * 5] = "NoContextRulesAny";
124888         })(RulesPosition || (RulesPosition = {}));
124889         // The Rules list contains all the inserted rules into a rulebucket in the following order:
124890         //    1- Ignore rules with specific token combination
124891         //    2- Ignore rules with any token combination
124892         //    3- Context rules with specific token combination
124893         //    4- Context rules with any token combination
124894         //    5- Non-context rules with specific token combination
124895         //    6- Non-context rules with any token combination
124896         //
124897         // The member rulesInsertionIndexBitmap is used to describe the number of rules
124898         // in each sub-bucket (above) hence can be used to know the index of where to insert
124899         // the next rule. It's a bitmap which contains 6 different sections each is given 5 bits.
124900         //
124901         // Example:
124902         // In order to insert a rule to the end of sub-bucket (3), we get the index by adding
124903         // the values in the bitmap segments 3rd, 2nd, and 1st.
124904         function addRule(rules, rule, specificTokens, constructionState, rulesBucketIndex) {
124905             var position = rule.action & 3 /* StopAction */ ?
124906                 specificTokens ? RulesPosition.StopRulesSpecific : RulesPosition.StopRulesAny :
124907                 rule.context !== formatting.anyContext ?
124908                     specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny :
124909                     specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny;
124910             var state = constructionState[rulesBucketIndex] || 0;
124911             rules.splice(getInsertionIndex(state, position), 0, rule);
124912             constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position);
124913         }
124914         function getInsertionIndex(indexBitmap, maskPosition) {
124915             var index = 0;
124916             for (var pos = 0; pos <= maskPosition; pos += maskBitSize) {
124917                 index += indexBitmap & mask;
124918                 indexBitmap >>= maskBitSize;
124919             }
124920             return index;
124921         }
124922         function increaseInsertionIndex(indexBitmap, maskPosition) {
124923             var value = ((indexBitmap >> maskPosition) & mask) + 1;
124924             ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
124925             return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition);
124926         }
124927     })(formatting = ts.formatting || (ts.formatting = {}));
124928 })(ts || (ts = {}));
124929 /* @internal */
124930 var ts;
124931 (function (ts) {
124932     var formatting;
124933     (function (formatting) {
124934         function createTextRangeWithKind(pos, end, kind) {
124935             var textRangeWithKind = { pos: pos, end: end, kind: kind };
124936             if (ts.Debug.isDebugging) {
124937                 Object.defineProperty(textRangeWithKind, "__debugKind", {
124938                     get: function () { return ts.Debug.formatSyntaxKind(kind); },
124939                 });
124940             }
124941             return textRangeWithKind;
124942         }
124943         formatting.createTextRangeWithKind = createTextRangeWithKind;
124944         var Constants;
124945         (function (Constants) {
124946             Constants[Constants["Unknown"] = -1] = "Unknown";
124947         })(Constants || (Constants = {}));
124948         function formatOnEnter(position, sourceFile, formatContext) {
124949             var line = sourceFile.getLineAndCharacterOfPosition(position).line;
124950             if (line === 0) {
124951                 return [];
124952             }
124953             // After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
124954             // If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
124955             // trailing whitespaces. So the end of the formatting span should be the later one between:
124956             //  1. the end of the previous line
124957             //  2. the last non-whitespace character in the current line
124958             var endOfFormatSpan = ts.getEndLinePosition(line, sourceFile);
124959             while (ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
124960                 endOfFormatSpan--;
124961             }
124962             // 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
124963             // touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
124964             // previous character before the end of format span is line break character as well.
124965             if (ts.isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
124966                 endOfFormatSpan--;
124967             }
124968             var span = {
124969                 // get start position for the previous line
124970                 pos: ts.getStartPositionOfLine(line - 1, sourceFile),
124971                 // end value is exclusive so add 1 to the result
124972                 end: endOfFormatSpan + 1
124973             };
124974             return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */);
124975         }
124976         formatting.formatOnEnter = formatOnEnter;
124977         function formatOnSemicolon(position, sourceFile, formatContext) {
124978             var semicolon = findImmediatelyPrecedingTokenOfKind(position, 26 /* SemicolonToken */, sourceFile);
124979             return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */);
124980         }
124981         formatting.formatOnSemicolon = formatOnSemicolon;
124982         function formatOnOpeningCurly(position, sourceFile, formatContext) {
124983             var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 18 /* OpenBraceToken */, sourceFile);
124984             if (!openingCurly) {
124985                 return [];
124986             }
124987             var curlyBraceRange = openingCurly.parent;
124988             var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
124989             /**
124990              * We limit the span to end at the opening curly to handle the case where
124991              * the brace matched to that just typed will be incorrect after further edits.
124992              * For example, we could type the opening curly for the following method
124993              * body without brace-matching activated:
124994              * ```
124995              * class C {
124996              *     foo()
124997              * }
124998              * ```
124999              * and we wouldn't want to move the closing brace.
125000              */
125001             var textRange = {
125002                 pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile),
125003                 end: position
125004             };
125005             return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */);
125006         }
125007         formatting.formatOnOpeningCurly = formatOnOpeningCurly;
125008         function formatOnClosingCurly(position, sourceFile, formatContext) {
125009             var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 19 /* CloseBraceToken */, sourceFile);
125010             return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */);
125011         }
125012         formatting.formatOnClosingCurly = formatOnClosingCurly;
125013         function formatDocument(sourceFile, formatContext) {
125014             var span = {
125015                 pos: 0,
125016                 end: sourceFile.text.length
125017             };
125018             return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */);
125019         }
125020         formatting.formatDocument = formatDocument;
125021         function formatSelection(start, end, sourceFile, formatContext) {
125022             // format from the beginning of the line
125023             var span = {
125024                 pos: ts.getLineStartPositionForPosition(start, sourceFile),
125025                 end: end,
125026             };
125027             return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */);
125028         }
125029         formatting.formatSelection = formatSelection;
125030         /**
125031          * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment).
125032          * @param expectedTokenKind The kind of the last token constituting the desired parent node.
125033          */
125034         function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) {
125035             var precedingToken = ts.findPrecedingToken(end, sourceFile);
125036             return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ?
125037                 precedingToken :
125038                 undefined;
125039         }
125040         /**
125041          * Finds the highest node enclosing `node` at the same list level as `node`
125042          * and whose end does not exceed `node.end`.
125043          *
125044          * Consider typing the following
125045          * ```
125046          * let x = 1;
125047          * while (true) {
125048          * }
125049          * ```
125050          * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding
125051          * variable declaration.
125052          */
125053         function findOutermostNodeWithinListLevel(node) {
125054             var current = node;
125055             while (current &&
125056                 current.parent &&
125057                 current.parent.end === node.end &&
125058                 !isListElement(current.parent, current)) {
125059                 current = current.parent;
125060             }
125061             return current;
125062         }
125063         // Returns true if node is a element in some list in parent
125064         // i.e. parent is class declaration with the list of members and node is one of members.
125065         function isListElement(parent, node) {
125066             switch (parent.kind) {
125067                 case 245 /* ClassDeclaration */:
125068                 case 246 /* InterfaceDeclaration */:
125069                     return ts.rangeContainsRange(parent.members, node);
125070                 case 249 /* ModuleDeclaration */:
125071                     var body = parent.body;
125072                     return !!body && body.kind === 250 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
125073                 case 290 /* SourceFile */:
125074                 case 223 /* Block */:
125075                 case 250 /* ModuleBlock */:
125076                     return ts.rangeContainsRange(parent.statements, node);
125077                 case 280 /* CatchClause */:
125078                     return ts.rangeContainsRange(parent.block.statements, node);
125079             }
125080             return false;
125081         }
125082         /** find node that fully contains given text range */
125083         function findEnclosingNode(range, sourceFile) {
125084             return find(sourceFile);
125085             function find(n) {
125086                 var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });
125087                 if (candidate) {
125088                     var result = find(candidate);
125089                     if (result) {
125090                         return result;
125091                     }
125092                 }
125093                 return n;
125094             }
125095         }
125096         /** formatting is not applied to ranges that contain parse errors.
125097          * This function will return a predicate that for a given text range will tell
125098          * if there are any parse errors that overlap with the range.
125099          */
125100         function prepareRangeContainsErrorFunction(errors, originalRange) {
125101             if (!errors.length) {
125102                 return rangeHasNoErrors;
125103             }
125104             // pick only errors that fall in range
125105             var sorted = errors
125106                 .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217
125107                 .sort(function (e1, e2) { return e1.start - e2.start; });
125108             if (!sorted.length) {
125109                 return rangeHasNoErrors;
125110             }
125111             var index = 0;
125112             return function (r) {
125113                 // in current implementation sequence of arguments [r1, r2...] is monotonically increasing.
125114                 // 'index' tracks the index of the most recent error that was checked.
125115                 while (true) {
125116                     if (index >= sorted.length) {
125117                         // all errors in the range were already checked -> no error in specified range
125118                         return false;
125119                     }
125120                     var error = sorted[index];
125121                     if (r.end <= error.start) {
125122                         // specified range ends before the error referred by 'index' - no error in range
125123                         return false;
125124                     }
125125                     if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {
125126                         // specified range overlaps with error range
125127                         return true;
125128                     }
125129                     index++;
125130                 }
125131             };
125132             function rangeHasNoErrors() {
125133                 return false;
125134             }
125135         }
125136         /**
125137          * Start of the original range might fall inside the comment - scanner will not yield appropriate results
125138          * This function will look for token that is located before the start of target range
125139          * and return its end as start position for the scanner.
125140          */
125141         function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
125142             var start = enclosingNode.getStart(sourceFile);
125143             if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
125144                 return start;
125145             }
125146             var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile);
125147             if (!precedingToken) {
125148                 // no preceding token found - start from the beginning of enclosing node
125149                 return enclosingNode.pos;
125150             }
125151             // preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal)
125152             // start from the beginning of enclosingNode to handle the entire 'originalRange'
125153             if (precedingToken.end >= originalRange.pos) {
125154                 return enclosingNode.pos;
125155             }
125156             return precedingToken.end;
125157         }
125158         /*
125159          * For cases like
125160          * if (a ||
125161          *     b ||$
125162          *     c) {...}
125163          * If we hit Enter at $ we want line '    b ||' to be indented.
125164          * Formatting will be applied to the last two lines.
125165          * Node that fully encloses these lines is binary expression 'a ||...'.
125166          * Initial indentation for this node will be 0.
125167          * Binary expressions don't introduce new indentation scopes, however it is possible
125168          * that some parent node on the same line does - like if statement in this case.
125169          * Note that we are considering parents only from the same line with initial node -
125170          * if parent is on the different line - its delta was already contributed
125171          * to the initial indentation.
125172          */
125173         function getOwnOrInheritedDelta(n, options, sourceFile) {
125174             var previousLine = -1 /* Unknown */;
125175             var child;
125176             while (n) {
125177                 var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
125178                 if (previousLine !== -1 /* Unknown */ && line !== previousLine) {
125179                     break;
125180                 }
125181                 if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
125182                     return options.indentSize;
125183                 }
125184                 previousLine = line;
125185                 child = n;
125186                 n = n.parent;
125187             }
125188             return 0;
125189         }
125190         function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) {
125191             var range = { pos: 0, end: sourceFileLike.text.length };
125192             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
125193             sourceFileLike); });
125194         }
125195         formatting.formatNodeGivenIndentation = formatNodeGivenIndentation;
125196         function formatNodeLines(node, sourceFile, formatContext, requestKind) {
125197             if (!node) {
125198                 return [];
125199             }
125200             var span = {
125201                 pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
125202                 end: node.end
125203             };
125204             return formatSpan(span, sourceFile, formatContext, requestKind);
125205         }
125206         function formatSpan(originalRange, sourceFile, formatContext, requestKind) {
125207             // find the smallest node that fully wraps the range and compute the initial indentation for the node
125208             var enclosingNode = findEnclosingNode(originalRange, sourceFile);
125209             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); });
125210         }
125211         function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) {
125212             var options = _a.options, getRules = _a.getRules, host = _a.host;
125213             // formatting context is used by rules provider
125214             var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options);
125215             var previousRange;
125216             var previousParent;
125217             var previousRangeStartLine;
125218             var lastIndentedLine;
125219             var indentationOnLastIndentedLine = -1 /* Unknown */;
125220             var edits = [];
125221             formattingScanner.advance();
125222             if (formattingScanner.isOnToken()) {
125223                 var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
125224                 var undecoratedStartLine = startLine;
125225                 if (enclosingNode.decorators) {
125226                     undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
125227                 }
125228                 processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
125229             }
125230             if (!formattingScanner.isOnToken()) {
125231                 var leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
125232                 if (leadingTrivia) {
125233                     indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); });
125234                     if (options.trimTrailingWhitespace !== false) {
125235                         trimTrailingWhitespacesForRemainingRange();
125236                     }
125237                 }
125238             }
125239             return edits;
125240             // local functions
125241             /** Tries to compute the indentation for a list element.
125242              * If list element is not in range then
125243              * function will pick its actual indentation
125244              * so it can be pushed downstream as inherited indentation.
125245              * If list element is in the range - its indentation will be equal
125246              * to inherited indentation from its predecessors.
125247              */
125248             function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
125249                 if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) ||
125250                     ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
125251                     if (inheritedIndentation !== -1 /* Unknown */) {
125252                         return inheritedIndentation;
125253                     }
125254                 }
125255                 else {
125256                     var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
125257                     var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile);
125258                     var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
125259                     if (startLine !== parentStartLine || startPos === column) {
125260                         // Use the base indent size if it is greater than
125261                         // the indentation of the inherited predecessor.
125262                         var baseIndentSize = formatting.SmartIndenter.getBaseIndentation(options);
125263                         return baseIndentSize > column ? baseIndentSize : column;
125264                     }
125265                 }
125266                 return -1 /* Unknown */;
125267             }
125268             function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) {
125269                 var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
125270                 if (effectiveParentStartLine === startLine) {
125271                     // if node is located on the same line with the parent
125272                     // - inherit indentation from the parent
125273                     // - push children if either parent of node itself has non-zero delta
125274                     return {
125275                         indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
125276                         delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta)
125277                     };
125278                 }
125279                 else if (inheritedIndentation === -1 /* Unknown */) {
125280                     if (node.kind === 20 /* OpenParenToken */ && startLine === lastIndentedLine) {
125281                         // the is used for chaining methods formatting
125282                         // - we need to get the indentation on last line and the delta of parent
125283                         return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
125284                     }
125285                     else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
125286                         return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
125287                     }
125288                     else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) {
125289                         return { indentation: parentDynamicIndentation.getIndentation(), delta: delta };
125290                     }
125291                     else {
125292                         return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta };
125293                     }
125294                 }
125295                 else {
125296                     return { indentation: inheritedIndentation, delta: delta };
125297                 }
125298             }
125299             function getFirstNonDecoratorTokenOfNode(node) {
125300                 if (node.modifiers && node.modifiers.length) {
125301                     return node.modifiers[0].kind;
125302                 }
125303                 switch (node.kind) {
125304                     case 245 /* ClassDeclaration */: return 80 /* ClassKeyword */;
125305                     case 246 /* InterfaceDeclaration */: return 114 /* InterfaceKeyword */;
125306                     case 244 /* FunctionDeclaration */: return 94 /* FunctionKeyword */;
125307                     case 248 /* EnumDeclaration */: return 248 /* EnumDeclaration */;
125308                     case 163 /* GetAccessor */: return 131 /* GetKeyword */;
125309                     case 164 /* SetAccessor */: return 142 /* SetKeyword */;
125310                     case 161 /* MethodDeclaration */:
125311                         if (node.asteriskToken) {
125312                             return 41 /* AsteriskToken */;
125313                         }
125314                     // falls through
125315                     case 159 /* PropertyDeclaration */:
125316                     case 156 /* Parameter */:
125317                         var name = ts.getNameOfDeclaration(node);
125318                         if (name) {
125319                             return name.kind;
125320                         }
125321                 }
125322             }
125323             function getDynamicIndentation(node, nodeStartLine, indentation, delta) {
125324                 return {
125325                     getIndentationForComment: function (kind, tokenIndentation, container) {
125326                         switch (kind) {
125327                             // preceding comment to the token that closes the indentation scope inherits the indentation from the scope
125328                             // ..  {
125329                             //     // comment
125330                             // }
125331                             case 19 /* CloseBraceToken */:
125332                             case 23 /* CloseBracketToken */:
125333                             case 21 /* CloseParenToken */:
125334                                 return indentation + getDelta(container);
125335                         }
125336                         return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation;
125337                     },
125338                     // if list end token is LessThanToken '>' then its delta should be explicitly suppressed
125339                     // so that LessThanToken as a binary operator can still be indented.
125340                     // foo.then
125341                     //     <
125342                     //         number,
125343                     //         string,
125344                     //     >();
125345                     // vs
125346                     // var a = xValue
125347                     //     > yValue;
125348                     getIndentationForToken: function (line, kind, container, suppressDelta) {
125349                         return !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation;
125350                     },
125351                     getIndentation: function () { return indentation; },
125352                     getDelta: getDelta,
125353                     recomputeIndentation: function (lineAdded, parent) {
125354                         if (formatting.SmartIndenter.shouldIndentChildNode(options, parent, node, sourceFile)) {
125355                             indentation += lineAdded ? options.indentSize : -options.indentSize;
125356                             delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0;
125357                         }
125358                     }
125359                 };
125360                 function shouldAddDelta(line, kind, container) {
125361                     switch (kind) {
125362                         // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
125363                         case 18 /* OpenBraceToken */:
125364                         case 19 /* CloseBraceToken */:
125365                         case 21 /* CloseParenToken */:
125366                         case 87 /* ElseKeyword */:
125367                         case 111 /* WhileKeyword */:
125368                         case 59 /* AtToken */:
125369                             return false;
125370                         case 43 /* SlashToken */:
125371                         case 31 /* GreaterThanToken */:
125372                             switch (container.kind) {
125373                                 case 268 /* JsxOpeningElement */:
125374                                 case 269 /* JsxClosingElement */:
125375                                 case 267 /* JsxSelfClosingElement */:
125376                                     return false;
125377                             }
125378                             break;
125379                         case 22 /* OpenBracketToken */:
125380                         case 23 /* CloseBracketToken */:
125381                             if (container.kind !== 186 /* MappedType */) {
125382                                 return false;
125383                             }
125384                             break;
125385                     }
125386                     // if token line equals to the line of containing node (this is a first token in the node) - use node indentation
125387                     return nodeStartLine !== line
125388                         // if this token is the first token following the list of decorators, we do not need to indent
125389                         && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node));
125390                 }
125391                 function getDelta(child) {
125392                     // Delta value should be zero when the node explicitly prevents indentation of the child node
125393                     return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0;
125394                 }
125395             }
125396             function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) {
125397                 if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
125398                     return;
125399                 }
125400                 var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
125401                 // a useful observations when tracking context node
125402                 //        /
125403                 //      [a]
125404                 //   /   |   \
125405                 //  [b] [c] [d]
125406                 // node 'a' is a context node for nodes 'b', 'c', 'd'
125407                 // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
125408                 // this rule can be applied recursively to child nodes of 'a'.
125409                 //
125410                 // context node is set to parent node value after processing every child node
125411                 // context node is set to parent of the token after processing every token
125412                 var childContextNode = contextNode;
125413                 // if there are any tokens that logically belong to node and interleave child nodes
125414                 // such tokens will be consumed in processChildNode for the child that follows them
125415                 ts.forEachChild(node, function (child) {
125416                     processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
125417                 }, function (nodes) {
125418                     processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
125419                 });
125420                 // proceed any tokens in the node that are located after child nodes
125421                 while (formattingScanner.isOnToken()) {
125422                     var tokenInfo = formattingScanner.readTokenInfo(node);
125423                     if (tokenInfo.token.end > node.end) {
125424                         break;
125425                     }
125426                     if (node.kind === 11 /* JsxText */) {
125427                         // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here
125428                         formattingScanner.advance();
125429                         continue;
125430                     }
125431                     consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
125432                 }
125433                 if (!node.parent && formattingScanner.isOnEOF()) {
125434                     var token = formattingScanner.readEOFTokenRange();
125435                     if (token.end <= node.end && previousRange) {
125436                         processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, node, previousRange, previousRangeStartLine, previousParent, contextNode, nodeDynamicIndentation);
125437                     }
125438                 }
125439                 function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
125440                     var childStartPos = child.getStart(sourceFile);
125441                     var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
125442                     var undecoratedChildStartLine = childStartLine;
125443                     if (child.decorators) {
125444                         undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
125445                     }
125446                     // if child is a list item - try to get its indentation, only if parent is within the original range.
125447                     var childIndentationAmount = -1 /* Unknown */;
125448                     if (isListItem && ts.rangeContainsRange(originalRange, parent)) {
125449                         childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
125450                         if (childIndentationAmount !== -1 /* Unknown */) {
125451                             inheritedIndentation = childIndentationAmount;
125452                         }
125453                     }
125454                     // child node is outside the target range - do not dive inside
125455                     if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
125456                         if (child.end < originalRange.pos) {
125457                             formattingScanner.skipToEndOf(child);
125458                         }
125459                         return inheritedIndentation;
125460                     }
125461                     if (child.getFullWidth() === 0) {
125462                         return inheritedIndentation;
125463                     }
125464                     while (formattingScanner.isOnToken()) {
125465                         // proceed any parent tokens that are located prior to child.getStart()
125466                         var tokenInfo = formattingScanner.readTokenInfo(node);
125467                         if (tokenInfo.token.end > childStartPos) {
125468                             // stop when formatting scanner advances past the beginning of the child
125469                             break;
125470                         }
125471                         consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
125472                     }
125473                     if (!formattingScanner.isOnToken()) {
125474                         return inheritedIndentation;
125475                     }
125476                     // JSX text shouldn't affect indenting
125477                     if (ts.isToken(child) && child.kind !== 11 /* JsxText */) {
125478                         // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
125479                         var tokenInfo = formattingScanner.readTokenInfo(child);
125480                         ts.Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
125481                         consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
125482                         return inheritedIndentation;
125483                     }
125484                     var effectiveParentStartLine = child.kind === 157 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
125485                     var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
125486                     processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
125487                     if (child.kind === 11 /* JsxText */) {
125488                         var range = { pos: child.getStart(), end: child.getEnd() };
125489                         if (range.pos !== range.end) { // don't indent zero-width jsx text
125490                             var siblings = parent.getChildren(sourceFile);
125491                             var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; });
125492                             var previousNode = siblings[currentIndex - 1];
125493                             if (previousNode) {
125494                                 // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on
125495                                 if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) {
125496                                     // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on
125497                                     var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line;
125498                                     indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true);
125499                                 }
125500                             }
125501                         }
125502                     }
125503                     childContextNode = node;
125504                     if (isFirstListItem && parent.kind === 192 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
125505                         inheritedIndentation = childIndentation.indentation;
125506                     }
125507                     return inheritedIndentation;
125508                 }
125509                 function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) {
125510                     ts.Debug.assert(ts.isNodeArray(nodes));
125511                     var listStartToken = getOpenTokenForList(parent, nodes);
125512                     var listDynamicIndentation = parentDynamicIndentation;
125513                     var startLine = parentStartLine;
125514                     if (listStartToken !== 0 /* Unknown */) {
125515                         // introduce a new indentation scope for lists (including list start and end tokens)
125516                         while (formattingScanner.isOnToken()) {
125517                             var tokenInfo = formattingScanner.readTokenInfo(parent);
125518                             if (tokenInfo.token.end > nodes.pos) {
125519                                 // stop when formatting scanner moves past the beginning of node list
125520                                 break;
125521                             }
125522                             else if (tokenInfo.token.kind === listStartToken) {
125523                                 // consume list start token
125524                                 startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
125525                                 consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
125526                                 var indentationOnListStartToken = void 0;
125527                                 if (indentationOnLastIndentedLine !== -1 /* Unknown */) {
125528                                     // scanner just processed list start token so consider last indentation as list indentation
125529                                     // function foo(): { // last indentation was 0, list item will be indented based on this value
125530                                     //   foo: number;
125531                                     // }: {};
125532                                     indentationOnListStartToken = indentationOnLastIndentedLine;
125533                                 }
125534                                 else {
125535                                     var startLinePosition = ts.getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile);
125536                                     indentationOnListStartToken = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options);
125537                                 }
125538                                 listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize); // TODO: GH#18217
125539                             }
125540                             else {
125541                                 // consume any tokens that precede the list as child elements of 'node' using its indentation scope
125542                                 consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
125543                             }
125544                         }
125545                     }
125546                     var inheritedIndentation = -1 /* Unknown */;
125547                     for (var i = 0; i < nodes.length; i++) {
125548                         var child = nodes[i];
125549                         inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0);
125550                     }
125551                     var listEndToken = getCloseTokenForOpenToken(listStartToken);
125552                     if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) {
125553                         var tokenInfo = formattingScanner.readTokenInfo(parent);
125554                         if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) {
125555                             var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
125556                             if (startLine !== commaTokenLine) {
125557                                 formattingScanner.advance();
125558                                 tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined;
125559                             }
125560                         }
125561                         // consume the list end token only if it is still belong to the parent
125562                         // there might be the case when current token matches end token but does not considered as one
125563                         // function (x: function) <--
125564                         // without this check close paren will be interpreted as list end token for function expression which is wrong
125565                         if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) {
125566                             // consume list end token
125567                             consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true);
125568                         }
125569                     }
125570                 }
125571                 function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container, isListEndToken) {
125572                     ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token));
125573                     var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
125574                     var indentToken = false;
125575                     if (currentTokenInfo.leadingTrivia) {
125576                         processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation);
125577                     }
125578                     var lineAction = 0 /* None */;
125579                     var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token);
125580                     var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
125581                     if (isTokenInRange) {
125582                         var rangeHasError = rangeContainsError(currentTokenInfo.token);
125583                         // save previousRange since processRange will overwrite this value with current one
125584                         var savePreviousRange = previousRange;
125585                         lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation);
125586                         // do not indent comments\token if token range overlaps with some error
125587                         if (!rangeHasError) {
125588                             if (lineAction === 0 /* None */) {
125589                                 // indent token only if end line of previous range does not match start line of the token
125590                                 var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
125591                                 indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
125592                             }
125593                             else {
125594                                 indentToken = lineAction === 1 /* LineAdded */;
125595                             }
125596                         }
125597                     }
125598                     if (currentTokenInfo.trailingTrivia) {
125599                         processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation);
125600                     }
125601                     if (indentToken) {
125602                         var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
125603                             dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) :
125604                             -1 /* Unknown */;
125605                         var indentNextTokenOrTrivia = true;
125606                         if (currentTokenInfo.leadingTrivia) {
125607                             var commentIndentation_1 = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
125608                             indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation_1, indentNextTokenOrTrivia, function (item) { return insertIndentation(item.pos, commentIndentation_1, /*lineAdded*/ false); });
125609                         }
125610                         // indent token only if is it is in target range and does not overlap with any error ranges
125611                         if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) {
125612                             insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */);
125613                             lastIndentedLine = tokenStart.line;
125614                             indentationOnLastIndentedLine = tokenIndentation;
125615                         }
125616                     }
125617                     formattingScanner.advance();
125618                     childContextNode = parent;
125619                 }
125620             }
125621             function indentTriviaItems(trivia, commentIndentation, indentNextTokenOrTrivia, indentSingleLine) {
125622                 for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) {
125623                     var triviaItem = trivia_1[_i];
125624                     var triviaInRange = ts.rangeContainsRange(originalRange, triviaItem);
125625                     switch (triviaItem.kind) {
125626                         case 3 /* MultiLineCommentTrivia */:
125627                             if (triviaInRange) {
125628                                 indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
125629                             }
125630                             indentNextTokenOrTrivia = false;
125631                             break;
125632                         case 2 /* SingleLineCommentTrivia */:
125633                             if (indentNextTokenOrTrivia && triviaInRange) {
125634                                 indentSingleLine(triviaItem);
125635                             }
125636                             indentNextTokenOrTrivia = false;
125637                             break;
125638                         case 4 /* NewLineTrivia */:
125639                             indentNextTokenOrTrivia = true;
125640                             break;
125641                     }
125642                 }
125643                 return indentNextTokenOrTrivia;
125644             }
125645             function processTrivia(trivia, parent, contextNode, dynamicIndentation) {
125646                 for (var _i = 0, trivia_2 = trivia; _i < trivia_2.length; _i++) {
125647                     var triviaItem = trivia_2[_i];
125648                     if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) {
125649                         var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
125650                         processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation);
125651                     }
125652                 }
125653             }
125654             function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) {
125655                 var rangeHasError = rangeContainsError(range);
125656                 var lineAction = 0 /* None */;
125657                 if (!rangeHasError) {
125658                     if (!previousRange) {
125659                         // trim whitespaces starting from the beginning of the span up to the current line
125660                         var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
125661                         trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
125662                     }
125663                     else {
125664                         lineAction =
125665                             processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
125666                     }
125667                 }
125668                 previousRange = range;
125669                 previousParent = parent;
125670                 previousRangeStartLine = rangeStart.line;
125671                 return lineAction;
125672             }
125673             function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) {
125674                 formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode);
125675                 var rules = getRules(formattingContext);
125676                 var trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false;
125677                 var lineAction = 0 /* None */;
125678                 if (rules) {
125679                     // Apply rules in reverse order so that higher priority rules (which are first in the array)
125680                     // win in a conflict with lower priority rules.
125681                     ts.forEachRight(rules, function (rule) {
125682                         lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine);
125683                         switch (lineAction) {
125684                             case 2 /* LineRemoved */:
125685                                 // Handle the case where the next line is moved to be the end of this line.
125686                                 // In this case we don't indent the next line in the next pass.
125687                                 if (currentParent.getStart(sourceFile) === currentItem.pos) {
125688                                     dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode);
125689                                 }
125690                                 break;
125691                             case 1 /* LineAdded */:
125692                                 // Handle the case where token2 is moved to the new line.
125693                                 // In this case we indent token2 in the next pass but we set
125694                                 // sameLineIndent flag to notify the indenter that the indentation is within the line.
125695                                 if (currentParent.getStart(sourceFile) === currentItem.pos) {
125696                                     dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode);
125697                                 }
125698                                 break;
125699                             default:
125700                                 ts.Debug.assert(lineAction === 0 /* None */);
125701                         }
125702                         // 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
125703                         trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */;
125704                     });
125705                 }
125706                 else {
125707                     trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.kind !== 1 /* EndOfFileToken */;
125708                 }
125709                 if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) {
125710                     // 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
125711                     trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem);
125712                 }
125713                 return lineAction;
125714             }
125715             function insertIndentation(pos, indentation, lineAdded) {
125716                 var indentationString = getIndentationString(indentation, options);
125717                 if (lineAdded) {
125718                     // new line is added before the token by the formatting rules
125719                     // insert indentation string at the very beginning of the token
125720                     recordReplace(pos, 0, indentationString);
125721                 }
125722                 else {
125723                     var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
125724                     var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile);
125725                     if (indentation !== characterToColumn(startLinePosition, tokenStart.character) || indentationIsDifferent(indentationString, startLinePosition)) {
125726                         recordReplace(startLinePosition, tokenStart.character, indentationString);
125727                     }
125728                 }
125729             }
125730             function characterToColumn(startLinePosition, characterInLine) {
125731                 var column = 0;
125732                 for (var i = 0; i < characterInLine; i++) {
125733                     if (sourceFile.text.charCodeAt(startLinePosition + i) === 9 /* tab */) {
125734                         column += options.tabSize - column % options.tabSize;
125735                     }
125736                     else {
125737                         column++;
125738                     }
125739                 }
125740                 return column;
125741             }
125742             function indentationIsDifferent(indentationString, startLinePosition) {
125743                 return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length);
125744             }
125745             function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) {
125746                 if (indentFinalLine === void 0) { indentFinalLine = true; }
125747                 // split comment in lines
125748                 var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
125749                 var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
125750                 if (startLine === endLine) {
125751                     if (!firstLineIsIndented) {
125752                         // treat as single line comment
125753                         insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false);
125754                     }
125755                     return;
125756                 }
125757                 var parts = [];
125758                 var startPos = commentRange.pos;
125759                 for (var line = startLine; line < endLine; line++) {
125760                     var endOfLine = ts.getEndLinePosition(line, sourceFile);
125761                     parts.push({ pos: startPos, end: endOfLine });
125762                     startPos = ts.getStartPositionOfLine(line + 1, sourceFile);
125763                 }
125764                 if (indentFinalLine) {
125765                     parts.push({ pos: startPos, end: commentRange.end });
125766                 }
125767                 if (parts.length === 0)
125768                     return;
125769                 var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile);
125770                 var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
125771                 if (indentation === nonWhitespaceColumnInFirstPart.column && !jsxTextStyleIndent) {
125772                     return;
125773                 }
125774                 var startIndex = 0;
125775                 if (firstLineIsIndented) {
125776                     startIndex = 1;
125777                     startLine++;
125778                 }
125779                 // shift all parts on the delta size
125780                 var delta = indentation - nonWhitespaceColumnInFirstPart.column;
125781                 for (var i = startIndex; i < parts.length; i++, startLine++) {
125782                     var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile);
125783                     var nonWhitespaceCharacterAndColumn = i === 0
125784                         ? nonWhitespaceColumnInFirstPart
125785                         : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
125786                     if (jsxTextStyleIndent) {
125787                         // skip adding indentation to blank lines
125788                         if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile))))
125789                             continue;
125790                         // reset delta on every line
125791                         delta = indentation - nonWhitespaceCharacterAndColumn.column;
125792                     }
125793                     var newIndentation = nonWhitespaceCharacterAndColumn.column + delta;
125794                     if (newIndentation > 0) {
125795                         var indentationString = getIndentationString(newIndentation, options);
125796                         recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString);
125797                     }
125798                     else {
125799                         recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character);
125800                     }
125801                 }
125802             }
125803             function trimTrailingWhitespacesForLines(line1, line2, range) {
125804                 for (var line = line1; line < line2; line++) {
125805                     var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile);
125806                     var lineEndPosition = ts.getEndLinePosition(line, sourceFile);
125807                     // do not trim whitespaces in comments or template expression
125808                     if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
125809                         continue;
125810                     }
125811                     var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
125812                     if (whitespaceStart !== -1) {
125813                         ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(whitespaceStart - 1)));
125814                         recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
125815                     }
125816                 }
125817             }
125818             /**
125819              * @param start The position of the first character in range
125820              * @param end The position of the last character in range
125821              */
125822             function getTrailingWhitespaceStartPosition(start, end) {
125823                 var pos = end;
125824                 while (pos >= start && ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(pos))) {
125825                     pos--;
125826                 }
125827                 if (pos !== end) {
125828                     return pos + 1;
125829                 }
125830                 return -1;
125831             }
125832             /**
125833              * Trimming will be done for lines after the previous range
125834              */
125835             function trimTrailingWhitespacesForRemainingRange() {
125836                 var startPosition = previousRange ? previousRange.end : originalRange.pos;
125837                 var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
125838                 var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
125839                 trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange);
125840             }
125841             function recordDelete(start, len) {
125842                 if (len) {
125843                     edits.push(ts.createTextChangeFromStartLength(start, len, ""));
125844                 }
125845             }
125846             function recordReplace(start, len, newText) {
125847                 if (len || newText) {
125848                     edits.push(ts.createTextChangeFromStartLength(start, len, newText));
125849                 }
125850             }
125851             function recordInsert(start, text) {
125852                 if (text) {
125853                     edits.push(ts.createTextChangeFromStartLength(start, 0, text));
125854                 }
125855             }
125856             function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) {
125857                 var onLaterLine = currentStartLine !== previousStartLine;
125858                 switch (rule.action) {
125859                     case 1 /* StopProcessingSpaceActions */:
125860                         // no action required
125861                         return 0 /* None */;
125862                     case 16 /* DeleteSpace */:
125863                         if (previousRange.end !== currentRange.pos) {
125864                             // delete characters starting from t1.end up to t2.pos exclusive
125865                             recordDelete(previousRange.end, currentRange.pos - previousRange.end);
125866                             return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
125867                         }
125868                         break;
125869                     case 32 /* DeleteToken */:
125870                         recordDelete(previousRange.pos, previousRange.end - previousRange.pos);
125871                         break;
125872                     case 8 /* InsertNewLine */:
125873                         // exit early if we on different lines and rule cannot change number of newlines
125874                         // if line1 and line2 are on subsequent lines then no edits are required - ok to exit
125875                         // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines
125876                         if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
125877                             return 0 /* None */;
125878                         }
125879                         // edit should not be applied if we have one line feed between elements
125880                         var lineDelta = currentStartLine - previousStartLine;
125881                         if (lineDelta !== 1) {
125882                             recordReplace(previousRange.end, currentRange.pos - previousRange.end, ts.getNewLineOrDefaultFromHost(host, options));
125883                             return onLaterLine ? 0 /* None */ : 1 /* LineAdded */;
125884                         }
125885                         break;
125886                     case 4 /* InsertSpace */:
125887                         // exit early if we on different lines and rule cannot change number of newlines
125888                         if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) {
125889                             return 0 /* None */;
125890                         }
125891                         var posDelta = currentRange.pos - previousRange.end;
125892                         if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) {
125893                             recordReplace(previousRange.end, currentRange.pos - previousRange.end, " ");
125894                             return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */;
125895                         }
125896                         break;
125897                     case 64 /* InsertTrailingSemicolon */:
125898                         recordInsert(previousRange.end, ";");
125899                 }
125900                 return 0 /* None */;
125901             }
125902         }
125903         var LineAction;
125904         (function (LineAction) {
125905             LineAction[LineAction["None"] = 0] = "None";
125906             LineAction[LineAction["LineAdded"] = 1] = "LineAdded";
125907             LineAction[LineAction["LineRemoved"] = 2] = "LineRemoved";
125908         })(LineAction || (LineAction = {}));
125909         /**
125910          * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`.
125911          */
125912         function getRangeOfEnclosingComment(sourceFile, position, precedingToken, tokenAtPosition) {
125913             if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); }
125914             var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc);
125915             if (jsdoc)
125916                 tokenAtPosition = jsdoc.parent;
125917             var tokenStart = tokenAtPosition.getStart(sourceFile);
125918             if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
125919                 return undefined;
125920             }
125921             // eslint-disable-next-line no-null/no-null
125922             precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken;
125923             // Between two consecutive tokens, all comments are either trailing on the former
125924             // or leading on the latter (and none are in both lists).
125925             var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end);
125926             var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
125927             var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
125928             return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) ||
125929                 // The end marker of a single-line comment does not include the newline character.
125930                 // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
125931                 //
125932                 //    // asdf   ^\n
125933                 //
125934                 // But for closed multi-line comments, we don't want to be inside the comment in the following case:
125935                 //
125936                 //    /* asdf */^
125937                 //
125938                 // However, unterminated multi-line comments *do* contain their end.
125939                 //
125940                 // Internally, we represent the end of the comment at the newline and closing '/', respectively.
125941                 //
125942                 position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); });
125943         }
125944         formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment;
125945         function getOpenTokenForList(node, list) {
125946             switch (node.kind) {
125947                 case 162 /* Constructor */:
125948                 case 244 /* FunctionDeclaration */:
125949                 case 201 /* FunctionExpression */:
125950                 case 161 /* MethodDeclaration */:
125951                 case 160 /* MethodSignature */:
125952                 case 202 /* ArrowFunction */:
125953                     if (node.typeParameters === list) {
125954                         return 29 /* LessThanToken */;
125955                     }
125956                     else if (node.parameters === list) {
125957                         return 20 /* OpenParenToken */;
125958                     }
125959                     break;
125960                 case 196 /* CallExpression */:
125961                 case 197 /* NewExpression */:
125962                     if (node.typeArguments === list) {
125963                         return 29 /* LessThanToken */;
125964                     }
125965                     else if (node.arguments === list) {
125966                         return 20 /* OpenParenToken */;
125967                     }
125968                     break;
125969                 case 169 /* TypeReference */:
125970                     if (node.typeArguments === list) {
125971                         return 29 /* LessThanToken */;
125972                     }
125973                     break;
125974                 case 173 /* TypeLiteral */:
125975                     return 18 /* OpenBraceToken */;
125976             }
125977             return 0 /* Unknown */;
125978         }
125979         function getCloseTokenForOpenToken(kind) {
125980             switch (kind) {
125981                 case 20 /* OpenParenToken */:
125982                     return 21 /* CloseParenToken */;
125983                 case 29 /* LessThanToken */:
125984                     return 31 /* GreaterThanToken */;
125985                 case 18 /* OpenBraceToken */:
125986                     return 19 /* CloseBraceToken */;
125987             }
125988             return 0 /* Unknown */;
125989         }
125990         var internedSizes;
125991         var internedTabsIndentation;
125992         var internedSpacesIndentation;
125993         function getIndentationString(indentation, options) {
125994             // reset interned strings if FormatCodeOptions were changed
125995             var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize);
125996             if (resetInternedStrings) {
125997                 internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize };
125998                 internedTabsIndentation = internedSpacesIndentation = undefined;
125999             }
126000             if (!options.convertTabsToSpaces) {
126001                 var tabs = Math.floor(indentation / options.tabSize);
126002                 var spaces = indentation - tabs * options.tabSize;
126003                 var tabString = void 0;
126004                 if (!internedTabsIndentation) {
126005                     internedTabsIndentation = [];
126006                 }
126007                 if (internedTabsIndentation[tabs] === undefined) {
126008                     internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs);
126009                 }
126010                 else {
126011                     tabString = internedTabsIndentation[tabs];
126012                 }
126013                 return spaces ? tabString + ts.repeatString(" ", spaces) : tabString;
126014             }
126015             else {
126016                 var spacesString = void 0;
126017                 var quotient = Math.floor(indentation / options.indentSize);
126018                 var remainder = indentation % options.indentSize;
126019                 if (!internedSpacesIndentation) {
126020                     internedSpacesIndentation = [];
126021                 }
126022                 if (internedSpacesIndentation[quotient] === undefined) {
126023                     spacesString = ts.repeatString(" ", options.indentSize * quotient);
126024                     internedSpacesIndentation[quotient] = spacesString;
126025                 }
126026                 else {
126027                     spacesString = internedSpacesIndentation[quotient];
126028                 }
126029                 return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString;
126030             }
126031         }
126032         formatting.getIndentationString = getIndentationString;
126033     })(formatting = ts.formatting || (ts.formatting = {}));
126034 })(ts || (ts = {}));
126035 /* @internal */
126036 var ts;
126037 (function (ts) {
126038     var formatting;
126039     (function (formatting) {
126040         var SmartIndenter;
126041         (function (SmartIndenter) {
126042             var Value;
126043             (function (Value) {
126044                 Value[Value["Unknown"] = -1] = "Unknown";
126045             })(Value || (Value = {}));
126046             /**
126047              * @param assumeNewLineBeforeCloseBrace
126048              * `false` when called on text from a real source file.
126049              * `true` when we need to assume `position` is on a newline.
126050              *
126051              * This is useful for codefixes. Consider
126052              * ```
126053              * function f() {
126054              * |}
126055              * ```
126056              * with `position` at `|`.
126057              *
126058              * When inserting some text after an open brace, we would like to get indentation as if a newline was already there.
126059              * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior.
126060              */
126061             function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) {
126062                 if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; }
126063                 if (position > sourceFile.text.length) {
126064                     return getBaseIndentation(options); // past EOF
126065                 }
126066                 // no indentation when the indent style is set to none,
126067                 // so we can return fast
126068                 if (options.indentStyle === ts.IndentStyle.None) {
126069                     return 0;
126070                 }
126071                 var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true);
126072                 // eslint-disable-next-line no-null/no-null
126073                 var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null);
126074                 if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
126075                     return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
126076                 }
126077                 if (!precedingToken) {
126078                     return getBaseIndentation(options);
126079                 }
126080                 // no indentation in string \regex\template literals
126081                 var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
126082                 if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && position < precedingToken.end) {
126083                     return 0;
126084                 }
126085                 var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
126086                 // indentation is first non-whitespace character in a previous line
126087                 // for block indentation, we should look for a line which contains something that's not
126088                 // whitespace.
126089                 if (options.indentStyle === ts.IndentStyle.Block) {
126090                     return getBlockIndent(sourceFile, position, options);
126091                 }
126092                 if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 209 /* BinaryExpression */) {
126093                     // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
126094                     var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
126095                     if (actualIndentation !== -1 /* Unknown */) {
126096                         return actualIndentation;
126097                     }
126098                 }
126099                 var containerList = getListByPosition(position, precedingToken.parent, sourceFile);
126100                 // use list position if the preceding token is before any list items
126101                 if (containerList && !ts.rangeContainsRange(containerList, precedingToken)) {
126102                     return getActualIndentationForListStartLine(containerList, sourceFile, options) + options.indentSize; // TODO: GH#18217
126103                 }
126104                 return getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options);
126105             }
126106             SmartIndenter.getIndentation = getIndentation;
126107             function getCommentIndent(sourceFile, position, options, enclosingCommentRange) {
126108                 var previousLine = ts.getLineAndCharacterOfPosition(sourceFile, position).line - 1;
126109                 var commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, enclosingCommentRange.pos).line;
126110                 ts.Debug.assert(commentStartLine >= 0);
126111                 if (previousLine <= commentStartLine) {
126112                     return findFirstNonWhitespaceColumn(ts.getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options);
126113                 }
126114                 var startPositionOfLine = ts.getStartPositionOfLine(previousLine, sourceFile);
126115                 var _a = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options), column = _a.column, character = _a.character;
126116                 if (column === 0) {
126117                     return column;
126118                 }
126119                 var firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character);
126120                 return firstNonWhitespaceCharacterCode === 42 /* asterisk */ ? column - 1 : column;
126121             }
126122             function getBlockIndent(sourceFile, position, options) {
126123                 // move backwards until we find a line with a non-whitespace character,
126124                 // then find the first non-whitespace character for that line.
126125                 var current = position;
126126                 while (current > 0) {
126127                     var char = sourceFile.text.charCodeAt(current);
126128                     if (!ts.isWhiteSpaceLike(char)) {
126129                         break;
126130                     }
126131                     current--;
126132                 }
126133                 var lineStart = ts.getLineStartPositionForPosition(current, sourceFile);
126134                 return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
126135             }
126136             function getSmartIndent(sourceFile, position, precedingToken, lineAtPosition, assumeNewLineBeforeCloseBrace, options) {
126137                 // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken'
126138                 // if such node is found - compute initial indentation for 'position' inside this node
126139                 var previous;
126140                 var current = precedingToken;
126141                 while (current) {
126142                     if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) {
126143                         var currentStart = getStartLineAndCharacterForNode(current, sourceFile);
126144                         var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
126145                         var indentationDelta = nextTokenKind !== 0 /* Unknown */
126146                             // handle cases when codefix is about to be inserted before the close brace
126147                             ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0
126148                             : lineAtPosition !== currentStart.line ? options.indentSize : 0;
126149                         return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217
126150                     }
126151                     // check if current node is a list item - if yes, take indentation from it
126152                     // do not consider parent-child line sharing yet:
126153                     // function foo(a
126154                     //    | preceding node 'a' does share line with its parent but indentation is expected
126155                     var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ true);
126156                     if (actualIndentation !== -1 /* Unknown */) {
126157                         return actualIndentation;
126158                     }
126159                     previous = current;
126160                     current = current.parent;
126161                 }
126162                 // no parent was found - return the base indentation of the SourceFile
126163                 return getBaseIndentation(options);
126164             }
126165             function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) {
126166                 var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
126167                 return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options);
126168             }
126169             SmartIndenter.getIndentationForNode = getIndentationForNode;
126170             function getBaseIndentation(options) {
126171                 return options.baseIndentSize || 0;
126172             }
126173             SmartIndenter.getBaseIndentation = getBaseIndentation;
126174             function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) {
126175                 var parent = current.parent;
126176                 // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if
126177                 // * parent and child nodes start on the same line, or
126178                 // * parent is an IfStatement and child starts on the same line as an 'else clause'.
126179                 while (parent) {
126180                     var useActualIndentation = true;
126181                     if (ignoreActualIndentationRange) {
126182                         var start = current.getStart(sourceFile);
126183                         useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end;
126184                     }
126185                     var containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile);
126186                     var parentAndChildShareLine = containingListOrParentStart.line === currentStart.line ||
126187                         childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile);
126188                     if (useActualIndentation) {
126189                         // check if current node is a list item - if yes, take indentation from it
126190                         var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine);
126191                         if (actualIndentation !== -1 /* Unknown */) {
126192                             return actualIndentation + indentationDelta;
126193                         }
126194                         // try to fetch actual indentation for current node from source text
126195                         actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options);
126196                         if (actualIndentation !== -1 /* Unknown */) {
126197                             return actualIndentation + indentationDelta;
126198                         }
126199                     }
126200                     // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
126201                     if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) {
126202                         indentationDelta += options.indentSize;
126203                     }
126204                     // In our AST, a call argument's `parent` is the call-expression, not the argument list.
126205                     // We would like to increase indentation based on the relationship between an argument and its argument-list,
126206                     // so we spoof the starting position of the (parent) call-expression to match the (non-parent) argument-list.
126207                     // But, the spoofed start-value could then cause a problem when comparing the start position of the call-expression
126208                     // to *its* parent (in the case of an iife, an expression statement), adding an extra level of indentation.
126209                     //
126210                     // Instead, when at an argument, we unspoof the starting position of the enclosing call expression
126211                     // *after* applying indentation for the argument.
126212                     var useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile);
126213                     current = parent;
126214                     parent = current.parent;
126215                     currentStart = useTrueStart ? sourceFile.getLineAndCharacterOfPosition(current.getStart(sourceFile)) : containingListOrParentStart;
126216                 }
126217                 return indentationDelta + getBaseIndentation(options);
126218             }
126219             function getContainingListOrParentStart(parent, child, sourceFile) {
126220                 var containingList = getContainingList(child, sourceFile);
126221                 var startPos = containingList ? containingList.pos : parent.getStart(sourceFile);
126222                 return sourceFile.getLineAndCharacterOfPosition(startPos);
126223             }
126224             /*
126225              * Function returns Value.Unknown if indentation cannot be determined
126226              */
126227             function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) {
126228                 // previous token is comma that separates items in list - find the previous item and try to derive indentation from it
126229                 var commaItemInfo = ts.findListItemInfo(commaToken);
126230                 if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
126231                     return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
126232                 }
126233                 else {
126234                     // handle broken code gracefully
126235                     return -1 /* Unknown */;
126236                 }
126237             }
126238             /*
126239              * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression)
126240              */
126241             function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) {
126242                 // actual indentation is used for statements\declarations if one of cases below is true:
126243                 // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
126244                 // - parent and child are not on the same line
126245                 var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
126246                     (parent.kind === 290 /* SourceFile */ || !parentAndChildShareLine);
126247                 if (!useActualIndentation) {
126248                     return -1 /* Unknown */;
126249                 }
126250                 return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
126251             }
126252             var NextTokenKind;
126253             (function (NextTokenKind) {
126254                 NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown";
126255                 NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace";
126256                 NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
126257             })(NextTokenKind || (NextTokenKind = {}));
126258             function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
126259                 var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
126260                 if (!nextToken) {
126261                     return 0 /* Unknown */;
126262                 }
126263                 if (nextToken.kind === 18 /* OpenBraceToken */) {
126264                     // open braces are always indented at the parent level
126265                     return 1 /* OpenBrace */;
126266                 }
126267                 else if (nextToken.kind === 19 /* CloseBraceToken */) {
126268                     // close braces are indented at the parent level if they are located on the same line with cursor
126269                     // this means that if new line will be added at $ position, this case will be indented
126270                     // class A {
126271                     //    $
126272                     // }
126273                     /// and this one - not
126274                     // class A {
126275                     // $}
126276                     var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
126277                     return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
126278                 }
126279                 return 0 /* Unknown */;
126280             }
126281             function getStartLineAndCharacterForNode(n, sourceFile) {
126282                 return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
126283             }
126284             function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, child, childStartLine, sourceFile) {
126285                 if (!(ts.isCallExpression(parent) && ts.contains(parent.arguments, child))) {
126286                     return false;
126287                 }
126288                 var expressionOfCallExpressionEnd = parent.expression.getEnd();
126289                 var expressionOfCallExpressionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, expressionOfCallExpressionEnd).line;
126290                 return expressionOfCallExpressionEndLine === childStartLine;
126291             }
126292             SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
126293             function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
126294                 if (parent.kind === 227 /* IfStatement */ && parent.elseStatement === child) {
126295                     var elseKeyword = ts.findChildOfKind(parent, 87 /* ElseKeyword */, sourceFile);
126296                     ts.Debug.assert(elseKeyword !== undefined);
126297                     var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
126298                     return elseKeywordStartLine === childStartLine;
126299                 }
126300                 return false;
126301             }
126302             SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
126303             function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) {
126304                 if (ts.isCallOrNewExpression(parent)) {
126305                     if (!parent.arguments)
126306                         return false;
126307                     var currentNode = ts.find(parent.arguments, function (arg) { return arg.pos === child.pos; });
126308                     // If it's not one of the arguments, don't look past this
126309                     if (!currentNode)
126310                         return false;
126311                     var currentIndex = parent.arguments.indexOf(currentNode);
126312                     if (currentIndex === 0)
126313                         return false; // Can't look at previous node if first
126314                     var previousNode = parent.arguments[currentIndex - 1];
126315                     var lineOfPreviousNode = ts.getLineAndCharacterOfPosition(sourceFile, previousNode.getEnd()).line;
126316                     if (childStartLine === lineOfPreviousNode) {
126317                         return true;
126318                     }
126319                 }
126320                 return false;
126321             }
126322             SmartIndenter.argumentStartsOnSameLineAsPreviousArgument = argumentStartsOnSameLineAsPreviousArgument;
126323             function getContainingList(node, sourceFile) {
126324                 return node.parent && getListByRange(node.getStart(sourceFile), node.getEnd(), node.parent, sourceFile);
126325             }
126326             SmartIndenter.getContainingList = getContainingList;
126327             function getListByPosition(pos, node, sourceFile) {
126328                 return node && getListByRange(pos, pos, node, sourceFile);
126329             }
126330             function getListByRange(start, end, node, sourceFile) {
126331                 switch (node.kind) {
126332                     case 169 /* TypeReference */:
126333                         return getList(node.typeArguments);
126334                     case 193 /* ObjectLiteralExpression */:
126335                         return getList(node.properties);
126336                     case 192 /* ArrayLiteralExpression */:
126337                         return getList(node.elements);
126338                     case 173 /* TypeLiteral */:
126339                         return getList(node.members);
126340                     case 244 /* FunctionDeclaration */:
126341                     case 201 /* FunctionExpression */:
126342                     case 202 /* ArrowFunction */:
126343                     case 161 /* MethodDeclaration */:
126344                     case 160 /* MethodSignature */:
126345                     case 165 /* CallSignature */:
126346                     case 162 /* Constructor */:
126347                     case 171 /* ConstructorType */:
126348                     case 166 /* ConstructSignature */:
126349                         return getList(node.typeParameters) || getList(node.parameters);
126350                     case 245 /* ClassDeclaration */:
126351                     case 214 /* ClassExpression */:
126352                     case 246 /* InterfaceDeclaration */:
126353                     case 247 /* TypeAliasDeclaration */:
126354                     case 321 /* JSDocTemplateTag */:
126355                         return getList(node.typeParameters);
126356                     case 197 /* NewExpression */:
126357                     case 196 /* CallExpression */:
126358                         return getList(node.typeArguments) || getList(node.arguments);
126359                     case 243 /* VariableDeclarationList */:
126360                         return getList(node.declarations);
126361                     case 257 /* NamedImports */:
126362                     case 261 /* NamedExports */:
126363                         return getList(node.elements);
126364                     case 189 /* ObjectBindingPattern */:
126365                     case 190 /* ArrayBindingPattern */:
126366                         return getList(node.elements);
126367                 }
126368                 function getList(list) {
126369                     return list && ts.rangeContainsStartEnd(getVisualListRange(node, list, sourceFile), start, end) ? list : undefined;
126370                 }
126371             }
126372             function getVisualListRange(node, list, sourceFile) {
126373                 var children = node.getChildren(sourceFile);
126374                 for (var i = 1; i < children.length - 1; i++) {
126375                     if (children[i].pos === list.pos && children[i].end === list.end) {
126376                         return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) };
126377                     }
126378                 }
126379                 return list;
126380             }
126381             function getActualIndentationForListStartLine(list, sourceFile, options) {
126382                 if (!list) {
126383                     return -1 /* Unknown */;
126384                 }
126385                 return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options);
126386             }
126387             function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) {
126388                 if (node.parent && node.parent.kind === 243 /* VariableDeclarationList */) {
126389                     // VariableDeclarationList has no wrapping tokens
126390                     return -1 /* Unknown */;
126391                 }
126392                 var containingList = getContainingList(node, sourceFile);
126393                 if (containingList) {
126394                     var index = containingList.indexOf(node);
126395                     if (index !== -1) {
126396                         var result = deriveActualIndentationFromList(containingList, index, sourceFile, options);
126397                         if (result !== -1 /* Unknown */) {
126398                             return result;
126399                         }
126400                     }
126401                     return getActualIndentationForListStartLine(containingList, sourceFile, options) + (listIndentsChild ? options.indentSize : 0); // TODO: GH#18217
126402                 }
126403                 return -1 /* Unknown */;
126404             }
126405             function deriveActualIndentationFromList(list, index, sourceFile, options) {
126406                 ts.Debug.assert(index >= 0 && index < list.length);
126407                 var node = list[index];
126408                 // walk toward the start of the list starting from current node and check if the line is the same for all items.
126409                 // 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]
126410                 var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
126411                 for (var i = index - 1; i >= 0; i--) {
126412                     if (list[i].kind === 27 /* CommaToken */) {
126413                         continue;
126414                     }
126415                     // skip list items that ends on the same line with the current list element
126416                     var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
126417                     if (prevEndLine !== lineAndCharacter.line) {
126418                         return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
126419                     }
126420                     lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile);
126421                 }
126422                 return -1 /* Unknown */;
126423             }
126424             function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) {
126425                 var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
126426                 return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
126427             }
126428             /**
126429              * Character is the actual index of the character since the beginning of the line.
126430              * Column - position of the character after expanding tabs to spaces.
126431              * "0\t2$"
126432              * value of 'character' for '$' is 3
126433              * value of 'column' for '$' is 6 (assuming that tab size is 4)
126434              */
126435             function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) {
126436                 var character = 0;
126437                 var column = 0;
126438                 for (var pos = startPos; pos < endPos; pos++) {
126439                     var ch = sourceFile.text.charCodeAt(pos);
126440                     if (!ts.isWhiteSpaceSingleLine(ch)) {
126441                         break;
126442                     }
126443                     if (ch === 9 /* tab */) {
126444                         column += options.tabSize + (column % options.tabSize);
126445                     }
126446                     else {
126447                         column++;
126448                     }
126449                     character++;
126450                 }
126451                 return { column: column, character: character };
126452             }
126453             SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn;
126454             function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) {
126455                 return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column;
126456             }
126457             SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
126458             function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) {
126459                 var childKind = child ? child.kind : 0 /* Unknown */;
126460                 switch (parent.kind) {
126461                     case 226 /* ExpressionStatement */:
126462                     case 245 /* ClassDeclaration */:
126463                     case 214 /* ClassExpression */:
126464                     case 246 /* InterfaceDeclaration */:
126465                     case 248 /* EnumDeclaration */:
126466                     case 247 /* TypeAliasDeclaration */:
126467                     case 192 /* ArrayLiteralExpression */:
126468                     case 223 /* Block */:
126469                     case 250 /* ModuleBlock */:
126470                     case 193 /* ObjectLiteralExpression */:
126471                     case 173 /* TypeLiteral */:
126472                     case 186 /* MappedType */:
126473                     case 175 /* TupleType */:
126474                     case 251 /* CaseBlock */:
126475                     case 278 /* DefaultClause */:
126476                     case 277 /* CaseClause */:
126477                     case 200 /* ParenthesizedExpression */:
126478                     case 194 /* PropertyAccessExpression */:
126479                     case 196 /* CallExpression */:
126480                     case 197 /* NewExpression */:
126481                     case 225 /* VariableStatement */:
126482                     case 259 /* ExportAssignment */:
126483                     case 235 /* ReturnStatement */:
126484                     case 210 /* ConditionalExpression */:
126485                     case 190 /* ArrayBindingPattern */:
126486                     case 189 /* ObjectBindingPattern */:
126487                     case 268 /* JsxOpeningElement */:
126488                     case 271 /* JsxOpeningFragment */:
126489                     case 267 /* JsxSelfClosingElement */:
126490                     case 276 /* JsxExpression */:
126491                     case 160 /* MethodSignature */:
126492                     case 165 /* CallSignature */:
126493                     case 166 /* ConstructSignature */:
126494                     case 156 /* Parameter */:
126495                     case 170 /* FunctionType */:
126496                     case 171 /* ConstructorType */:
126497                     case 182 /* ParenthesizedType */:
126498                     case 198 /* TaggedTemplateExpression */:
126499                     case 206 /* AwaitExpression */:
126500                     case 261 /* NamedExports */:
126501                     case 257 /* NamedImports */:
126502                     case 263 /* ExportSpecifier */:
126503                     case 258 /* ImportSpecifier */:
126504                     case 159 /* PropertyDeclaration */:
126505                         return true;
126506                     case 242 /* VariableDeclaration */:
126507                     case 281 /* PropertyAssignment */:
126508                     case 209 /* BinaryExpression */:
126509                         if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 193 /* ObjectLiteralExpression */) { // TODO: GH#18217
126510                             return rangeIsOnOneLine(sourceFile, child);
126511                         }
126512                         if (parent.kind !== 209 /* BinaryExpression */) {
126513                             return true;
126514                         }
126515                         break;
126516                     case 228 /* DoStatement */:
126517                     case 229 /* WhileStatement */:
126518                     case 231 /* ForInStatement */:
126519                     case 232 /* ForOfStatement */:
126520                     case 230 /* ForStatement */:
126521                     case 227 /* IfStatement */:
126522                     case 244 /* FunctionDeclaration */:
126523                     case 201 /* FunctionExpression */:
126524                     case 161 /* MethodDeclaration */:
126525                     case 202 /* ArrowFunction */:
126526                     case 162 /* Constructor */:
126527                     case 163 /* GetAccessor */:
126528                     case 164 /* SetAccessor */:
126529                         return childKind !== 223 /* Block */;
126530                     case 260 /* ExportDeclaration */:
126531                         return childKind !== 261 /* NamedExports */;
126532                     case 254 /* ImportDeclaration */:
126533                         return childKind !== 255 /* ImportClause */ ||
126534                             (!!child.namedBindings && child.namedBindings.kind !== 257 /* NamedImports */);
126535                     case 266 /* JsxElement */:
126536                         return childKind !== 269 /* JsxClosingElement */;
126537                     case 270 /* JsxFragment */:
126538                         return childKind !== 272 /* JsxClosingFragment */;
126539                     case 179 /* IntersectionType */:
126540                     case 178 /* UnionType */:
126541                         if (childKind === 173 /* TypeLiteral */) {
126542                             return false;
126543                         }
126544                     // falls through
126545                 }
126546                 // No explicit rule for given nodes so the result will follow the default value argument
126547                 return indentByDefault;
126548             }
126549             SmartIndenter.nodeWillIndentChild = nodeWillIndentChild;
126550             function isControlFlowEndingStatement(kind, parent) {
126551                 switch (kind) {
126552                     case 235 /* ReturnStatement */:
126553                     case 239 /* ThrowStatement */:
126554                     case 233 /* ContinueStatement */:
126555                     case 234 /* BreakStatement */:
126556                         return parent.kind !== 223 /* Block */;
126557                     default:
126558                         return false;
126559                 }
126560             }
126561             /**
126562              * True when the parent node should indent the given child by an explicit rule.
126563              * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child.
126564              */
126565             function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) {
126566                 if (isNextChild === void 0) { isNextChild = false; }
126567                 return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false)
126568                     && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent));
126569             }
126570             SmartIndenter.shouldIndentChildNode = shouldIndentChildNode;
126571             function rangeIsOnOneLine(sourceFile, range) {
126572                 var rangeStart = ts.skipTrivia(sourceFile.text, range.pos);
126573                 var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line;
126574                 var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
126575                 return startLine === endLine;
126576             }
126577         })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {}));
126578     })(formatting = ts.formatting || (ts.formatting = {}));
126579 })(ts || (ts = {}));
126580 /* @internal */
126581 var ts;
126582 (function (ts) {
126583     var textChanges;
126584     (function (textChanges_3) {
126585         /**
126586          * Currently for simplicity we store recovered positions on the node itself.
126587          * It can be changed to side-table later if we decide that current design is too invasive.
126588          */
126589         function getPos(n) {
126590             var result = n.__pos;
126591             ts.Debug.assert(typeof result === "number");
126592             return result;
126593         }
126594         function setPos(n, pos) {
126595             ts.Debug.assert(typeof pos === "number");
126596             n.__pos = pos;
126597         }
126598         function getEnd(n) {
126599             var result = n.__end;
126600             ts.Debug.assert(typeof result === "number");
126601             return result;
126602         }
126603         function setEnd(n, end) {
126604             ts.Debug.assert(typeof end === "number");
126605             n.__end = end;
126606         }
126607         var LeadingTriviaOption;
126608         (function (LeadingTriviaOption) {
126609             /** Exclude all leading trivia (use getStart()) */
126610             LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
126611             /** Include leading trivia and,
126612              * if there are no line breaks between the node and the previous token,
126613              * include all trivia between the node and the previous token
126614              */
126615             LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
126616             /**
126617              * Include attached JSDoc comments
126618              */
126619             LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc";
126620             /**
126621              * Only delete trivia on the same line as getStart().
126622              * Used to avoid deleting leading comments
126623              */
126624             LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine";
126625         })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
126626         var TrailingTriviaOption;
126627         (function (TrailingTriviaOption) {
126628             /** Exclude all trailing trivia (use getEnd()) */
126629             TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
126630             /** Include trailing trivia */
126631             TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
126632         })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
126633         function skipWhitespacesAndLineBreaks(text, start) {
126634             return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
126635         }
126636         function hasCommentsBeforeLineBreak(text, start) {
126637             var i = start;
126638             while (i < text.length) {
126639                 var ch = text.charCodeAt(i);
126640                 if (ts.isWhiteSpaceSingleLine(ch)) {
126641                     i++;
126642                     continue;
126643                 }
126644                 return ch === 47 /* slash */;
126645             }
126646             return false;
126647         }
126648         var useNonAdjustedPositions = {
126649             leadingTriviaOption: LeadingTriviaOption.Exclude,
126650             trailingTriviaOption: TrailingTriviaOption.Exclude,
126651         };
126652         var ChangeKind;
126653         (function (ChangeKind) {
126654             ChangeKind[ChangeKind["Remove"] = 0] = "Remove";
126655             ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode";
126656             ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes";
126657             ChangeKind[ChangeKind["Text"] = 3] = "Text";
126658         })(ChangeKind || (ChangeKind = {}));
126659         function getAdjustedRange(sourceFile, startNode, endNode, options) {
126660             return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
126661         }
126662         function getAdjustedStartPosition(sourceFile, node, options) {
126663             var leadingTriviaOption = options.leadingTriviaOption;
126664             if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
126665                 return node.getStart(sourceFile);
126666             }
126667             if (leadingTriviaOption === LeadingTriviaOption.StartLine) {
126668                 return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile);
126669             }
126670             if (leadingTriviaOption === LeadingTriviaOption.JSDoc) {
126671                 var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text);
126672                 if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) {
126673                     return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile);
126674                 }
126675             }
126676             var fullStart = node.getFullStart();
126677             var start = node.getStart(sourceFile);
126678             if (fullStart === start) {
126679                 return start;
126680             }
126681             var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile);
126682             var startLine = ts.getLineStartPositionForPosition(start, sourceFile);
126683             if (startLine === fullStartLine) {
126684                 // full start and start of the node are on the same line
126685                 //   a,     b;
126686                 //    ^     ^
126687                 //    |   start
126688                 // fullstart
126689                 // when b is replaced - we usually want to keep the leading trvia
126690                 // when b is deleted - we delete it
126691                 return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
126692             }
126693             // get start position of the line following the line that contains fullstart position
126694             // (but only if the fullstart isn't the very beginning of the file)
126695             var nextLineStart = fullStart > 0 ? 1 : 0;
126696             var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
126697             // skip whitespaces/newlines
126698             adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
126699             return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
126700         }
126701         function getAdjustedEndPosition(sourceFile, node, options) {
126702             var end = node.end;
126703             var trailingTriviaOption = options.trailingTriviaOption;
126704             if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
126705                 return end;
126706             }
126707             var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
126708             return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
126709                 ? newEnd
126710                 : end;
126711         }
126712         /**
126713          * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
126714          */
126715         function isSeparator(node, candidate) {
126716             return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 193 /* ObjectLiteralExpression */));
126717         }
126718         function spaces(count) {
126719             var s = "";
126720             for (var i = 0; i < count; i++) {
126721                 s += " ";
126722             }
126723             return s;
126724         }
126725         function isThisTypeAnnotatable(containingFunction) {
126726             return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction);
126727         }
126728         textChanges_3.isThisTypeAnnotatable = isThisTypeAnnotatable;
126729         var ChangeTracker = /** @class */ (function () {
126730             /** Public for tests only. Other callers should use `ChangeTracker.with`. */
126731             function ChangeTracker(newLineCharacter, formatContext) {
126732                 this.newLineCharacter = newLineCharacter;
126733                 this.formatContext = formatContext;
126734                 this.changes = [];
126735                 this.newFiles = [];
126736                 this.classesWithNodesInsertedAtStart = ts.createMap(); // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
126737                 this.deletedNodes = [];
126738             }
126739             ChangeTracker.fromContext = function (context) {
126740                 return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
126741             };
126742             ChangeTracker.with = function (context, cb) {
126743                 var tracker = ChangeTracker.fromContext(context);
126744                 cb(tracker);
126745                 return tracker.getChanges();
126746             };
126747             ChangeTracker.prototype.pushRaw = function (sourceFile, change) {
126748                 ts.Debug.assertEqual(sourceFile.fileName, change.fileName);
126749                 for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) {
126750                     var c = _a[_i];
126751                     this.changes.push({
126752                         kind: ChangeKind.Text,
126753                         sourceFile: sourceFile,
126754                         text: c.newText,
126755                         range: ts.createTextRangeFromSpan(c.span),
126756                     });
126757                 }
126758             };
126759             ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
126760                 this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
126761             };
126762             ChangeTracker.prototype.delete = function (sourceFile, node) {
126763                 this.deletedNodes.push({ sourceFile: sourceFile, node: node });
126764             };
126765             ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) {
126766                 if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
126767                 this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options));
126768             };
126769             ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) {
126770                 this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
126771             };
126772             ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
126773                 if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
126774                 var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
126775                 var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
126776                 this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
126777             };
126778             ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
126779                 if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
126780                 var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
126781                 var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
126782                 this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
126783             };
126784             ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
126785                 if (options === void 0) { options = {}; }
126786                 this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
126787             };
126788             ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
126789                 if (options === void 0) { options = useNonAdjustedPositions; }
126790                 this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
126791             };
126792             ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
126793                 if (options === void 0) { options = useNonAdjustedPositions; }
126794                 this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
126795             };
126796             ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
126797                 if (options === void 0) { options = {}; }
126798                 this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
126799             };
126800             ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
126801                 if (options === void 0) { options = useNonAdjustedPositions; }
126802                 this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
126803             };
126804             ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
126805                 this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
126806             };
126807             ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
126808                 if (options === void 0) { options = useNonAdjustedPositions; }
126809                 this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
126810             };
126811             ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
126812                 var next = ts.findNextToken(node, node.parent, sourceFile);
126813                 return next && next.kind === 27 /* CommaToken */ ? next : undefined;
126814             };
126815             ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
126816                 var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
126817                 this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
126818             };
126819             ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
126820                 if (options === void 0) { options = {}; }
126821                 this.replaceRange(sourceFile, ts.createRange(pos), newNode, options);
126822             };
126823             ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) {
126824                 if (options === void 0) { options = {}; }
126825                 this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options);
126826             };
126827             ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) {
126828                 this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween);
126829             };
126830             ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) {
126831                 this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween);
126832             };
126833             ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) {
126834                 var pos = getInsertionPositionAtSourceFileTop(sourceFile);
126835                 var options = {
126836                     prefix: pos === 0 ? undefined : this.newLineCharacter,
126837                     suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""),
126838                 };
126839                 if (ts.isArray(insert)) {
126840                     this.insertNodesAt(sourceFile, pos, insert, options);
126841                 }
126842                 else {
126843                     this.insertNodeAt(sourceFile, pos, insert, options);
126844                 }
126845             };
126846             ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) {
126847                 var p0 = ts.firstOrUndefined(parameters);
126848                 if (p0) {
126849                     this.insertNodeBefore(sourceFile, p0, newParam);
126850                 }
126851                 else {
126852                     this.insertNodeAt(sourceFile, parameters.pos, newParam);
126853                 }
126854             };
126855             ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
126856                 if (blankLineBetween === void 0) { blankLineBetween = false; }
126857                 this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
126858             };
126859             ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
126860                 var pos = before.getStart(sourceFile);
126861                 this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " });
126862             };
126863             ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) {
126864                 if (!before.modifiers) {
126865                     this.insertModifierBefore(sourceFile, modifier, before);
126866                     return;
126867                 }
126868                 var pos = before.modifiers.end;
126869                 this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " });
126870             };
126871             ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) {
126872                 var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile);
126873                 var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
126874                 // First try to see if we can put the comment on the previous line.
126875                 // We need to make sure that we are not in the middle of a string literal or a comment.
126876                 // If so, we do not want to separate the node from its comment if we can.
126877                 // Otherwise, add an extra new line immediately before the error span.
126878                 var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
126879                 var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
126880                 var indent = sourceFile.text.slice(lineStartPosition, startPosition);
126881                 var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
126882                 this.insertText(sourceFile, token.getStart(sourceFile), text);
126883             };
126884             ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) {
126885                 var fnStart = node.getStart(sourceFile);
126886                 if (node.jsDoc) {
126887                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
126888                         var jsdoc = _a[_i];
126889                         this.deleteRange(sourceFile, {
126890                             pos: ts.getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile),
126891                             end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {})
126892                         });
126893                     }
126894                 }
126895                 var startPosition = ts.getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1);
126896                 var indent = sourceFile.text.slice(startPosition, fnStart);
126897                 this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent });
126898             };
126899             ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
126900                 this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text });
126901             };
126902             ChangeTracker.prototype.insertText = function (sourceFile, pos, text) {
126903                 this.replaceRangeWithText(sourceFile, ts.createRange(pos), text);
126904             };
126905             /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
126906             ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) {
126907                 var _a;
126908                 var endNode;
126909                 if (ts.isFunctionLike(node)) {
126910                     endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile);
126911                     if (!endNode) {
126912                         if (!ts.isArrowFunction(node))
126913                             return false; // Function missing parentheses, give up
126914                         // If no `)`, is an arrow function `x => x`, so use the end of the first parameter
126915                         endNode = ts.first(node.parameters);
126916                     }
126917                 }
126918                 else {
126919                     endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name;
126920                 }
126921                 this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
126922                 return true;
126923             };
126924             ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) {
126925                 var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1;
126926                 var suffix = node.parameters.length ? ", " : "";
126927                 this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix: suffix });
126928             };
126929             ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) {
126930                 // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter
126931                 var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile);
126932                 this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" });
126933             };
126934             ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, inserted, doubleNewlines) {
126935                 if (ts.isStatement(before) || ts.isClassElement(before)) {
126936                     return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
126937                 }
126938                 else if (ts.isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
126939                     return { suffix: ", " };
126940                 }
126941                 else if (ts.isParameter(before)) {
126942                     return ts.isParameter(inserted) ? { suffix: ", " } : {};
126943                 }
126944                 else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) {
126945                     return { suffix: ", " };
126946                 }
126947                 return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
126948             };
126949             ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
126950                 var firstStatement = ts.firstOrUndefined(ctr.body.statements);
126951                 if (!firstStatement || !ctr.body.multiLine) {
126952                     this.replaceConstructorBody(sourceFile, ctr, __spreadArrays([newStatement], ctr.body.statements));
126953                 }
126954                 else {
126955                     this.insertNodeBefore(sourceFile, firstStatement, newStatement);
126956                 }
126957             };
126958             ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) {
126959                 var lastStatement = ts.lastOrUndefined(ctr.body.statements);
126960                 if (!lastStatement || !ctr.body.multiLine) {
126961                     this.replaceConstructorBody(sourceFile, ctr, __spreadArrays(ctr.body.statements, [newStatement]));
126962                 }
126963                 else {
126964                     this.insertNodeAfter(sourceFile, lastStatement, newStatement);
126965                 }
126966             };
126967             ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) {
126968                 this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
126969             };
126970             ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
126971                 var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
126972                 this.insertNodeAt(sourceFile, pos, newNode, {
126973                     prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
126974                     suffix: this.newLineCharacter
126975                 });
126976             };
126977             ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
126978                 this.insertNodeAtStartWorker(sourceFile, cls, newElement);
126979             };
126980             ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) {
126981                 this.insertNodeAtStartWorker(sourceFile, obj, newElement);
126982             };
126983             ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) {
126984                 var _a;
126985                 var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls);
126986                 this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation));
126987             };
126988             /**
126989              * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on
126990              * new lines and must share the same indentation.
126991              */
126992             ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) {
126993                 var indentation;
126994                 var lastRange = cls;
126995                 for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) {
126996                     var member = _a[_i];
126997                     if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) {
126998                         // each indented member must be on a new line
126999                         return undefined;
127000                     }
127001                     var memberStart = member.getStart(sourceFile);
127002                     var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options);
127003                     if (indentation === undefined) {
127004                         indentation = memberIndentation;
127005                     }
127006                     else if (memberIndentation !== indentation) {
127007                         // indentation of multiple members is not consistent
127008                         return undefined;
127009                     }
127010                     lastRange = member;
127011                 }
127012                 return indentation;
127013             };
127014             ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) {
127015                 var _a;
127016                 var clsStart = cls.getStart(sourceFile);
127017                 return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
127018                     + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4);
127019             };
127020             ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) {
127021                 // Rules:
127022                 // - Always insert leading newline.
127023                 // - For object literals:
127024                 //   - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file
127025                 //     (because trailing commas are generally illegal in a JSON file).
127026                 //   - Add a leading comma if the source file is not a JSON file, there are existing insertions,
127027                 //     and the node is empty (because we didn't add a trailing comma per the previous rule).
127028                 // - Only insert a trailing newline if body is single-line and there are no other insertions for the node.
127029                 //   NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`.
127030                 var members = getMembersOrProperties(cls);
127031                 var isEmpty = members.length === 0;
127032                 var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile });
127033                 var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty);
127034                 var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion;
127035                 return {
127036                     indentation: indentation,
127037                     prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter,
127038                     suffix: insertTrailingComma ? "," : ""
127039                 };
127040             };
127041             ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
127042                 var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
127043                 this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
127044             };
127045             ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
127046                 var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
127047                 this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
127048             };
127049             ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) {
127050                 this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
127051             };
127052             ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
127053                 var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
127054                 this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
127055             };
127056             ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
127057                 if (needSemicolonBetween(after, newNode)) {
127058                     // check if previous statement ends with semicolon
127059                     // if not - insert semicolon to preserve the code from changing the meaning due to ASI
127060                     if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
127061                         this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(26 /* SemicolonToken */));
127062                     }
127063                 }
127064                 var endPosition = getAdjustedEndPosition(sourceFile, after, {});
127065                 return endPosition;
127066             };
127067             ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
127068                 var options = this.getInsertNodeAfterOptionsWorker(after);
127069                 return __assign(__assign({}, options), { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
127070             };
127071             ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
127072                 switch (node.kind) {
127073                     case 245 /* ClassDeclaration */:
127074                     case 249 /* ModuleDeclaration */:
127075                         return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
127076                     case 242 /* VariableDeclaration */:
127077                     case 10 /* StringLiteral */:
127078                     case 75 /* Identifier */:
127079                         return { prefix: ", " };
127080                     case 281 /* PropertyAssignment */:
127081                         return { suffix: "," + this.newLineCharacter };
127082                     case 89 /* ExportKeyword */:
127083                         return { prefix: " " };
127084                     case 156 /* Parameter */:
127085                         return {};
127086                     default:
127087                         ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it
127088                         return { suffix: this.newLineCharacter };
127089                 }
127090             };
127091             ChangeTracker.prototype.insertName = function (sourceFile, node, name) {
127092                 ts.Debug.assert(!node.name);
127093                 if (node.kind === 202 /* ArrowFunction */) {
127094                     var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile);
127095                     var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile);
127096                     if (lparen) {
127097                         // `() => {}` --> `function f() {}`
127098                         this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(94 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " });
127099                         deleteNode(this, sourceFile, arrow);
127100                     }
127101                     else {
127102                         // `x => {}` -> `function f(x) {}`
127103                         this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "(");
127104                         // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)`
127105                         this.replaceRange(sourceFile, arrow, ts.createToken(21 /* CloseParenToken */));
127106                     }
127107                     if (node.body.kind !== 223 /* Block */) {
127108                         // `() => 0` => `function f() { return 0; }`
127109                         this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(18 /* OpenBraceToken */), ts.createToken(101 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
127110                         this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(26 /* SemicolonToken */), ts.createToken(19 /* CloseBraceToken */)], { joiner: " " });
127111                     }
127112                 }
127113                 else {
127114                     var pos = ts.findChildOfKind(node, node.kind === 201 /* FunctionExpression */ ? 94 /* FunctionKeyword */ : 80 /* ClassKeyword */, sourceFile).end;
127115                     this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
127116                 }
127117             };
127118             ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
127119                 this.insertText(sourceFile, node.getStart(sourceFile), "export ");
127120             };
127121             /**
127122              * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
127123              * i.e. arguments in arguments lists, parameters in parameter lists etc.
127124              * Note that separators are part of the node in statements and class elements.
127125              */
127126             ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
127127                 if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
127128                 if (!containingList) {
127129                     ts.Debug.fail("node is not a list element");
127130                     return;
127131                 }
127132                 var index = ts.indexOfNode(containingList, after);
127133                 if (index < 0) {
127134                     return;
127135                 }
127136                 var end = after.getEnd();
127137                 if (index !== containingList.length - 1) {
127138                     // any element except the last one
127139                     // use next sibling as an anchor
127140                     var nextToken = ts.getTokenAtPosition(sourceFile, after.end);
127141                     if (nextToken && isSeparator(after, nextToken)) {
127142                         // for list
127143                         // a, b, c
127144                         // create change for adding 'e' after 'a' as
127145                         // - find start of next element after a (it is b)
127146                         // - use this start as start and end position in final change
127147                         // - build text of change by formatting the text of node + separator + whitespace trivia of b
127148                         // in multiline case it will work as
127149                         //   a,
127150                         //   b,
127151                         //   c,
127152                         // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#')
127153                         //   a,*
127154                         // ***insertedtext<separator>#
127155                         // ###b,
127156                         //   c,
127157                         // find line and character of the next element
127158                         var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart()));
127159                         // find line and character of the token that precedes next element (usually it is separator)
127160                         var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end);
127161                         var prefix = void 0;
127162                         var startPos = void 0;
127163                         if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) {
127164                             // next element is located on the same line with separator:
127165                             // a,$$$$b
127166                             //  ^    ^
127167                             //  |    |-next element
127168                             //  |-separator
127169                             // where $$$ is some leading trivia
127170                             // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces
127171                             // a,    x,$$$$b
127172                             //  ^    ^     ^
127173                             //  |    |     |-next element
127174                             //  |    |-new inserted node padded with spaces
127175                             //  |-separator
127176                             startPos = nextToken.end;
127177                             prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character);
127178                         }
127179                         else {
127180                             // next element is located on different line that separator
127181                             // let insert position be the beginning of the line that contains next element
127182                             startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile);
127183                         }
127184                         // write separator and leading trivia of the next element as suffix
127185                         var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile));
127186                         this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix });
127187                     }
127188                 }
127189                 else {
127190                     var afterStart = after.getStart(sourceFile);
127191                     var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile);
127192                     var separator = void 0;
127193                     var multilineList = false;
127194                     // insert element after the last element in the list that has more than one item
127195                     // pick the element preceding the after element to:
127196                     // - pick the separator
127197                     // - determine if list is a multiline
127198                     if (containingList.length === 1) {
127199                         // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise
127200                         // i.e. var x = 1 // this is x
127201                         //     | new element will be inserted at this position
127202                         separator = 27 /* CommaToken */;
127203                     }
127204                     else {
127205                         // element has more than one element, pick separator from the list
127206                         var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile);
127207                         separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 27 /* CommaToken */;
127208                         // determine if list is multiline by checking lines of after element and element that precedes it.
127209                         var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
127210                         multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
127211                     }
127212                     if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) {
127213                         // in this case we'll always treat containing list as multiline
127214                         multilineList = true;
127215                     }
127216                     if (multilineList) {
127217                         // insert separator immediately following the 'after' node to preserve comments in trailing trivia
127218                         this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator));
127219                         // use the same indentation as 'after' item
127220                         var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options);
127221                         // insert element before the line break on the line that contains 'after' element
127222                         var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false);
127223                         if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
127224                             insertPos--;
127225                         }
127226                         this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter });
127227                     }
127228                     else {
127229                         this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " });
127230                     }
127231                 }
127232             };
127233             ChangeTracker.prototype.parenthesizeExpression = function (sourceFile, expression) {
127234                 this.replaceRange(sourceFile, ts.rangeOfNode(expression), ts.createParen(expression));
127235             };
127236             ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () {
127237                 var _this = this;
127238                 this.classesWithNodesInsertedAtStart.forEach(function (_a) {
127239                     var node = _a.node, sourceFile = _a.sourceFile;
127240                     var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1];
127241                     if (openBraceEnd !== undefined && closeBraceEnd !== undefined) {
127242                         var isEmpty = getMembersOrProperties(node).length === 0;
127243                         var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile);
127244                         if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) {
127245                             // For `class C { }` remove the whitespace inside the braces.
127246                             _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1));
127247                         }
127248                         if (isSingleLine) {
127249                             _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter);
127250                         }
127251                     }
127252                 });
127253             };
127254             ChangeTracker.prototype.finishDeleteDeclarations = function () {
127255                 var _this = this;
127256                 var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
127257                 var _loop_9 = function (sourceFile, node) {
127258                     if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
127259                         if (ts.isArray(node)) {
127260                             this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
127261                         }
127262                         else {
127263                             deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node);
127264                         }
127265                     }
127266                 };
127267                 var this_1 = this;
127268                 for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
127269                     var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
127270                     _loop_9(sourceFile, node);
127271                 }
127272                 deletedNodesInLists.forEach(function (node) {
127273                     var sourceFile = node.getSourceFile();
127274                     var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
127275                     if (node !== ts.last(list))
127276                         return;
127277                     var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2);
127278                     if (lastNonDeletedIndex !== -1) {
127279                         _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
127280                     }
127281                 });
127282             };
127283             /**
127284              * Note: after calling this, the TextChanges object must be discarded!
127285              * @param validate only for tests
127286              *    The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions,
127287              *    so we can only call this once and can't get the non-formatted text separately.
127288              */
127289             ChangeTracker.prototype.getChanges = function (validate) {
127290                 this.finishDeleteDeclarations();
127291                 this.finishClassesWithNodesInsertedAtStart();
127292                 var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
127293                 for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
127294                     var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
127295                     changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext));
127296                 }
127297                 return changes;
127298             };
127299             ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
127300                 this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
127301             };
127302             return ChangeTracker;
127303         }());
127304         textChanges_3.ChangeTracker = ChangeTracker;
127305         // find first non-whitespace position in the leading trivia of the node
127306         function startPositionToDeleteNodeInList(sourceFile, node) {
127307             return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
127308         }
127309         function getClassOrObjectBraceEnds(cls, sourceFile) {
127310             var open = ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile);
127311             var close = ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile);
127312             return [open === null || open === void 0 ? void 0 : open.end, close === null || close === void 0 ? void 0 : close.end];
127313         }
127314         function getMembersOrProperties(cls) {
127315             return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members;
127316         }
127317         function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) {
127318             return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext);
127319         }
127320         textChanges_3.getNewFileText = getNewFileText;
127321         var changesToText;
127322         (function (changesToText) {
127323             function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) {
127324                 return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) {
127325                     var sourceFile = changesInFile[0].sourceFile;
127326                     // order changes by start position
127327                     // 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.
127328                     var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
127329                     var _loop_10 = function (i) {
127330                         ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
127331                             return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
127332                         });
127333                     };
127334                     // verify that change intervals do not overlap, except possibly at end points.
127335                     for (var i = 0; i < normalized.length - 1; i++) {
127336                         _loop_10(i);
127337                     }
127338                     var textChanges = ts.mapDefined(normalized, function (c) {
127339                         var span = ts.createTextSpanFromRange(c.range);
127340                         var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate);
127341                         // Filter out redundant changes.
127342                         if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) {
127343                             return undefined;
127344                         }
127345                         return ts.createTextChange(span, newText);
127346                     });
127347                     return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined;
127348                 });
127349             }
127350             changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
127351             function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) {
127352                 var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext);
127353                 return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
127354             }
127355             changesToText.newFileChanges = newFileChanges;
127356             function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
127357                 // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
127358                 var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
127359                 var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 99 /* ESNext */, /*setParentNodes*/ true, scriptKind);
127360                 var changes = ts.formatting.formatDocument(sourceFile, formatContext);
127361                 return applyChanges(nonFormattedText, changes) + newLineCharacter;
127362             }
127363             changesToText.newFileChangesWorker = newFileChangesWorker;
127364             function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
127365                 if (change.kind === ChangeKind.Remove) {
127366                     return "";
127367                 }
127368                 if (change.kind === ChangeKind.Text) {
127369                     return change.text;
127370                 }
127371                 var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos;
127372                 var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); };
127373                 var text = change.kind === ChangeKind.ReplaceWithMultipleNodes
127374                     ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217
127375                     : format(change.node);
127376                 // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
127377                 var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, "");
127378                 return (options.prefix || "") + noIndent
127379                     + ((!options.suffix || ts.endsWith(noIndent, options.suffix))
127380                         ? "" : options.suffix);
127381             }
127382             function getFormatCodeSettingsForWriting(_a, sourceFile) {
127383                 var options = _a.options;
127384                 var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore;
127385                 var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !ts.probablyUsesSemicolons(sourceFile);
127386                 return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore });
127387             }
127388             /** Note: this may mutate `nodeIn`. */
127389             function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) {
127390                 var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta;
127391                 var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text;
127392                 if (validate)
127393                     validate(node, text);
127394                 var formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile);
127395                 var initialIndentation = indentation !== undefined
127396                     ? indentation
127397                     : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos);
127398                 if (delta === undefined) {
127399                     delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? (formatOptions.indentSize || 0) : 0;
127400                 }
127401                 var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } };
127402                 var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, __assign(__assign({}, formatContext), { options: formatOptions }));
127403                 return applyChanges(text, changes);
127404             }
127405             /** Note: output node may be mutated input node. */
127406             function getNonformattedText(node, sourceFile, newLineCharacter) {
127407                 var writer = createWriter(newLineCharacter);
127408                 var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */;
127409                 ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, preserveSourceNewlines: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer);
127410                 return { text: writer.getText(), node: assignPositionsToNode(node) };
127411             }
127412             changesToText.getNonformattedText = getNonformattedText;
127413         })(changesToText || (changesToText = {}));
127414         function applyChanges(text, changes) {
127415             for (var i = changes.length - 1; i >= 0; i--) {
127416                 var _a = changes[i], span = _a.span, newText = _a.newText;
127417                 text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span));
127418             }
127419             return text;
127420         }
127421         textChanges_3.applyChanges = applyChanges;
127422         function isTrivia(s) {
127423             return ts.skipTrivia(s, 0) === s.length;
127424         }
127425         function assignPositionsToNode(node) {
127426             var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217
127427             // create proxy node for non synthesized nodes
127428             var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited);
127429             newNode.pos = getPos(node);
127430             newNode.end = getEnd(node);
127431             return newNode;
127432         }
127433         function assignPositionsToNodeArray(nodes, visitor, test, start, count) {
127434             var visited = ts.visitNodes(nodes, visitor, test, start, count);
127435             if (!visited) {
127436                 return visited;
127437             }
127438             // clone nodearray if necessary
127439             var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited;
127440             nodeArray.pos = getPos(nodes);
127441             nodeArray.end = getEnd(nodes);
127442             return nodeArray;
127443         }
127444         function createWriter(newLine) {
127445             var lastNonTriviaPosition = 0;
127446             var writer = ts.createTextWriter(newLine);
127447             var onEmitNode = function (hint, node, printCallback) {
127448                 if (node) {
127449                     setPos(node, lastNonTriviaPosition);
127450                 }
127451                 printCallback(hint, node);
127452                 if (node) {
127453                     setEnd(node, lastNonTriviaPosition);
127454                 }
127455             };
127456             var onBeforeEmitNodeArray = function (nodes) {
127457                 if (nodes) {
127458                     setPos(nodes, lastNonTriviaPosition);
127459                 }
127460             };
127461             var onAfterEmitNodeArray = function (nodes) {
127462                 if (nodes) {
127463                     setEnd(nodes, lastNonTriviaPosition);
127464                 }
127465             };
127466             var onBeforeEmitToken = function (node) {
127467                 if (node) {
127468                     setPos(node, lastNonTriviaPosition);
127469                 }
127470             };
127471             var onAfterEmitToken = function (node) {
127472                 if (node) {
127473                     setEnd(node, lastNonTriviaPosition);
127474                 }
127475             };
127476             function setLastNonTriviaPosition(s, force) {
127477                 if (force || !isTrivia(s)) {
127478                     lastNonTriviaPosition = writer.getTextPos();
127479                     var i = 0;
127480                     while (ts.isWhiteSpaceLike(s.charCodeAt(s.length - i - 1))) {
127481                         i++;
127482                     }
127483                     // trim trailing whitespaces
127484                     lastNonTriviaPosition -= i;
127485                 }
127486             }
127487             function write(s) {
127488                 writer.write(s);
127489                 setLastNonTriviaPosition(s, /*force*/ false);
127490             }
127491             function writeComment(s) {
127492                 writer.writeComment(s);
127493             }
127494             function writeKeyword(s) {
127495                 writer.writeKeyword(s);
127496                 setLastNonTriviaPosition(s, /*force*/ false);
127497             }
127498             function writeOperator(s) {
127499                 writer.writeOperator(s);
127500                 setLastNonTriviaPosition(s, /*force*/ false);
127501             }
127502             function writePunctuation(s) {
127503                 writer.writePunctuation(s);
127504                 setLastNonTriviaPosition(s, /*force*/ false);
127505             }
127506             function writeTrailingSemicolon(s) {
127507                 writer.writeTrailingSemicolon(s);
127508                 setLastNonTriviaPosition(s, /*force*/ false);
127509             }
127510             function writeParameter(s) {
127511                 writer.writeParameter(s);
127512                 setLastNonTriviaPosition(s, /*force*/ false);
127513             }
127514             function writeProperty(s) {
127515                 writer.writeProperty(s);
127516                 setLastNonTriviaPosition(s, /*force*/ false);
127517             }
127518             function writeSpace(s) {
127519                 writer.writeSpace(s);
127520                 setLastNonTriviaPosition(s, /*force*/ false);
127521             }
127522             function writeStringLiteral(s) {
127523                 writer.writeStringLiteral(s);
127524                 setLastNonTriviaPosition(s, /*force*/ false);
127525             }
127526             function writeSymbol(s, sym) {
127527                 writer.writeSymbol(s, sym);
127528                 setLastNonTriviaPosition(s, /*force*/ false);
127529             }
127530             function writeLine(force) {
127531                 writer.writeLine(force);
127532             }
127533             function increaseIndent() {
127534                 writer.increaseIndent();
127535             }
127536             function decreaseIndent() {
127537                 writer.decreaseIndent();
127538             }
127539             function getText() {
127540                 return writer.getText();
127541             }
127542             function rawWrite(s) {
127543                 writer.rawWrite(s);
127544                 setLastNonTriviaPosition(s, /*force*/ false);
127545             }
127546             function writeLiteral(s) {
127547                 writer.writeLiteral(s);
127548                 setLastNonTriviaPosition(s, /*force*/ true);
127549             }
127550             function getTextPos() {
127551                 return writer.getTextPos();
127552             }
127553             function getLine() {
127554                 return writer.getLine();
127555             }
127556             function getColumn() {
127557                 return writer.getColumn();
127558             }
127559             function getIndent() {
127560                 return writer.getIndent();
127561             }
127562             function isAtStartOfLine() {
127563                 return writer.isAtStartOfLine();
127564             }
127565             function clear() {
127566                 writer.clear();
127567                 lastNonTriviaPosition = 0;
127568             }
127569             return {
127570                 onEmitNode: onEmitNode,
127571                 onBeforeEmitNodeArray: onBeforeEmitNodeArray,
127572                 onAfterEmitNodeArray: onAfterEmitNodeArray,
127573                 onBeforeEmitToken: onBeforeEmitToken,
127574                 onAfterEmitToken: onAfterEmitToken,
127575                 write: write,
127576                 writeComment: writeComment,
127577                 writeKeyword: writeKeyword,
127578                 writeOperator: writeOperator,
127579                 writePunctuation: writePunctuation,
127580                 writeTrailingSemicolon: writeTrailingSemicolon,
127581                 writeParameter: writeParameter,
127582                 writeProperty: writeProperty,
127583                 writeSpace: writeSpace,
127584                 writeStringLiteral: writeStringLiteral,
127585                 writeSymbol: writeSymbol,
127586                 writeLine: writeLine,
127587                 increaseIndent: increaseIndent,
127588                 decreaseIndent: decreaseIndent,
127589                 getText: getText,
127590                 rawWrite: rawWrite,
127591                 writeLiteral: writeLiteral,
127592                 getTextPos: getTextPos,
127593                 getLine: getLine,
127594                 getColumn: getColumn,
127595                 getIndent: getIndent,
127596                 isAtStartOfLine: isAtStartOfLine,
127597                 hasTrailingComment: function () { return writer.hasTrailingComment(); },
127598                 hasTrailingWhitespace: function () { return writer.hasTrailingWhitespace(); },
127599                 clear: clear
127600             };
127601         }
127602         function getInsertionPositionAtSourceFileTop(sourceFile) {
127603             var lastPrologue;
127604             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
127605                 var node = _a[_i];
127606                 if (ts.isPrologueDirective(node)) {
127607                     lastPrologue = node;
127608                 }
127609                 else {
127610                     break;
127611                 }
127612             }
127613             var position = 0;
127614             var text = sourceFile.text;
127615             if (lastPrologue) {
127616                 position = lastPrologue.end;
127617                 advancePastLineBreak();
127618                 return position;
127619             }
127620             var shebang = ts.getShebang(text);
127621             if (shebang !== undefined) {
127622                 position = shebang.length;
127623                 advancePastLineBreak();
127624             }
127625             var ranges = ts.getLeadingCommentRanges(text, position);
127626             if (!ranges)
127627                 return position;
127628             // Find the first attached comment to the first node and add before it
127629             var lastComment;
127630             var firstNodeLine;
127631             for (var _b = 0, ranges_1 = ranges; _b < ranges_1.length; _b++) {
127632                 var range = ranges_1[_b];
127633                 if (range.kind === 3 /* MultiLineCommentTrivia */) {
127634                     if (ts.isPinnedComment(text, range.pos)) {
127635                         lastComment = { range: range, pinnedOrTripleSlash: true };
127636                         continue;
127637                     }
127638                 }
127639                 else if (ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) {
127640                     lastComment = { range: range, pinnedOrTripleSlash: true };
127641                     continue;
127642                 }
127643                 if (lastComment) {
127644                     // Always insert after pinned or triple slash comments
127645                     if (lastComment.pinnedOrTripleSlash)
127646                         break;
127647                     // There was a blank line between the last comment and this comment.
127648                     // This comment is not part of the copyright comments
127649                     var commentLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
127650                     var lastCommentEndLine = sourceFile.getLineAndCharacterOfPosition(lastComment.range.end).line;
127651                     if (commentLine >= lastCommentEndLine + 2)
127652                         break;
127653                 }
127654                 if (sourceFile.statements.length) {
127655                     if (firstNodeLine === undefined)
127656                         firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line;
127657                     var commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
127658                     if (firstNodeLine < commentEndLine + 2)
127659                         break;
127660                 }
127661                 lastComment = { range: range, pinnedOrTripleSlash: false };
127662             }
127663             if (lastComment) {
127664                 position = lastComment.range.end;
127665                 advancePastLineBreak();
127666             }
127667             return position;
127668             function advancePastLineBreak() {
127669                 if (position < text.length) {
127670                     var charCode = text.charCodeAt(position);
127671                     if (ts.isLineBreak(charCode)) {
127672                         position++;
127673                         if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) {
127674                             position++;
127675                         }
127676                     }
127677                 }
127678             }
127679         }
127680         function isValidLocationToAddComment(sourceFile, position) {
127681             return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position);
127682         }
127683         textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment;
127684         function needSemicolonBetween(a, b) {
127685             return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 154 /* ComputedPropertyName */
127686                 || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[`
127687         }
127688         var deleteDeclaration;
127689         (function (deleteDeclaration_1) {
127690             function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) {
127691                 switch (node.kind) {
127692                     case 156 /* Parameter */: {
127693                         var oldFunction = node.parent;
127694                         if (ts.isArrowFunction(oldFunction) &&
127695                             oldFunction.parameters.length === 1 &&
127696                             !ts.findChildOfKind(oldFunction, 20 /* OpenParenToken */, sourceFile)) {
127697                             // Lambdas with exactly one parameter are special because, after removal, there
127698                             // must be an empty parameter list (i.e. `()`) and this won't necessarily be the
127699                             // case if the parameter is simply removed (e.g. in `x => 1`).
127700                             changes.replaceNodeWithText(sourceFile, node, "()");
127701                         }
127702                         else {
127703                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127704                         }
127705                         break;
127706                     }
127707                     case 254 /* ImportDeclaration */:
127708                     case 253 /* ImportEqualsDeclaration */:
127709                         var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax);
127710                         // For first import, leave header comment in place, otherwise only delete JSDoc comments
127711                         deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine });
127712                         break;
127713                     case 191 /* BindingElement */:
127714                         var pattern = node.parent;
127715                         var preserveComma = pattern.kind === 190 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements);
127716                         if (preserveComma) {
127717                             deleteNode(changes, sourceFile, node);
127718                         }
127719                         else {
127720                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127721                         }
127722                         break;
127723                     case 242 /* VariableDeclaration */:
127724                         deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
127725                         break;
127726                     case 155 /* TypeParameter */:
127727                         deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127728                         break;
127729                     case 258 /* ImportSpecifier */:
127730                         var namedImports = node.parent;
127731                         if (namedImports.elements.length === 1) {
127732                             deleteImportBinding(changes, sourceFile, namedImports);
127733                         }
127734                         else {
127735                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127736                         }
127737                         break;
127738                     case 256 /* NamespaceImport */:
127739                         deleteImportBinding(changes, sourceFile, node);
127740                         break;
127741                     case 26 /* SemicolonToken */:
127742                         deleteNode(changes, sourceFile, node, { trailingTriviaOption: TrailingTriviaOption.Exclude });
127743                         break;
127744                     case 94 /* FunctionKeyword */:
127745                         deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude });
127746                         break;
127747                     case 245 /* ClassDeclaration */:
127748                     case 244 /* FunctionDeclaration */:
127749                         deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine });
127750                         break;
127751                     default:
127752                         if (ts.isImportClause(node.parent) && node.parent.name === node) {
127753                             deleteDefaultImport(changes, sourceFile, node.parent);
127754                         }
127755                         else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) {
127756                             deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127757                         }
127758                         else {
127759                             deleteNode(changes, sourceFile, node);
127760                         }
127761                 }
127762             }
127763             deleteDeclaration_1.deleteDeclaration = deleteDeclaration;
127764             function deleteDefaultImport(changes, sourceFile, importClause) {
127765                 if (!importClause.namedBindings) {
127766                     // Delete the whole import
127767                     deleteNode(changes, sourceFile, importClause.parent);
127768                 }
127769                 else {
127770                     // import |d,| * as ns from './file'
127771                     var start = importClause.name.getStart(sourceFile);
127772                     var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end);
127773                     if (nextToken && nextToken.kind === 27 /* CommaToken */) {
127774                         // shift first non-whitespace position after comma to the start position of the node
127775                         var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true);
127776                         changes.deleteRange(sourceFile, { pos: start, end: end });
127777                     }
127778                     else {
127779                         deleteNode(changes, sourceFile, importClause.name);
127780                     }
127781                 }
127782             }
127783             function deleteImportBinding(changes, sourceFile, node) {
127784                 if (node.parent.name) {
127785                     // Delete named imports while preserving the default import
127786                     // import d|, * as ns| from './file'
127787                     // import d|, { a }| from './file'
127788                     var previousToken = ts.Debug.checkDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1));
127789                     changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
127790                 }
127791                 else {
127792                     // Delete the entire import declaration
127793                     // |import * as ns from './file'|
127794                     // |import { a } from './file'|
127795                     var importDecl = ts.getAncestor(node, 254 /* ImportDeclaration */);
127796                     deleteNode(changes, sourceFile, importDecl);
127797                 }
127798             }
127799             function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
127800                 var parent = node.parent;
127801                 if (parent.kind === 280 /* CatchClause */) {
127802                     // TODO: There's currently no unused diagnostic for this, could be a suggestion
127803                     changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile));
127804                     return;
127805                 }
127806                 if (parent.declarations.length !== 1) {
127807                     deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
127808                     return;
127809                 }
127810                 var gp = parent.parent;
127811                 switch (gp.kind) {
127812                     case 232 /* ForOfStatement */:
127813                     case 231 /* ForInStatement */:
127814                         changes.replaceNode(sourceFile, node, ts.createObjectLiteral());
127815                         break;
127816                     case 230 /* ForStatement */:
127817                         deleteNode(changes, sourceFile, parent);
127818                         break;
127819                     case 225 /* VariableStatement */:
127820                         deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine });
127821                         break;
127822                     default:
127823                         ts.Debug.assertNever(gp);
127824                 }
127825             }
127826         })(deleteDeclaration || (deleteDeclaration = {}));
127827         /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
127828         // Exported for tests only! (TODO: improve tests to not need this)
127829         function deleteNode(changes, sourceFile, node, options) {
127830             if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
127831             var startPosition = getAdjustedStartPosition(sourceFile, node, options);
127832             var endPosition = getAdjustedEndPosition(sourceFile, node, options);
127833             changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
127834         }
127835         textChanges_3.deleteNode = deleteNode;
127836         function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
127837             var containingList = ts.Debug.checkDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile));
127838             var index = ts.indexOfNode(containingList, node);
127839             ts.Debug.assert(index !== -1);
127840             if (containingList.length === 1) {
127841                 deleteNode(changes, sourceFile, node);
127842                 return;
127843             }
127844             // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node.
127845             // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`.
127846             ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
127847             deletedNodesInLists.add(node);
127848             changes.deleteRange(sourceFile, {
127849                 pos: startPositionToDeleteNodeInList(sourceFile, node),
127850                 end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]),
127851             });
127852         }
127853     })(textChanges = ts.textChanges || (ts.textChanges = {}));
127854 })(ts || (ts = {}));
127855 /* @internal */
127856 var ts;
127857 (function (ts) {
127858     var codefix;
127859     (function (codefix) {
127860         var errorCodeToFixes = ts.createMultiMap();
127861         var fixIdToRegistration = ts.createMap();
127862         function diagnosticToString(diag) {
127863             return ts.isArray(diag)
127864                 ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1))
127865                 : ts.getLocaleSpecificMessage(diag);
127866         }
127867         function createCodeFixActionWithoutFixAll(fixName, changes, description) {
127868             return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined);
127869         }
127870         codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll;
127871         function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) {
127872             return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command);
127873         }
127874         codefix.createCodeFixAction = createCodeFixAction;
127875         function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) {
127876             return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined };
127877         }
127878         function registerCodeFix(reg) {
127879             for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) {
127880                 var error = _a[_i];
127881                 errorCodeToFixes.add(String(error), reg);
127882             }
127883             if (reg.fixIds) {
127884                 for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) {
127885                     var fixId = _c[_b];
127886                     ts.Debug.assert(!fixIdToRegistration.has(fixId));
127887                     fixIdToRegistration.set(fixId, reg);
127888                 }
127889             }
127890         }
127891         codefix.registerCodeFix = registerCodeFix;
127892         function getSupportedErrorCodes() {
127893             return ts.arrayFrom(errorCodeToFixes.keys());
127894         }
127895         codefix.getSupportedErrorCodes = getSupportedErrorCodes;
127896         function removeFixIdIfFixAllUnavailable(registration, diagnostics) {
127897             var errorCodes = registration.errorCodes;
127898             var maybeFixableDiagnostics = 0;
127899             for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
127900                 var diag = diagnostics_1[_i];
127901                 if (ts.contains(errorCodes, diag.code))
127902                     maybeFixableDiagnostics++;
127903                 if (maybeFixableDiagnostics > 1)
127904                     break;
127905             }
127906             var fixAllUnavailable = maybeFixableDiagnostics < 2;
127907             return function (_a) {
127908                 var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]);
127909                 return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription });
127910             };
127911         }
127912         function getFixes(context) {
127913             var diagnostics = getDiagnostics(context);
127914             var registrations = errorCodeToFixes.get(String(context.errorCode));
127915             return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); });
127916         }
127917         codefix.getFixes = getFixes;
127918         function getAllFixes(context) {
127919             // Currently fixId is always a string.
127920             return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context);
127921         }
127922         codefix.getAllFixes = getAllFixes;
127923         function createCombinedCodeActions(changes, commands) {
127924             return { changes: changes, commands: commands };
127925         }
127926         codefix.createCombinedCodeActions = createCombinedCodeActions;
127927         function createFileTextChanges(fileName, textChanges) {
127928             return { fileName: fileName, textChanges: textChanges };
127929         }
127930         codefix.createFileTextChanges = createFileTextChanges;
127931         function codeFixAll(context, errorCodes, use) {
127932             var commands = [];
127933             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); });
127934             return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands);
127935         }
127936         codefix.codeFixAll = codeFixAll;
127937         function eachDiagnostic(context, errorCodes, cb) {
127938             for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) {
127939                 var diag = _a[_i];
127940                 if (ts.contains(errorCodes, diag.code)) {
127941                     cb(diag);
127942                 }
127943             }
127944         }
127945         codefix.eachDiagnostic = eachDiagnostic;
127946         function getDiagnostics(_a) {
127947             var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken;
127948             return __spreadArrays(program.getSemanticDiagnostics(sourceFile, cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken));
127949         }
127950     })(codefix = ts.codefix || (ts.codefix = {}));
127951 })(ts || (ts = {}));
127952 /* @internal */
127953 var ts;
127954 (function (ts) {
127955     var refactor;
127956     (function (refactor_1) {
127957         // A map with the refactor code as key, the refactor itself as value
127958         // e.g.  nonSuggestableRefactors[refactorCode] -> the refactor you want
127959         var refactors = ts.createMap();
127960         /** @param name An unique code associated with each refactor. Does not have to be human-readable. */
127961         function registerRefactor(name, refactor) {
127962             refactors.set(name, refactor);
127963         }
127964         refactor_1.registerRefactor = registerRefactor;
127965         function getApplicableRefactors(context) {
127966             return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) {
127967                 return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context);
127968             }));
127969         }
127970         refactor_1.getApplicableRefactors = getApplicableRefactors;
127971         function getEditsForRefactor(context, refactorName, actionName) {
127972             var refactor = refactors.get(refactorName);
127973             return refactor && refactor.getEditsForAction(context, actionName);
127974         }
127975         refactor_1.getEditsForRefactor = getEditsForRefactor;
127976     })(refactor = ts.refactor || (ts.refactor = {}));
127977 })(ts || (ts = {}));
127978 /* @internal */
127979 var ts;
127980 (function (ts) {
127981     var codefix;
127982     (function (codefix) {
127983         var fixId = "addConvertToUnknownForNonOverlappingTypes";
127984         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];
127985         codefix.registerCodeFix({
127986             errorCodes: errorCodes,
127987             getCodeActions: function (context) {
127988                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
127989                 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)];
127990             },
127991             fixIds: [fixId],
127992             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
127993         });
127994         function makeChange(changeTracker, sourceFile, pos) {
127995             var token = ts.getTokenAtPosition(sourceFile, pos);
127996             var assertion = ts.Debug.checkDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); }), "Expected to find an assertion expression");
127997             var replacement = ts.isAsExpression(assertion)
127998                 ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(148 /* UnknownKeyword */))
127999                 : ts.createTypeAssertion(ts.createKeywordTypeNode(148 /* UnknownKeyword */), assertion.expression);
128000             changeTracker.replaceNode(sourceFile, assertion.expression, replacement);
128001         }
128002     })(codefix = ts.codefix || (ts.codefix = {}));
128003 })(ts || (ts = {}));
128004 /* @internal */
128005 var ts;
128006 (function (ts) {
128007     var codefix;
128008     (function (codefix) {
128009         codefix.registerCodeFix({
128010             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],
128011             getCodeActions: function (context) {
128012                 var sourceFile = context.sourceFile;
128013                 var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
128014                     var exportDeclaration = ts.createExportDeclaration(
128015                     /*decorators*/ undefined, 
128016                     /*modifiers*/ undefined, ts.createNamedExports([]), 
128017                     /*moduleSpecifier*/ undefined, 
128018                     /*isTypeOnly*/ false);
128019                     changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration);
128020                 });
128021                 return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)];
128022             },
128023         });
128024     })(codefix = ts.codefix || (ts.codefix = {}));
128025 })(ts || (ts = {}));
128026 /* @internal */
128027 var ts;
128028 (function (ts) {
128029     var codefix;
128030     (function (codefix) {
128031         var fixId = "addMissingAsync";
128032         var errorCodes = [
128033             ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
128034             ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
128035             ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code
128036         ];
128037         codefix.registerCodeFix({
128038             fixIds: [fixId],
128039             errorCodes: errorCodes,
128040             getCodeActions: function (context) {
128041                 var sourceFile = context.sourceFile, errorCode = context.errorCode, cancellationToken = context.cancellationToken, program = context.program, span = context.span;
128042                 var diagnostic = ts.find(program.getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode));
128043                 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; });
128044                 var decl = getFixableErrorSpanDeclaration(sourceFile, directSpan);
128045                 if (!decl) {
128046                     return;
128047                 }
128048                 var trackChanges = function (cb) { return ts.textChanges.ChangeTracker.with(context, cb); };
128049                 return [getFix(context, decl, trackChanges)];
128050             },
128051             getAllCodeActions: function (context) {
128052                 var sourceFile = context.sourceFile;
128053                 var fixedDeclarations = ts.createMap();
128054                 return codefix.codeFixAll(context, errorCodes, function (t, diagnostic) {
128055                     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; });
128056                     var decl = getFixableErrorSpanDeclaration(sourceFile, span);
128057                     if (!decl) {
128058                         return;
128059                     }
128060                     var trackChanges = function (cb) { return (cb(t), []); };
128061                     return getFix(context, decl, trackChanges, fixedDeclarations);
128062                 });
128063             },
128064         });
128065         function getFix(context, decl, trackChanges, fixedDeclarations) {
128066             var changes = trackChanges(function (t) { return makeChange(t, context.sourceFile, decl, fixedDeclarations); });
128067             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers);
128068         }
128069         function makeChange(changeTracker, sourceFile, insertionSite, fixedDeclarations) {
128070             if (fixedDeclarations) {
128071                 if (fixedDeclarations.has(ts.getNodeId(insertionSite).toString())) {
128072                     return;
128073                 }
128074             }
128075             fixedDeclarations === null || fixedDeclarations === void 0 ? void 0 : fixedDeclarations.set(ts.getNodeId(insertionSite).toString(), true);
128076             var cloneWithModifier = ts.getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true);
128077             cloneWithModifier.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(ts.getModifierFlags(insertionSite) | 256 /* Async */));
128078             cloneWithModifier.modifierFlagsCache = 0;
128079             changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier);
128080         }
128081         function getFixableErrorSpanDeclaration(sourceFile, span) {
128082             if (!span)
128083                 return undefined;
128084             var token = ts.getTokenAtPosition(sourceFile, span.start);
128085             // Checker has already done work to determine that async might be possible, and has attached
128086             // related info to the node, so start by finding the signature that exactly matches up
128087             // with the diagnostic range.
128088             var decl = ts.findAncestor(token, function (node) {
128089                 if (node.getStart(sourceFile) < span.start || node.getEnd() > ts.textSpanEnd(span)) {
128090                     return "quit";
128091                 }
128092                 return (ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node)) && ts.textSpansEqual(span, ts.createTextSpanFromNode(node, sourceFile));
128093             });
128094             return decl;
128095         }
128096         function getIsMatchingAsyncError(span, errorCode) {
128097             return function (_a) {
128098                 var start = _a.start, length = _a.length, relatedInformation = _a.relatedInformation, code = _a.code;
128099                 return ts.isNumber(start) && ts.isNumber(length) && ts.textSpansEqual({ start: start, length: length }, span) &&
128100                     code === errorCode &&
128101                     !!relatedInformation &&
128102                     ts.some(relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; });
128103             };
128104         }
128105     })(codefix = ts.codefix || (ts.codefix = {}));
128106 })(ts || (ts = {}));
128107 /* @internal */
128108 var ts;
128109 (function (ts) {
128110     var codefix;
128111     (function (codefix) {
128112         var fixId = "addMissingAwait";
128113         var propertyAccessCode = ts.Diagnostics.Property_0_does_not_exist_on_type_1.code;
128114         var callableConstructableErrorCodes = [
128115             ts.Diagnostics.This_expression_is_not_callable.code,
128116             ts.Diagnostics.This_expression_is_not_constructable.code,
128117         ];
128118         var errorCodes = __spreadArrays([
128119             ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code,
128120             ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
128121             ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code,
128122             ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code,
128123             ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code,
128124             ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code,
128125             ts.Diagnostics.Type_0_is_not_an_array_type.code,
128126             ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code,
128127             ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code,
128128             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,
128129             ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
128130             ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code,
128131             ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code,
128132             ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
128133             propertyAccessCode
128134         ], callableConstructableErrorCodes);
128135         codefix.registerCodeFix({
128136             fixIds: [fixId],
128137             errorCodes: errorCodes,
128138             getCodeActions: function (context) {
128139                 var sourceFile = context.sourceFile, errorCode = context.errorCode, span = context.span, cancellationToken = context.cancellationToken, program = context.program;
128140                 var expression = getFixableErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program);
128141                 if (!expression) {
128142                     return;
128143                 }
128144                 var checker = context.program.getTypeChecker();
128145                 var trackChanges = function (cb) { return ts.textChanges.ChangeTracker.with(context, cb); };
128146                 return ts.compact([
128147                     getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges),
128148                     getUseSiteFix(context, expression, errorCode, checker, trackChanges)
128149                 ]);
128150             },
128151             getAllCodeActions: function (context) {
128152                 var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
128153                 var checker = context.program.getTypeChecker();
128154                 var fixedDeclarations = ts.createMap();
128155                 return codefix.codeFixAll(context, errorCodes, function (t, diagnostic) {
128156                     var expression = getFixableErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program);
128157                     if (!expression) {
128158                         return;
128159                     }
128160                     var trackChanges = function (cb) { return (cb(t), []); };
128161                     return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations)
128162                         || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations);
128163                 });
128164             },
128165         });
128166         function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
128167             var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
128168             var awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker);
128169             if (awaitableInitializers) {
128170                 var initializerChanges = trackChanges(function (t) {
128171                     ts.forEach(awaitableInitializers.initializers, function (_a) {
128172                         var expression = _a.expression;
128173                         return makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
128174                     });
128175                     if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) {
128176                         makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations);
128177                     }
128178                 });
128179                 // No fix-all because it will already be included once with the use site fix,
128180                 // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes.
128181                 return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1
128182                     ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name]
128183                     : ts.Diagnostics.Add_await_to_initializers);
128184             }
128185         }
128186         function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) {
128187             var changes = trackChanges(function (t) { return makeChange(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations); });
128188             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_await, fixId, ts.Diagnostics.Fix_all_expressions_possibly_missing_await);
128189         }
128190         function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) {
128191             var checker = program.getDiagnosticsProducingTypeChecker();
128192             var diagnostics = checker.getDiagnostics(sourceFile, cancellationToken);
128193             return ts.some(diagnostics, function (_a) {
128194                 var start = _a.start, length = _a.length, relatedInformation = _a.relatedInformation, code = _a.code;
128195                 return ts.isNumber(start) && ts.isNumber(length) && ts.textSpansEqual({ start: start, length: length }, span) &&
128196                     code === errorCode &&
128197                     !!relatedInformation &&
128198                     ts.some(relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_forget_to_use_await.code; });
128199             });
128200         }
128201         function getFixableErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program) {
128202             var token = ts.getTokenAtPosition(sourceFile, span.start);
128203             // Checker has already done work to determine that await might be possible, and has attached
128204             // related info to the node, so start by finding the expression that exactly matches up
128205             // with the diagnostic range.
128206             var expression = ts.findAncestor(token, function (node) {
128207                 if (node.getStart(sourceFile) < span.start || node.getEnd() > ts.textSpanEnd(span)) {
128208                     return "quit";
128209                 }
128210                 return ts.isExpression(node) && ts.textSpansEqual(span, ts.createTextSpanFromNode(node, sourceFile));
128211             });
128212             return expression
128213                 && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program)
128214                 && isInsideAwaitableBody(expression) ? expression : undefined;
128215         }
128216         function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) {
128217             var identifiers = getIdentifiersFromErrorSpanExpression(expression, checker);
128218             if (!identifiers) {
128219                 return;
128220             }
128221             var isCompleteFix = identifiers.isCompleteFix;
128222             var initializers;
128223             var _loop_11 = function (identifier) {
128224                 var symbol = checker.getSymbolAtLocation(identifier);
128225                 if (!symbol) {
128226                     return "continue";
128227                 }
128228                 var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration);
128229                 var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier);
128230                 var variableStatement = ts.getAncestor(declaration, 225 /* VariableStatement */);
128231                 if (!declaration || !variableStatement ||
128232                     declaration.type ||
128233                     !declaration.initializer ||
128234                     variableStatement.getSourceFile() !== sourceFile ||
128235                     ts.hasModifier(variableStatement, 1 /* Export */) ||
128236                     !variableName ||
128237                     !isInsideAwaitableBody(declaration.initializer)) {
128238                     isCompleteFix = false;
128239                     return "continue";
128240                 }
128241                 var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken);
128242                 var isUsedElsewhere = ts.FindAllReferences.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, function (reference) {
128243                     return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker);
128244                 });
128245                 if (isUsedElsewhere) {
128246                     isCompleteFix = false;
128247                     return "continue";
128248                 }
128249                 (initializers || (initializers = [])).push({
128250                     expression: declaration.initializer,
128251                     declarationSymbol: symbol,
128252                 });
128253             };
128254             for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) {
128255                 var identifier = _a[_i];
128256                 _loop_11(identifier);
128257             }
128258             return initializers && {
128259                 initializers: initializers,
128260                 needsSecondPassForFixAll: !isCompleteFix,
128261             };
128262         }
128263         function getIdentifiersFromErrorSpanExpression(expression, checker) {
128264             if (ts.isPropertyAccessExpression(expression.parent) && ts.isIdentifier(expression.parent.expression)) {
128265                 return { identifiers: [expression.parent.expression], isCompleteFix: true };
128266             }
128267             if (ts.isIdentifier(expression)) {
128268                 return { identifiers: [expression], isCompleteFix: true };
128269             }
128270             if (ts.isBinaryExpression(expression)) {
128271                 var sides = void 0;
128272                 var isCompleteFix = true;
128273                 for (var _i = 0, _a = [expression.left, expression.right]; _i < _a.length; _i++) {
128274                     var side = _a[_i];
128275                     var type = checker.getTypeAtLocation(side);
128276                     if (checker.getPromisedTypeOfPromise(type)) {
128277                         if (!ts.isIdentifier(side)) {
128278                             isCompleteFix = false;
128279                             continue;
128280                         }
128281                         (sides || (sides = [])).push(side);
128282                     }
128283                 }
128284                 return sides && { identifiers: sides, isCompleteFix: isCompleteFix };
128285             }
128286         }
128287         function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) {
128288             var errorNode = ts.isPropertyAccessExpression(reference.parent) ? reference.parent.name :
128289                 ts.isBinaryExpression(reference.parent) ? reference.parent :
128290                     reference;
128291             var diagnostic = ts.find(diagnostics, function (diagnostic) {
128292                 return diagnostic.start === errorNode.getStart(sourceFile) &&
128293                     (diagnostic.start + diagnostic.length) === errorNode.getEnd();
128294             });
128295             return diagnostic && ts.contains(errorCodes, diagnostic.code) ||
128296                 // A Promise is usually not correct in a binary expression (it’s not valid
128297                 // in an arithmetic expression and an equality comparison seems unusual),
128298                 // but if the other side of the binary expression has an error, the side
128299                 // is typed `any` which will squash the error that would identify this
128300                 // Promise as an invalid operand. So if the whole binary expression is
128301                 // typed `any` as a result, there is a strong likelihood that this Promise
128302                 // is accidentally missing `await`.
128303                 checker.getTypeAtLocation(errorNode).flags & 1 /* Any */;
128304         }
128305         function isInsideAwaitableBody(node) {
128306             return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) {
128307                 return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor ||
128308                     ts.isBlock(ancestor) && (ancestor.parent.kind === 244 /* FunctionDeclaration */ ||
128309                         ancestor.parent.kind === 201 /* FunctionExpression */ ||
128310                         ancestor.parent.kind === 202 /* ArrowFunction */ ||
128311                         ancestor.parent.kind === 161 /* MethodDeclaration */);
128312             });
128313         }
128314         function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) {
128315             if (ts.isBinaryExpression(insertionSite)) {
128316                 for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) {
128317                     var side = _a[_i];
128318                     if (fixedDeclarations && ts.isIdentifier(side)) {
128319                         var symbol = checker.getSymbolAtLocation(side);
128320                         if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
128321                             continue;
128322                         }
128323                     }
128324                     var type = checker.getTypeAtLocation(side);
128325                     var newNode = checker.getPromisedTypeOfPromise(type) ? ts.createAwait(side) : side;
128326                     changeTracker.replaceNode(sourceFile, side, newNode);
128327                 }
128328             }
128329             else if (errorCode === propertyAccessCode && ts.isPropertyAccessExpression(insertionSite.parent)) {
128330                 if (fixedDeclarations && ts.isIdentifier(insertionSite.parent.expression)) {
128331                     var symbol = checker.getSymbolAtLocation(insertionSite.parent.expression);
128332                     if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
128333                         return;
128334                     }
128335                 }
128336                 changeTracker.replaceNode(sourceFile, insertionSite.parent.expression, ts.createParen(ts.createAwait(insertionSite.parent.expression)));
128337                 insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile);
128338             }
128339             else if (ts.contains(callableConstructableErrorCodes, errorCode) && ts.isCallOrNewExpression(insertionSite.parent)) {
128340                 if (fixedDeclarations && ts.isIdentifier(insertionSite)) {
128341                     var symbol = checker.getSymbolAtLocation(insertionSite);
128342                     if (symbol && fixedDeclarations.has(ts.getSymbolId(symbol).toString())) {
128343                         return;
128344                     }
128345                 }
128346                 changeTracker.replaceNode(sourceFile, insertionSite, ts.createParen(ts.createAwait(insertionSite)));
128347                 insertLeadingSemicolonIfNeeded(changeTracker, insertionSite, sourceFile);
128348             }
128349             else {
128350                 if (fixedDeclarations && ts.isVariableDeclaration(insertionSite.parent) && ts.isIdentifier(insertionSite.parent.name)) {
128351                     var symbol = checker.getSymbolAtLocation(insertionSite.parent.name);
128352                     if (symbol && !ts.addToSeen(fixedDeclarations, ts.getSymbolId(symbol))) {
128353                         return;
128354                     }
128355                 }
128356                 changeTracker.replaceNode(sourceFile, insertionSite, ts.createAwait(insertionSite));
128357             }
128358         }
128359         function insertLeadingSemicolonIfNeeded(changeTracker, beforeNode, sourceFile) {
128360             var precedingToken = ts.findPrecedingToken(beforeNode.pos, sourceFile);
128361             if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) {
128362                 changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";");
128363             }
128364         }
128365     })(codefix = ts.codefix || (ts.codefix = {}));
128366 })(ts || (ts = {}));
128367 /* @internal */
128368 var ts;
128369 (function (ts) {
128370     var codefix;
128371     (function (codefix) {
128372         var fixId = "addMissingConst";
128373         var errorCodes = [
128374             ts.Diagnostics.Cannot_find_name_0.code,
128375             ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code
128376         ];
128377         codefix.registerCodeFix({
128378             errorCodes: errorCodes,
128379             getCodeActions: function (context) {
128380                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start, context.program); });
128381                 if (changes.length > 0) {
128382                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_const_to_unresolved_variable, fixId, ts.Diagnostics.Add_const_to_all_unresolved_variables)];
128383                 }
128384             },
128385             fixIds: [fixId],
128386             getAllCodeActions: function (context) {
128387                 var fixedNodes = new ts.NodeSet();
128388                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start, context.program, fixedNodes); });
128389             },
128390         });
128391         function makeChange(changeTracker, sourceFile, pos, program, fixedNodes) {
128392             var token = ts.getTokenAtPosition(sourceFile, pos);
128393             var forInitializer = ts.findAncestor(token, function (node) {
128394                 return ts.isForInOrOfStatement(node.parent) ? node.parent.initializer === node :
128395                     isPossiblyPartOfDestructuring(node) ? false : "quit";
128396             });
128397             if (forInitializer)
128398                 return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes);
128399             var parent = token.parent;
128400             if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) {
128401                 return applyChange(changeTracker, token, sourceFile, fixedNodes);
128402             }
128403             if (ts.isArrayLiteralExpression(parent)) {
128404                 var checker_1 = program.getTypeChecker();
128405                 if (!ts.every(parent.elements, function (element) { return arrayElementCouldBeVariableDeclaration(element, checker_1); })) {
128406                     return;
128407                 }
128408                 return applyChange(changeTracker, parent, sourceFile, fixedNodes);
128409             }
128410             var commaExpression = ts.findAncestor(token, function (node) {
128411                 return ts.isExpressionStatement(node.parent) ? true :
128412                     isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit";
128413             });
128414             if (commaExpression) {
128415                 var checker = program.getTypeChecker();
128416                 if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) {
128417                     return;
128418                 }
128419                 return applyChange(changeTracker, commaExpression, sourceFile, fixedNodes);
128420             }
128421         }
128422         function applyChange(changeTracker, initializer, sourceFile, fixedNodes) {
128423             if (!fixedNodes || fixedNodes.tryAdd(initializer)) {
128424                 changeTracker.insertModifierBefore(sourceFile, 81 /* ConstKeyword */, initializer);
128425             }
128426         }
128427         function isPossiblyPartOfDestructuring(node) {
128428             switch (node.kind) {
128429                 case 75 /* Identifier */:
128430                 case 192 /* ArrayLiteralExpression */:
128431                 case 193 /* ObjectLiteralExpression */:
128432                 case 281 /* PropertyAssignment */:
128433                 case 282 /* ShorthandPropertyAssignment */:
128434                     return true;
128435                 default:
128436                     return false;
128437             }
128438         }
128439         function arrayElementCouldBeVariableDeclaration(expression, checker) {
128440             var identifier = ts.isIdentifier(expression) ? expression :
128441                 ts.isAssignmentExpression(expression, /*excludeCompoundAssignment*/ true) && ts.isIdentifier(expression.left) ? expression.left :
128442                     undefined;
128443             return !!identifier && !checker.getSymbolAtLocation(identifier);
128444         }
128445         function isPossiblyPartOfCommaSeperatedInitializer(node) {
128446             switch (node.kind) {
128447                 case 75 /* Identifier */:
128448                 case 209 /* BinaryExpression */:
128449                 case 27 /* CommaToken */:
128450                     return true;
128451                 default:
128452                     return false;
128453             }
128454         }
128455         function expressionCouldBeVariableDeclaration(expression, checker) {
128456             if (!ts.isBinaryExpression(expression)) {
128457                 return false;
128458             }
128459             if (expression.operatorToken.kind === 27 /* CommaToken */) {
128460                 return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); });
128461             }
128462             return expression.operatorToken.kind === 62 /* EqualsToken */
128463                 && ts.isIdentifier(expression.left)
128464                 && !checker.getSymbolAtLocation(expression.left);
128465         }
128466     })(codefix = ts.codefix || (ts.codefix = {}));
128467 })(ts || (ts = {}));
128468 /* @internal */
128469 var ts;
128470 (function (ts) {
128471     var codefix;
128472     (function (codefix) {
128473         var fixId = "addMissingDeclareProperty";
128474         var errorCodes = [
128475             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,
128476         ];
128477         codefix.registerCodeFix({
128478             errorCodes: errorCodes,
128479             getCodeActions: function (context) {
128480                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
128481                 if (changes.length > 0) {
128482                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Prefix_with_declare, fixId, ts.Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)];
128483                 }
128484             },
128485             fixIds: [fixId],
128486             getAllCodeActions: function (context) {
128487                 var fixedNodes = new ts.NodeSet();
128488                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start, fixedNodes); });
128489             },
128490         });
128491         function makeChange(changeTracker, sourceFile, pos, fixedNodes) {
128492             var token = ts.getTokenAtPosition(sourceFile, pos);
128493             if (!ts.isIdentifier(token)) {
128494                 return;
128495             }
128496             var declaration = token.parent;
128497             if (declaration.kind === 159 /* PropertyDeclaration */ &&
128498                 (!fixedNodes || fixedNodes.tryAdd(declaration))) {
128499                 changeTracker.insertModifierBefore(sourceFile, 130 /* DeclareKeyword */, declaration);
128500             }
128501         }
128502     })(codefix = ts.codefix || (ts.codefix = {}));
128503 })(ts || (ts = {}));
128504 /* @internal */
128505 var ts;
128506 (function (ts) {
128507     var codefix;
128508     (function (codefix) {
128509         var fixId = "addMissingInvocationForDecorator";
128510         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];
128511         codefix.registerCodeFix({
128512             errorCodes: errorCodes,
128513             getCodeActions: function (context) {
128514                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
128515                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)];
128516             },
128517             fixIds: [fixId],
128518             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
128519         });
128520         function makeChange(changeTracker, sourceFile, pos) {
128521             var token = ts.getTokenAtPosition(sourceFile, pos);
128522             var decorator = ts.findAncestor(token, ts.isDecorator);
128523             ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
128524             var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
128525             changeTracker.replaceNode(sourceFile, decorator.expression, replacement);
128526         }
128527     })(codefix = ts.codefix || (ts.codefix = {}));
128528 })(ts || (ts = {}));
128529 /* @internal */
128530 var ts;
128531 (function (ts) {
128532     var codefix;
128533     (function (codefix) {
128534         var fixId = "addNameToNamelessParameter";
128535         var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
128536         codefix.registerCodeFix({
128537             errorCodes: errorCodes,
128538             getCodeActions: function (context) {
128539                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
128540                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
128541             },
128542             fixIds: [fixId],
128543             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
128544         });
128545         function makeChange(changeTracker, sourceFile, pos) {
128546             var token = ts.getTokenAtPosition(sourceFile, pos);
128547             if (!ts.isIdentifier(token)) {
128548                 return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind));
128549             }
128550             var param = token.parent;
128551             if (!ts.isParameter(param)) {
128552                 return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind));
128553             }
128554             var i = param.parent.parameters.indexOf(param);
128555             ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
128556             ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
128557             var replacement = ts.createParameter(
128558             /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
128559             changeTracker.replaceNode(sourceFile, token, replacement);
128560         }
128561     })(codefix = ts.codefix || (ts.codefix = {}));
128562 })(ts || (ts = {}));
128563 /* @internal */
128564 var ts;
128565 (function (ts) {
128566     var codefix;
128567     (function (codefix) {
128568         var fixId = "annotateWithTypeFromJSDoc";
128569         var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
128570         codefix.registerCodeFix({
128571             errorCodes: errorCodes,
128572             getCodeActions: function (context) {
128573                 var decl = getDeclaration(context.sourceFile, context.span.start);
128574                 if (!decl)
128575                     return;
128576                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); });
128577                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)];
128578             },
128579             fixIds: [fixId],
128580             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
128581                 var decl = getDeclaration(diag.file, diag.start);
128582                 if (decl)
128583                     doChange(changes, diag.file, decl);
128584             }); },
128585         });
128586         function getDeclaration(file, pos) {
128587             var name = ts.getTokenAtPosition(file, pos);
128588             // For an arrow function with no name, 'name' lands on the first parameter.
128589             return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
128590         }
128591         function parameterShouldGetTypeFromJSDoc(node) {
128592             return isDeclarationWithType(node) && hasUsableJSDoc(node);
128593         }
128594         codefix.parameterShouldGetTypeFromJSDoc = parameterShouldGetTypeFromJSDoc;
128595         function hasUsableJSDoc(decl) {
128596             return ts.isFunctionLikeDeclaration(decl)
128597                 ? decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl))
128598                 : !decl.type && !!ts.getJSDocType(decl);
128599         }
128600         function doChange(changes, sourceFile, decl) {
128601             if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
128602                 if (!decl.typeParameters) {
128603                     var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
128604                     if (typeParameters.length)
128605                         changes.insertTypeParameters(sourceFile, decl, typeParameters);
128606                 }
128607                 var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 20 /* OpenParenToken */, sourceFile);
128608                 if (needParens)
128609                     changes.insertNodeBefore(sourceFile, ts.first(decl.parameters), ts.createToken(20 /* OpenParenToken */));
128610                 for (var _i = 0, _a = decl.parameters; _i < _a.length; _i++) {
128611                     var param = _a[_i];
128612                     if (!param.type) {
128613                         var paramType = ts.getJSDocType(param);
128614                         if (paramType)
128615                             changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType));
128616                     }
128617                 }
128618                 if (needParens)
128619                     changes.insertNodeAfter(sourceFile, ts.last(decl.parameters), ts.createToken(21 /* CloseParenToken */));
128620                 if (!decl.type) {
128621                     var returnType = ts.getJSDocReturnType(decl);
128622                     if (returnType)
128623                         changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType));
128624                 }
128625             }
128626             else {
128627                 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
128628                 ts.Debug.assert(!decl.type, "The JSDocType decl should have a type"); // If defined, shouldn't have been an error to fix.
128629                 changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType));
128630             }
128631         }
128632         function isDeclarationWithType(node) {
128633             return ts.isFunctionLikeDeclaration(node) ||
128634                 node.kind === 242 /* VariableDeclaration */ ||
128635                 node.kind === 158 /* PropertySignature */ ||
128636                 node.kind === 159 /* PropertyDeclaration */;
128637         }
128638         function transformJSDocType(node) {
128639             switch (node.kind) {
128640                 case 295 /* JSDocAllType */:
128641                 case 296 /* JSDocUnknownType */:
128642                     return ts.createTypeReferenceNode("any", ts.emptyArray);
128643                 case 299 /* JSDocOptionalType */:
128644                     return transformJSDocOptionalType(node);
128645                 case 298 /* JSDocNonNullableType */:
128646                     return transformJSDocType(node.type);
128647                 case 297 /* JSDocNullableType */:
128648                     return transformJSDocNullableType(node);
128649                 case 301 /* JSDocVariadicType */:
128650                     return transformJSDocVariadicType(node);
128651                 case 300 /* JSDocFunctionType */:
128652                     return transformJSDocFunctionType(node);
128653                 case 169 /* TypeReference */:
128654                     return transformJSDocTypeReference(node);
128655                 default:
128656                     var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217
128657                     ts.setEmitFlags(visited, 1 /* SingleLine */);
128658                     return visited;
128659             }
128660         }
128661         function transformJSDocOptionalType(node) {
128662             return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("undefined", ts.emptyArray)]);
128663         }
128664         function transformJSDocNullableType(node) {
128665             return ts.createUnionTypeNode([ts.visitNode(node.type, transformJSDocType), ts.createTypeReferenceNode("null", ts.emptyArray)]);
128666         }
128667         function transformJSDocVariadicType(node) {
128668             return ts.createArrayTypeNode(ts.visitNode(node.type, transformJSDocType));
128669         }
128670         function transformJSDocFunctionType(node) {
128671             return ts.createFunctionTypeNode(ts.emptyArray, node.parameters.map(transformJSDocParameter), node.type);
128672         }
128673         function transformJSDocParameter(node) {
128674             var index = node.parent.parameters.indexOf(node);
128675             var isRest = node.type.kind === 301 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
128676             var name = node.name || (isRest ? "rest" : "arg" + index);
128677             var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
128678             return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
128679         }
128680         function transformJSDocTypeReference(node) {
128681             var name = node.typeName;
128682             var args = node.typeArguments;
128683             if (ts.isIdentifier(node.typeName)) {
128684                 if (ts.isJSDocIndexSignature(node)) {
128685                     return transformJSDocIndexSignature(node);
128686                 }
128687                 var text = node.typeName.text;
128688                 switch (node.typeName.text) {
128689                     case "String":
128690                     case "Boolean":
128691                     case "Object":
128692                     case "Number":
128693                         text = text.toLowerCase();
128694                         break;
128695                     case "array":
128696                     case "date":
128697                     case "promise":
128698                         text = text[0].toUpperCase() + text.slice(1);
128699                         break;
128700                 }
128701                 name = ts.createIdentifier(text);
128702                 if ((text === "Array" || text === "Promise") && !node.typeArguments) {
128703                     args = ts.createNodeArray([ts.createTypeReferenceNode("any", ts.emptyArray)]);
128704                 }
128705                 else {
128706                     args = ts.visitNodes(node.typeArguments, transformJSDocType);
128707                 }
128708             }
128709             return ts.createTypeReferenceNode(name, args);
128710         }
128711         function transformJSDocIndexSignature(node) {
128712             var index = ts.createParameter(
128713             /*decorators*/ undefined, 
128714             /*modifiers*/ undefined, 
128715             /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 140 /* NumberKeyword */ ? "n" : "s", 
128716             /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 140 /* NumberKeyword */ ? "number" : "string", []), 
128717             /*initializer*/ undefined);
128718             var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]);
128719             ts.setEmitFlags(indexSignature, 1 /* SingleLine */);
128720             return indexSignature;
128721         }
128722     })(codefix = ts.codefix || (ts.codefix = {}));
128723 })(ts || (ts = {}));
128724 /* @internal */
128725 var ts;
128726 (function (ts) {
128727     var codefix;
128728     (function (codefix) {
128729         var fixId = "convertFunctionToEs6Class";
128730         var errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code];
128731         codefix.registerCodeFix({
128732             errorCodes: errorCodes,
128733             getCodeActions: function (context) {
128734                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); });
128735                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)];
128736             },
128737             fixIds: [fixId],
128738             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
128739         });
128740         function doChange(changes, sourceFile, position, checker) {
128741             var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position));
128742             if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
128743                 // Bad input
128744                 return undefined;
128745             }
128746             var ctorDeclaration = ctorSymbol.valueDeclaration;
128747             var precedingNode;
128748             var newClassDeclaration;
128749             switch (ctorDeclaration.kind) {
128750                 case 244 /* FunctionDeclaration */:
128751                     precedingNode = ctorDeclaration;
128752                     changes.delete(sourceFile, ctorDeclaration);
128753                     newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
128754                     break;
128755                 case 242 /* VariableDeclaration */:
128756                     precedingNode = ctorDeclaration.parent.parent;
128757                     newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
128758                     if (ctorDeclaration.parent.declarations.length === 1) {
128759                         ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
128760                         changes.delete(sourceFile, precedingNode);
128761                     }
128762                     else {
128763                         changes.delete(sourceFile, ctorDeclaration);
128764                     }
128765                     break;
128766             }
128767             if (!newClassDeclaration) {
128768                 return undefined;
128769             }
128770             // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node.
128771             if (ts.hasJSDocNodes(ctorDeclaration)) {
128772                 ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
128773             }
128774             // Because the preceding node could be touched, we need to insert nodes before delete nodes.
128775             changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
128776             function createClassElementsFromSymbol(symbol) {
128777                 var memberElements = [];
128778                 // all instance members are stored in the "member" array of symbol
128779                 if (symbol.members) {
128780                     symbol.members.forEach(function (member) {
128781                         var memberElement = createClassElement(member, /*modifiers*/ undefined);
128782                         if (memberElement) {
128783                             memberElements.push(memberElement);
128784                         }
128785                     });
128786                 }
128787                 // all static members are stored in the "exports" array of symbol
128788                 if (symbol.exports) {
128789                     symbol.exports.forEach(function (member) {
128790                         var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]);
128791                         if (memberElement) {
128792                             memberElements.push(memberElement);
128793                         }
128794                     });
128795                 }
128796                 return memberElements;
128797                 function shouldConvertDeclaration(_target, source) {
128798                     // Right now the only thing we can convert are function expressions - other values shouldn't get
128799                     // transformed. We can update this once ES public class properties are available.
128800                     return ts.isFunctionLike(source);
128801                 }
128802                 function createClassElement(symbol, modifiers) {
128803                     // Right now the only thing we can convert are function expressions, which are marked as methods
128804                     if (!(symbol.flags & 8192 /* Method */)) {
128805                         return;
128806                     }
128807                     var memberDeclaration = symbol.valueDeclaration;
128808                     var assignmentBinaryExpression = memberDeclaration.parent;
128809                     if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
128810                         return;
128811                     }
128812                     // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
128813                     var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */
128814                         ? assignmentBinaryExpression.parent : assignmentBinaryExpression;
128815                     changes.delete(sourceFile, nodeToDelete);
128816                     if (!assignmentBinaryExpression.right) {
128817                         return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, 
128818                         /*type*/ undefined, /*initializer*/ undefined);
128819                     }
128820                     switch (assignmentBinaryExpression.right.kind) {
128821                         case 201 /* FunctionExpression */: {
128822                             var functionExpression = assignmentBinaryExpression.right;
128823                             var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */));
128824                             var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, 
128825                             /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
128826                             ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
128827                             return method;
128828                         }
128829                         case 202 /* ArrowFunction */: {
128830                             var arrowFunction = assignmentBinaryExpression.right;
128831                             var arrowFunctionBody = arrowFunction.body;
128832                             var bodyBlock = void 0;
128833                             // case 1: () => { return [1,2,3] }
128834                             if (arrowFunctionBody.kind === 223 /* Block */) {
128835                                 bodyBlock = arrowFunctionBody;
128836                             }
128837                             // case 2: () => [1,2,3]
128838                             else {
128839                                 bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]);
128840                             }
128841                             var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */));
128842                             var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, 
128843                             /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
128844                             ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
128845                             return method;
128846                         }
128847                         default: {
128848                             // Don't try to declare members in JavaScript files
128849                             if (ts.isSourceFileJS(sourceFile)) {
128850                                 return;
128851                             }
128852                             var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, 
128853                             /*type*/ undefined, assignmentBinaryExpression.right);
128854                             ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
128855                             return prop;
128856                         }
128857                     }
128858                 }
128859             }
128860             function createClassFromVariableDeclaration(node) {
128861                 var initializer = node.initializer;
128862                 if (!initializer || initializer.kind !== 201 /* FunctionExpression */) {
128863                     return undefined;
128864                 }
128865                 if (node.name.kind !== 75 /* Identifier */) {
128866                     return undefined;
128867                 }
128868                 var memberElements = createClassElementsFromSymbol(node.symbol);
128869                 if (initializer.body) {
128870                     memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
128871                 }
128872                 var modifiers = getModifierKindFromSource(precedingNode, 89 /* ExportKeyword */);
128873                 var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, 
128874                 /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
128875                 // Don't call copyComments here because we'll already leave them in place
128876                 return cls;
128877             }
128878             function createClassFromFunctionDeclaration(node) {
128879                 var memberElements = createClassElementsFromSymbol(ctorSymbol);
128880                 if (node.body) {
128881                     memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
128882                 }
128883                 var modifiers = getModifierKindFromSource(node, 89 /* ExportKeyword */);
128884                 var cls = ts.createClassDeclaration(/*decorators*/ undefined, modifiers, node.name, 
128885                 /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
128886                 // Don't call copyComments here because we'll already leave them in place
128887                 return cls;
128888             }
128889         }
128890         function getModifierKindFromSource(source, kind) {
128891             return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; });
128892         }
128893     })(codefix = ts.codefix || (ts.codefix = {}));
128894 })(ts || (ts = {}));
128895 /* @internal */
128896 var ts;
128897 (function (ts) {
128898     var codefix;
128899     (function (codefix) {
128900         var fixId = "convertToAsyncFunction";
128901         var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code];
128902         var codeActionSucceeded = true;
128903         codefix.registerCodeFix({
128904             errorCodes: errorCodes,
128905             getCodeActions: function (context) {
128906                 codeActionSucceeded = true;
128907                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); });
128908                 return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : [];
128909             },
128910             fixIds: [fixId],
128911             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); },
128912         });
128913         var SynthBindingNameKind;
128914         (function (SynthBindingNameKind) {
128915             SynthBindingNameKind[SynthBindingNameKind["Identifier"] = 0] = "Identifier";
128916             SynthBindingNameKind[SynthBindingNameKind["BindingPattern"] = 1] = "BindingPattern";
128917         })(SynthBindingNameKind || (SynthBindingNameKind = {}));
128918         function convertToAsyncFunction(changes, sourceFile, position, checker, context) {
128919             // get the function declaration - returns a promise
128920             var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position);
128921             var functionToConvert;
128922             // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name
128923             if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) &&
128924                 tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) {
128925                 functionToConvert = tokenAtPosition.parent.initializer;
128926             }
128927             else {
128928                 functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration);
128929             }
128930             if (!functionToConvert) {
128931                 return;
128932             }
128933             var synthNamesMap = ts.createMap();
128934             var isInJavascript = ts.isInJSFile(functionToConvert);
128935             var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker);
128936             var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context.sourceFile);
128937             var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray;
128938             var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript };
128939             if (!returnStatements.length) {
128940                 return;
128941             }
128942             // add the async keyword
128943             changes.insertLastModifierBefore(sourceFile, 126 /* AsyncKeyword */, functionToConvert);
128944             var _loop_12 = function (returnStatement) {
128945                 ts.forEachChild(returnStatement, function visit(node) {
128946                     if (ts.isCallExpression(node)) {
128947                         var newNodes = transformExpression(node, transformer);
128948                         changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes);
128949                     }
128950                     else if (!ts.isFunctionLike(node)) {
128951                         ts.forEachChild(node, visit);
128952                     }
128953                 });
128954             };
128955             for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
128956                 var returnStatement = returnStatements_1[_i];
128957                 _loop_12(returnStatement);
128958             }
128959         }
128960         function getReturnStatementsWithPromiseHandlers(body) {
128961             var res = [];
128962             ts.forEachReturnStatement(body, function (ret) {
128963                 if (ts.isReturnStatementWithFixablePromiseHandler(ret))
128964                     res.push(ret);
128965             });
128966             return res;
128967         }
128968         /*
128969             Finds all of the expressions of promise type that should not be saved in a variable during the refactor
128970         */
128971         function getAllPromiseExpressionsToReturn(func, checker) {
128972             if (!func.body) {
128973                 return ts.createMap();
128974             }
128975             var setOfExpressionsToReturn = ts.createMap();
128976             ts.forEachChild(func.body, function visit(node) {
128977                 if (isPromiseReturningCallExpression(node, checker, "then")) {
128978                     setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
128979                     ts.forEach(node.arguments, visit);
128980                 }
128981                 else if (isPromiseReturningCallExpression(node, checker, "catch")) {
128982                     setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
128983                     // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned
128984                     ts.forEachChild(node, visit);
128985                 }
128986                 else if (isPromiseTypedExpression(node, checker)) {
128987                     setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true);
128988                     // don't recurse here, since we won't refactor any children or arguments of the expression
128989                 }
128990                 else {
128991                     ts.forEachChild(node, visit);
128992                 }
128993             });
128994             return setOfExpressionsToReturn;
128995         }
128996         function isPromiseReturningCallExpression(node, checker, name) {
128997             if (!ts.isCallExpression(node))
128998                 return false;
128999             var isExpressionOfName = ts.hasPropertyAccessExpressionWithName(node, name);
129000             var nodeType = isExpressionOfName && checker.getTypeAtLocation(node);
129001             return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType));
129002         }
129003         function isPromiseTypedExpression(node, checker) {
129004             if (!ts.isExpression(node))
129005                 return false;
129006             return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node));
129007         }
129008         function declaredInFile(symbol, sourceFile) {
129009             return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile;
129010         }
129011         /*
129012             Renaming of identifiers may be neccesary as the refactor changes scopes -
129013             This function collects all existing identifier names and names of identifiers that will be created in the refactor.
129014             It then checks for any collisions and renames them through getSynthesizedDeepClone
129015         */
129016         function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) {
129017             var identsToRenameMap = ts.createMap(); // key is the symbol id
129018             var collidingSymbolMap = ts.createMultiMap();
129019             ts.forEachChild(nodeToRename, function visit(node) {
129020                 if (!ts.isIdentifier(node)) {
129021                     ts.forEachChild(node, visit);
129022                     return;
129023                 }
129024                 var symbol = checker.getSymbolAtLocation(node);
129025                 var isDefinedInFile = symbol && declaredInFile(symbol, sourceFile);
129026                 if (symbol && isDefinedInFile) {
129027                     var type = checker.getTypeAtLocation(node);
129028                     // Note - the choice of the last call signature is arbitrary
129029                     var lastCallSignature = getLastCallSignature(type, checker);
129030                     var symbolIdString = ts.getSymbolId(symbol).toString();
129031                     // If the identifier refers to a function, we want to add the new synthesized variable for the declaration. Example:
129032                     //   fetch('...').then(response => { ... })
129033                     // will eventually become
129034                     //   const response = await fetch('...')
129035                     // so we push an entry for 'response'.
129036                     if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) {
129037                         var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters);
129038                         var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result");
129039                         var synthName = getNewNameIfConflict(ident, collidingSymbolMap);
129040                         synthNamesMap.set(symbolIdString, synthName);
129041                         collidingSymbolMap.add(ident.text, symbol);
129042                     }
129043                     // We only care about identifiers that are parameters, variable declarations, or binding elements
129044                     else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent) || ts.isBindingElement(node.parent))) {
129045                         var originalName = node.text;
129046                         var collidingSymbols = collidingSymbolMap.get(originalName);
129047                         // if the identifier name conflicts with a different identifier that we've already seen
129048                         if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) {
129049                             var newName = getNewNameIfConflict(node, collidingSymbolMap);
129050                             identsToRenameMap.set(symbolIdString, newName.identifier);
129051                             synthNamesMap.set(symbolIdString, newName);
129052                             collidingSymbolMap.add(originalName, symbol);
129053                         }
129054                         else {
129055                             var identifier = ts.getSynthesizedDeepClone(node);
129056                             synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier));
129057                             collidingSymbolMap.add(originalName, symbol);
129058                         }
129059                     }
129060                 }
129061             });
129062             return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker);
129063         }
129064         function getNewNameIfConflict(name, originalNames) {
129065             var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length;
129066             var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName);
129067             return createSynthIdentifier(identifier);
129068         }
129069         function silentFail() {
129070             codeActionSucceeded = false;
129071             return ts.emptyArray;
129072         }
129073         // dispatch function to recursively build the refactoring
129074         // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts
129075         function transformExpression(node, transformer, prevArgName) {
129076             if (isPromiseReturningCallExpression(node, transformer.checker, "then")) {
129077                 if (node.arguments.length === 0)
129078                     return silentFail();
129079                 return transformThen(node, transformer, prevArgName);
129080             }
129081             if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) {
129082                 if (node.arguments.length === 0)
129083                     return silentFail();
129084                 return transformCatch(node, transformer, prevArgName);
129085             }
129086             if (ts.isPropertyAccessExpression(node)) {
129087                 return transformExpression(node.expression, transformer, prevArgName);
129088             }
129089             var nodeType = transformer.checker.getTypeAtLocation(node);
129090             if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) {
129091                 ts.Debug.assertNode(node.original.parent, ts.isPropertyAccessExpression);
129092                 return transformPromiseExpressionOfPropertyAccess(node, transformer, prevArgName);
129093             }
129094             return silentFail();
129095         }
129096         function transformCatch(node, transformer, prevArgName) {
129097             var func = node.arguments[0];
129098             var argName = getArgBindingName(func, transformer);
129099             var possibleNameForVarDecl;
129100             /*
129101                 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)
129102                 To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap
129103                 We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step
129104             */
129105             if (prevArgName && !shouldReturn(node, transformer)) {
129106                 if (isSynthIdentifier(prevArgName)) {
129107                     possibleNameForVarDecl = prevArgName;
129108                     transformer.synthNamesMap.forEach(function (val, key) {
129109                         if (val.identifier.text === prevArgName.identifier.text) {
129110                             var newSynthName = createUniqueSynthName(prevArgName);
129111                             transformer.synthNamesMap.set(key, newSynthName);
129112                         }
129113                     });
129114                 }
129115                 else {
129116                     possibleNameForVarDecl = createSynthIdentifier(ts.createOptimisticUniqueName("result"), prevArgName.types);
129117                 }
129118                 // We are about to write a 'let' variable declaration, but `transformExpression` for both
129119                 // the try block and catch block will assign to this name. Setting this flag indicates
129120                 // that future assignments should be written as `name = value` instead of `const name = value`.
129121                 possibleNameForVarDecl.hasBeenDeclared = true;
129122             }
129123             var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, possibleNameForVarDecl));
129124             var transformationBody = getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer);
129125             var catchArg = argName ? isSynthIdentifier(argName) ? argName.identifier.text : argName.bindingPattern : "e";
129126             var catchVariableDeclaration = ts.createVariableDeclaration(catchArg);
129127             var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody));
129128             /*
129129                 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)
129130             */
129131             var varDeclList;
129132             var varDeclIdentifier;
129133             if (possibleNameForVarDecl && !shouldReturn(node, transformer)) {
129134                 varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier);
129135                 var typeArray = possibleNameForVarDecl.types;
129136                 var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */);
129137                 var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined);
129138                 var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)];
129139                 varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */));
129140             }
129141             var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined);
129142             var destructuredResult = prevArgName && varDeclIdentifier && isSynthBindingPattern(prevArgName)
129143                 && ts.createVariableStatement(/* modifiers */ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepCloneWithRenames(prevArgName.bindingPattern), /* type */ undefined, varDeclIdentifier)], 2 /* Const */));
129144             return ts.compact([varDeclList, tryStatement, destructuredResult]);
129145         }
129146         function createUniqueSynthName(prevArgName) {
129147             var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text);
129148             return createSynthIdentifier(renamedPrevArg);
129149         }
129150         function transformThen(node, transformer, prevArgName) {
129151             var _a = node.arguments, onFulfilled = _a[0], onRejected = _a[1];
129152             var onFulfilledArgumentName = getArgBindingName(onFulfilled, transformer);
129153             var transformationBody = getTransformationBody(onFulfilled, prevArgName, onFulfilledArgumentName, node, transformer);
129154             if (onRejected) {
129155                 var onRejectedArgumentName = getArgBindingName(onRejected, transformer);
129156                 var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, onFulfilledArgumentName).concat(transformationBody));
129157                 var transformationBody2 = getTransformationBody(onRejected, prevArgName, onRejectedArgumentName, node, transformer);
129158                 var catchArg = onRejectedArgumentName ? isSynthIdentifier(onRejectedArgumentName) ? onRejectedArgumentName.identifier.text : onRejectedArgumentName.bindingPattern : "e";
129159                 var catchVariableDeclaration = ts.createVariableDeclaration(catchArg);
129160                 var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody2));
129161                 return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)];
129162             }
129163             return transformExpression(node.expression, transformer, onFulfilledArgumentName).concat(transformationBody);
129164         }
129165         /**
129166          * Transforms the 'x' part of `x.then(...)`, or the 'y()' part of `y().catch(...)`, where 'x' and 'y()' are Promises.
129167          */
129168         function transformPromiseExpressionOfPropertyAccess(node, transformer, prevArgName) {
129169             if (shouldReturn(node, transformer)) {
129170                 return [ts.createReturn(ts.getSynthesizedDeepClone(node))];
129171             }
129172             return createVariableOrAssignmentOrExpressionStatement(prevArgName, ts.createAwait(node), /*typeAnnotation*/ undefined);
129173         }
129174         function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) {
129175             if (!variableName || isEmptyBindingName(variableName)) {
129176                 // if there's no argName to assign to, there still might be side effects
129177                 return [ts.createExpressionStatement(rightHandSide)];
129178             }
129179             if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) {
129180                 // if the variable has already been declared, we don't need "let" or "const"
129181                 return [ts.createExpressionStatement(ts.createAssignment(ts.getSynthesizedDeepClone(variableName.identifier), rightHandSide))];
129182             }
129183             return [
129184                 ts.createVariableStatement(
129185                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
129186                     ts.createVariableDeclaration(ts.getSynthesizedDeepClone(getNode(variableName)), typeAnnotation, rightHandSide)
129187                 ], 2 /* Const */))
129188             ];
129189         }
129190         function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) {
129191             if (typeAnnotation && expressionToReturn) {
129192                 var name = ts.createOptimisticUniqueName("result");
129193                 return __spreadArrays(createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), [
129194                     ts.createReturn(name)
129195                 ]);
129196             }
129197             return [ts.createReturn(expressionToReturn)];
129198         }
129199         // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts
129200         function getTransformationBody(func, prevArgName, argName, parent, transformer) {
129201             var _a, _b, _c, _d;
129202             switch (func.kind) {
129203                 case 100 /* NullKeyword */:
129204                     // do not produce a transformed statement for a null argument
129205                     break;
129206                 case 75 /* Identifier */: // identifier includes undefined
129207                     if (!argName) {
129208                         // undefined was argument passed to promise handler
129209                         break;
129210                     }
129211                     var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, isSynthIdentifier(argName) ? [argName.identifier] : []);
129212                     if (shouldReturn(parent, transformer)) {
129213                         return maybeAnnotateAndReturn(synthCall, (_a = parent.typeArguments) === null || _a === void 0 ? void 0 : _a[0]);
129214                     }
129215                     var type = transformer.checker.getTypeAtLocation(func);
129216                     var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */);
129217                     if (!callSignatures.length) {
129218                         // if identifier in handler has no call signatures, it's invalid
129219                         return silentFail();
129220                     }
129221                     var returnType = callSignatures[0].getReturnType();
129222                     var varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(prevArgName, ts.createAwait(synthCall), (_b = parent.typeArguments) === null || _b === void 0 ? void 0 : _b[0]);
129223                     if (prevArgName) {
129224                         prevArgName.types.push(returnType);
129225                     }
129226                     return varDeclOrAssignment;
129227                 case 201 /* FunctionExpression */:
129228                 case 202 /* ArrowFunction */: {
129229                     var funcBody = func.body;
129230                     // Arrow functions with block bodies { } will enter this control flow
129231                     if (ts.isBlock(funcBody)) {
129232                         var refactoredStmts = [];
129233                         var seenReturnStatement = false;
129234                         for (var _i = 0, _e = funcBody.statements; _i < _e.length; _i++) {
129235                             var statement = _e[_i];
129236                             if (ts.isReturnStatement(statement)) {
129237                                 seenReturnStatement = true;
129238                                 if (ts.isReturnStatementWithFixablePromiseHandler(statement)) {
129239                                     refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName));
129240                                 }
129241                                 else {
129242                                     refactoredStmts.push.apply(refactoredStmts, maybeAnnotateAndReturn(statement.expression, (_c = parent.typeArguments) === null || _c === void 0 ? void 0 : _c[0]));
129243                                 }
129244                             }
129245                             else {
129246                                 refactoredStmts.push(statement);
129247                             }
129248                         }
129249                         return shouldReturn(parent, transformer)
129250                             ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); })
129251                             : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement);
129252                     }
129253                     else {
129254                         var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray;
129255                         var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName);
129256                         if (innerCbBody.length > 0) {
129257                             return innerCbBody;
129258                         }
129259                         var type_1 = transformer.checker.getTypeAtLocation(func);
129260                         var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
129261                         var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
129262                         var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
129263                         if (!shouldReturn(parent, transformer)) {
129264                             var transformedStatement = createVariableOrAssignmentOrExpressionStatement(prevArgName, possiblyAwaitedRightHandSide, /*typeAnnotation*/ undefined);
129265                             if (prevArgName) {
129266                                 prevArgName.types.push(returnType_1);
129267                             }
129268                             return transformedStatement;
129269                         }
129270                         else {
129271                             return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, (_d = parent.typeArguments) === null || _d === void 0 ? void 0 : _d[0]);
129272                         }
129273                     }
129274                 }
129275                 default:
129276                     // 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.
129277                     return silentFail();
129278             }
129279             return ts.emptyArray;
129280         }
129281         function getLastCallSignature(type, checker) {
129282             var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */);
129283             return ts.lastOrUndefined(callSignatures);
129284         }
129285         function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) {
129286             var ret = [];
129287             for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) {
129288                 var stmt = stmts_1[_i];
129289                 if (ts.isReturnStatement(stmt)) {
129290                     if (stmt.expression) {
129291                         var possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression;
129292                         if (prevArgName === undefined) {
129293                             ret.push(ts.createExpressionStatement(possiblyAwaitedExpression));
129294                         }
129295                         else {
129296                             ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, possiblyAwaitedExpression)], 2 /* Const */))));
129297                         }
129298                     }
129299                 }
129300                 else {
129301                     ret.push(ts.getSynthesizedDeepClone(stmt));
129302                 }
129303             }
129304             // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables
129305             if (!seenReturnStatement && prevArgName !== undefined) {
129306                 ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, ts.createIdentifier("undefined"))], 2 /* Const */))));
129307             }
129308             return ret;
129309         }
129310         function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) {
129311             var innerCbBody = [];
129312             for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) {
129313                 var stmt = innerRetStmts_1[_i];
129314                 ts.forEachChild(stmt, function visit(node) {
129315                     if (ts.isCallExpression(node)) {
129316                         var temp = transformExpression(node, transformer, prevArgName);
129317                         innerCbBody = innerCbBody.concat(temp);
129318                         if (innerCbBody.length > 0) {
129319                             return;
129320                         }
129321                     }
129322                     else if (!ts.isFunctionLike(node)) {
129323                         ts.forEachChild(node, visit);
129324                     }
129325                 });
129326             }
129327             return innerCbBody;
129328         }
129329         function getArgBindingName(funcNode, transformer) {
129330             var types = [];
129331             var name;
129332             if (ts.isFunctionLikeDeclaration(funcNode)) {
129333                 if (funcNode.parameters.length > 0) {
129334                     var param = funcNode.parameters[0].name;
129335                     name = getMappedBindingNameOrDefault(param);
129336                 }
129337             }
129338             else if (ts.isIdentifier(funcNode)) {
129339                 name = getMapEntryOrDefault(funcNode);
129340             }
129341             // return undefined argName when arg is null or undefined
129342             // eslint-disable-next-line no-in-operator
129343             if (!name || "identifier" in name && name.identifier.text === "undefined") {
129344                 return undefined;
129345             }
129346             return name;
129347             function getMappedBindingNameOrDefault(bindingName) {
129348                 if (ts.isIdentifier(bindingName))
129349                     return getMapEntryOrDefault(bindingName);
129350                 var elements = ts.flatMap(bindingName.elements, function (element) {
129351                     if (ts.isOmittedExpression(element))
129352                         return [];
129353                     return [getMappedBindingNameOrDefault(element.name)];
129354                 });
129355                 return createSynthBindingPattern(bindingName, elements);
129356             }
129357             function getMapEntryOrDefault(identifier) {
129358                 var originalNode = getOriginalNode(identifier);
129359                 var symbol = getSymbol(originalNode);
129360                 if (!symbol) {
129361                     return createSynthIdentifier(identifier, types);
129362                 }
129363                 var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString());
129364                 return mapEntry || createSynthIdentifier(identifier, types);
129365             }
129366             function getSymbol(node) {
129367                 return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node);
129368             }
129369             function getOriginalNode(node) {
129370                 return node.original ? node.original : node;
129371             }
129372         }
129373         function isEmptyBindingName(bindingName) {
129374             if (!bindingName) {
129375                 return true;
129376             }
129377             if (isSynthIdentifier(bindingName)) {
129378                 return !bindingName.identifier.text;
129379             }
129380             return ts.every(bindingName.elements, isEmptyBindingName);
129381         }
129382         function getNode(bindingName) {
129383             return isSynthIdentifier(bindingName) ? bindingName.identifier : bindingName.bindingPattern;
129384         }
129385         function createSynthIdentifier(identifier, types) {
129386             if (types === void 0) { types = []; }
129387             return { kind: 0 /* Identifier */, identifier: identifier, types: types, hasBeenDeclared: false };
129388         }
129389         function createSynthBindingPattern(bindingPattern, elements, types) {
129390             if (elements === void 0) { elements = ts.emptyArray; }
129391             if (types === void 0) { types = []; }
129392             return { kind: 1 /* BindingPattern */, bindingPattern: bindingPattern, elements: elements, types: types };
129393         }
129394         function isSynthIdentifier(bindingName) {
129395             return bindingName.kind === 0 /* Identifier */;
129396         }
129397         function isSynthBindingPattern(bindingName) {
129398             return bindingName.kind === 1 /* BindingPattern */;
129399         }
129400         function shouldReturn(expression, transformer) {
129401             return !!expression.original && transformer.setOfExpressionsToReturn.has(ts.getNodeId(expression.original).toString());
129402         }
129403     })(codefix = ts.codefix || (ts.codefix = {}));
129404 })(ts || (ts = {}));
129405 /* @internal */
129406 var ts;
129407 (function (ts) {
129408     var codefix;
129409     (function (codefix) {
129410         codefix.registerCodeFix({
129411             errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],
129412             getCodeActions: function (context) {
129413                 var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences;
129414                 var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
129415                     var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences));
129416                     if (moduleExportsChangedToDefault) {
129417                         for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
129418                             var importingFile = _a[_i];
129419                             fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences));
129420                         }
129421                     }
129422                 });
129423                 // No support for fix-all since this applies to the whole file at once anyway.
129424                 return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)];
129425             },
129426         });
129427         function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) {
129428             for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) {
129429                 var moduleSpecifier = _a[_i];
129430                 var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text);
129431                 if (!imported || imported.resolvedFileName !== exportingFile.fileName) {
129432                     continue;
129433                 }
129434                 var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
129435                 switch (importNode.kind) {
129436                     case 253 /* ImportEqualsDeclaration */:
129437                         changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference));
129438                         break;
129439                     case 196 /* CallExpression */:
129440                         if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
129441                             changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default"));
129442                         }
129443                         break;
129444                 }
129445             }
129446         }
129447         /** @returns Whether we converted a `module.exports =` to a default export. */
129448         function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) {
129449             var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() };
129450             var exports = collectExportRenames(sourceFile, checker, identifiers);
129451             convertExportsAccesses(sourceFile, exports, changes);
129452             var moduleExportsChangedToDefault = false;
129453             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
129454                 var statement = _a[_i];
129455                 var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference);
129456                 moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged;
129457             }
129458             return moduleExportsChangedToDefault;
129459         }
129460         function collectExportRenames(sourceFile, checker, identifiers) {
129461             var res = ts.createMap();
129462             forEachExportReference(sourceFile, function (node) {
129463                 var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind;
129464                 if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind)
129465                     || checker.resolveName(text, node, 111551 /* Value */, /*excludeGlobals*/ true))) {
129466                     // Unconditionally add an underscore in case `text` is a keyword.
129467                     res.set(text, makeUniqueName("_" + text, identifiers));
129468                 }
129469             });
129470             return res;
129471         }
129472         function convertExportsAccesses(sourceFile, exports, changes) {
129473             forEachExportReference(sourceFile, function (node, isAssignmentLhs) {
129474                 if (isAssignmentLhs) {
129475                     return;
129476                 }
129477                 var text = node.name.text;
129478                 changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text));
129479             });
129480         }
129481         function forEachExportReference(sourceFile, cb) {
129482             sourceFile.forEachChild(function recur(node) {
129483                 if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && ts.isIdentifier(node.name)) {
129484                     var parent = node.parent;
129485                     cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 62 /* EqualsToken */);
129486                 }
129487                 node.forEachChild(recur);
129488             });
129489         }
129490         function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) {
129491             switch (statement.kind) {
129492                 case 225 /* VariableStatement */:
129493                     convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
129494                     return false;
129495                 case 226 /* ExpressionStatement */: {
129496                     var expression = statement.expression;
129497                     switch (expression.kind) {
129498                         case 196 /* CallExpression */: {
129499                             if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
129500                                 // For side-effecting require() call, just make a side-effecting import.
129501                                 changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference));
129502                             }
129503                             return false;
129504                         }
129505                         case 209 /* BinaryExpression */: {
129506                             var operatorToken = expression.operatorToken;
129507                             return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports);
129508                         }
129509                     }
129510                 }
129511                 // falls through
129512                 default:
129513                     return false;
129514             }
129515         }
129516         function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) {
129517             var declarationList = statement.declarationList;
129518             var foundImport = false;
129519             var newNodes = ts.flatMap(declarationList.declarations, function (decl) {
129520                 var name = decl.name, initializer = decl.initializer;
129521                 if (initializer) {
129522                     if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) {
129523                         // `const alias = module.exports;` can be removed.
129524                         foundImport = true;
129525                         return [];
129526                     }
129527                     else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
129528                         foundImport = true;
129529                         return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference);
129530                     }
129531                     else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) {
129532                         foundImport = true;
129533                         return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference);
129534                     }
129535                 }
129536                 // Move it out to its own variable statement. (This will not be used if `!foundImport`)
129537                 return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags));
129538             });
129539             if (foundImport) {
129540                 // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement.
129541                 changes.replaceNodeWithNodes(sourceFile, statement, newNodes);
129542             }
129543         }
129544         /** Converts `const name = require("moduleSpecifier").propertyName` */
129545         function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
129546             switch (name.kind) {
129547                 case 189 /* ObjectBindingPattern */:
129548                 case 190 /* ArrayBindingPattern */: {
129549                     // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
129550                     var tmp = makeUniqueName(propertyName, identifiers);
129551                     return [
129552                         makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference),
129553                         makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)),
129554                     ];
129555                 }
129556                 case 75 /* Identifier */:
129557                     // `const a = require("b").c` --> `import { c as a } from "./b";
129558                     return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)];
129559                 default:
129560                     return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind);
129561             }
129562         }
129563         function convertAssignment(sourceFile, checker, assignment, changes, exports) {
129564             var left = assignment.left, right = assignment.right;
129565             if (!ts.isPropertyAccessExpression(left)) {
129566                 return false;
129567             }
129568             if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
129569                 if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
129570                     // `const alias = module.exports;` or `module.exports = alias;` can be removed.
129571                     changes.delete(sourceFile, assignment.parent);
129572                 }
129573                 else {
129574                     var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
129575                         : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
129576                             : undefined;
129577                     if (replacement) {
129578                         changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
129579                         return replacement[1];
129580                     }
129581                     else {
129582                         changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default");
129583                         return true;
129584                     }
129585                 }
129586             }
129587             else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
129588                 convertNamedExport(sourceFile, assignment, changes, exports);
129589             }
129590             return false;
129591         }
129592         /**
129593          * Convert `module.exports = { ... }` to individual exports..
129594          * We can't always do this if the module has interesting members -- then it will be a default export instead.
129595          */
129596         function tryChangeModuleExportsObject(object) {
129597             var statements = ts.mapAllOrFail(object.properties, function (prop) {
129598                 switch (prop.kind) {
129599                     case 163 /* GetAccessor */:
129600                     case 164 /* SetAccessor */:
129601                     // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
129602                     // falls through
129603                     case 282 /* ShorthandPropertyAssignment */:
129604                     case 283 /* SpreadAssignment */:
129605                         return undefined;
129606                     case 281 /* PropertyAssignment */:
129607                         return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer);
129608                     case 161 /* MethodDeclaration */:
129609                         return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(89 /* ExportKeyword */)], prop);
129610                     default:
129611                         ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind);
129612                 }
129613             });
129614             return statements && [statements, false];
129615         }
129616         function convertNamedExport(sourceFile, assignment, changes, exports) {
129617             // If "originalKeywordKind" was set, this is e.g. `exports.
129618             var text = assignment.left.name.text;
129619             var rename = exports.get(text);
129620             if (rename !== undefined) {
129621                 /*
129622                 const _class = 0;
129623                 export { _class as class };
129624                 */
129625                 var newNodes = [
129626                     makeConst(/*modifiers*/ undefined, rename, assignment.right),
129627                     makeExportDeclaration([ts.createExportSpecifier(rename, text)]),
129628                 ];
129629                 changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
129630             }
129631             else {
129632                 convertExportsPropertyAssignment(assignment, sourceFile, changes);
129633             }
129634         }
129635         function convertReExportAll(reExported, checker) {
129636             // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
129637             var moduleSpecifier = reExported.text;
129638             var moduleSymbol = checker.getSymbolAtLocation(reExported);
129639             var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap;
129640             return exports.has("export=") ? [[reExportDefault(moduleSpecifier)], true] :
129641                 !exports.has("default") ? [[reExportStar(moduleSpecifier)], false] :
129642                     // If there's some non-default export, must include both `export *` and `export default`.
129643                     exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true];
129644         }
129645         function reExportStar(moduleSpecifier) {
129646             return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier);
129647         }
129648         function reExportDefault(moduleSpecifier) {
129649             return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier);
129650         }
129651         function convertExportsPropertyAssignment(_a, sourceFile, changes) {
129652             var left = _a.left, right = _a.right, parent = _a.parent;
129653             var name = left.name.text;
129654             if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) {
129655                 // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`.
129656                 changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(89 /* ExportKeyword */), { suffix: " " });
129657                 if (!right.name)
129658                     changes.insertName(sourceFile, right, name);
129659                 var semi = ts.findChildOfKind(parent, 26 /* SemicolonToken */, sourceFile);
129660                 if (semi)
129661                     changes.delete(sourceFile, semi);
129662             }
129663             else {
129664                 // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const `
129665                 changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 24 /* DotToken */, sourceFile), [ts.createToken(89 /* ExportKeyword */), ts.createToken(81 /* ConstKeyword */)], { joiner: " ", suffix: " " });
129666             }
129667         }
129668         // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node.
129669         function convertExportsDotXEquals_replaceNode(name, exported) {
129670             var modifiers = [ts.createToken(89 /* ExportKeyword */)];
129671             switch (exported.kind) {
129672                 case 201 /* FunctionExpression */: {
129673                     var expressionName = exported.name;
129674                     if (expressionName && expressionName.text !== name) {
129675                         // `exports.f = function g() {}` -> `export const f = function g() {}`
129676                         return exportConst();
129677                     }
129678                 }
129679                 // falls through
129680                 case 202 /* ArrowFunction */:
129681                     // `exports.f = function() {}` --> `export function f() {}`
129682                     return functionExpressionToDeclaration(name, modifiers, exported);
129683                 case 214 /* ClassExpression */:
129684                     // `exports.C = class {}` --> `export class C {}`
129685                     return classExpressionToDeclaration(name, modifiers, exported);
129686                 default:
129687                     return exportConst();
129688             }
129689             function exportConst() {
129690                 // `exports.x = 0;` --> `export const x = 0;`
129691                 return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217
129692             }
129693         }
129694         /**
129695          * Converts `const <<name>> = require("x");`.
129696          * Returns nodes that will replace the variable declaration for the commonjs import.
129697          * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`.
129698          */
129699         function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) {
129700             switch (name.kind) {
129701                 case 189 /* ObjectBindingPattern */: {
129702                     var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
129703                         return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
129704                             ? undefined
129705                             // (TODO: GH#18217)
129706                             // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
129707                             : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
129708                     });
129709                     if (importSpecifiers) {
129710                         return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)];
129711                     }
129712                 }
129713                 // falls through -- object destructuring has an interesting pattern and must be a variable declaration
129714                 case 190 /* ArrayBindingPattern */: {
129715                     /*
129716                     import x from "x";
129717                     const [a, b, c] = x;
129718                     */
129719                     var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
129720                     return [
129721                         ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference),
129722                         makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
129723                     ];
129724                 }
129725                 case 75 /* Identifier */:
129726                     return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference);
129727                 default:
129728                     return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind);
129729             }
129730         }
129731         /**
129732          * Convert `import x = require("x").`
129733          * Also converts uses like `x.y()` to `y()` and uses a named import.
129734          */
129735         function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) {
129736             var nameSymbol = checker.getSymbolAtLocation(name);
129737             // Maps from module property name to name actually used. (The same if there isn't shadowing.)
129738             var namedBindingsNames = ts.createMap();
129739             // True if there is some non-property use like `x()` or `f(x)`.
129740             var needDefaultImport = false;
129741             for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) {
129742                 var use = _a[_i];
129743                 if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) {
129744                     // This was a use of a different symbol with the same name, due to shadowing. Ignore.
129745                     continue;
129746                 }
129747                 var parent = use.parent;
129748                 if (ts.isPropertyAccessExpression(parent)) {
129749                     var expression = parent.expression, propertyName = parent.name.text;
129750                     ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers`
129751                     var idName = namedBindingsNames.get(propertyName);
129752                     if (idName === undefined) {
129753                         idName = makeUniqueName(propertyName, identifiers);
129754                         namedBindingsNames.set(propertyName, idName);
129755                     }
129756                     changes.replaceNode(file, parent, ts.createIdentifier(idName));
129757                 }
129758                 else {
129759                     needDefaultImport = true;
129760                 }
129761             }
129762             var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) {
129763                 var propertyName = _a[0], idName = _a[1];
129764                 return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName));
129765             }));
129766             if (!namedBindings) {
129767                 // If it was unused, ensure that we at least import *something*.
129768                 needDefaultImport = true;
129769             }
129770             return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)];
129771         }
129772         // Identifiers helpers
129773         function makeUniqueName(name, identifiers) {
129774             while (identifiers.original.has(name) || identifiers.additional.has(name)) {
129775                 name = "_" + name;
129776             }
129777             identifiers.additional.set(name, true);
129778             return name;
129779         }
129780         function collectFreeIdentifiers(file) {
129781             var map = ts.createMultiMap();
129782             forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); });
129783             return map;
129784         }
129785         /**
129786          * A free identifier is an identifier that can be accessed through name lookup as a local variable.
129787          * In the expression `x.y`, `x` is a free identifier, but `y` is not.
129788          */
129789         function forEachFreeIdentifier(node, cb) {
129790             if (ts.isIdentifier(node) && isFreeIdentifier(node))
129791                 cb(node);
129792             node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); });
129793         }
129794         function isFreeIdentifier(node) {
129795             var parent = node.parent;
129796             switch (parent.kind) {
129797                 case 194 /* PropertyAccessExpression */:
129798                     return parent.name !== node;
129799                 case 191 /* BindingElement */:
129800                     return parent.propertyName !== node;
129801                 case 258 /* ImportSpecifier */:
129802                     return parent.propertyName !== node;
129803                 default:
129804                     return true;
129805             }
129806         }
129807         // Node helpers
129808         function functionExpressionToDeclaration(name, additionalModifiers, fn) {
129809             return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal.
129810             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)));
129811         }
129812         function classExpressionToDeclaration(name, additionalModifiers, cls) {
129813             return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal.
129814             ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members));
129815         }
129816         function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) {
129817             return propertyName === "default"
129818                 ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference)
129819                 : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference);
129820         }
129821         function makeImportSpecifier(propertyName, name) {
129822             return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
129823         }
129824         function makeConst(modifiers, name, init) {
129825             return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */));
129826         }
129827         function makeExportDeclaration(exportSpecifiers, moduleSpecifier) {
129828             return ts.createExportDeclaration(
129829             /*decorators*/ undefined, 
129830             /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier));
129831         }
129832     })(codefix = ts.codefix || (ts.codefix = {}));
129833 })(ts || (ts = {}));
129834 /* @internal */
129835 var ts;
129836 (function (ts) {
129837     var codefix;
129838     (function (codefix) {
129839         var fixId = "correctQualifiedNameToIndexedAccessType";
129840         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];
129841         codefix.registerCodeFix({
129842             errorCodes: errorCodes,
129843             getCodeActions: function (context) {
129844                 var qualifiedName = getQualifiedName(context.sourceFile, context.span.start);
129845                 if (!qualifiedName)
129846                     return undefined;
129847                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); });
129848                 var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]";
129849                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)];
129850             },
129851             fixIds: [fixId],
129852             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129853                 var q = getQualifiedName(diag.file, diag.start);
129854                 if (q) {
129855                     doChange(changes, diag.file, q);
129856                 }
129857             }); },
129858         });
129859         function getQualifiedName(sourceFile, pos) {
129860             var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName);
129861             ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
129862             return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined;
129863         }
129864         function doChange(changeTracker, sourceFile, qualifiedName) {
129865             var rightText = qualifiedName.right.text;
129866             var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText)));
129867             changeTracker.replaceNode(sourceFile, qualifiedName, replacement);
129868         }
129869     })(codefix = ts.codefix || (ts.codefix = {}));
129870 })(ts || (ts = {}));
129871 /* @internal */
129872 var ts;
129873 (function (ts) {
129874     var codefix;
129875     (function (codefix) {
129876         var errorCodes = [ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type.code];
129877         var fixId = "convertToTypeOnlyExport";
129878         codefix.registerCodeFix({
129879             errorCodes: errorCodes,
129880             getCodeActions: function (context) {
129881                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context); });
129882                 if (changes.length) {
129883                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_export, fixId, ts.Diagnostics.Convert_all_re_exported_types_to_type_only_exports)];
129884                 }
129885             },
129886             fixIds: [fixId],
129887             getAllCodeActions: function (context) {
129888                 var fixedExportDeclarations = ts.createMap();
129889                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129890                     var exportSpecifier = getExportSpecifierForDiagnosticSpan(diag, context.sourceFile);
129891                     if (exportSpecifier && !ts.addToSeen(fixedExportDeclarations, ts.getNodeId(exportSpecifier.parent.parent))) {
129892                         fixSingleExportDeclaration(changes, exportSpecifier, context);
129893                     }
129894                 });
129895             }
129896         });
129897         function getExportSpecifierForDiagnosticSpan(span, sourceFile) {
129898             return ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start).parent, ts.isExportSpecifier);
129899         }
129900         function fixSingleExportDeclaration(changes, exportSpecifier, context) {
129901             if (!exportSpecifier) {
129902                 return;
129903             }
129904             var exportClause = exportSpecifier.parent;
129905             var exportDeclaration = exportClause.parent;
129906             var typeExportSpecifiers = getTypeExportSpecifiers(exportSpecifier, context);
129907             if (typeExportSpecifiers.length === exportClause.elements.length) {
129908                 changes.replaceNode(context.sourceFile, exportDeclaration, ts.updateExportDeclaration(exportDeclaration, exportDeclaration.decorators, exportDeclaration.modifiers, exportClause, exportDeclaration.moduleSpecifier, 
129909                 /*isTypeOnly*/ true));
129910             }
129911             else {
129912                 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, 
129913                 /*isTypeOnly*/ false);
129914                 var typeExportDeclaration = ts.createExportDeclaration(
129915                 /*decorators*/ undefined, 
129916                 /*modifiers*/ undefined, ts.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, 
129917                 /*isTypeOnly*/ true);
129918                 changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration);
129919                 changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration);
129920             }
129921         }
129922         function getTypeExportSpecifiers(originExportSpecifier, context) {
129923             var exportClause = originExportSpecifier.parent;
129924             if (exportClause.elements.length === 1) {
129925                 return exportClause.elements;
129926             }
129927             var diagnostics = ts.getDiagnosticsWithinSpan(ts.createTextSpanFromNode(exportClause), context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken));
129928             return ts.filter(exportClause.elements, function (element) {
129929                 var _a;
129930                 return element === originExportSpecifier || ((_a = ts.findDiagnosticForNode(element, diagnostics)) === null || _a === void 0 ? void 0 : _a.code) === errorCodes[0];
129931             });
129932         }
129933     })(codefix = ts.codefix || (ts.codefix = {}));
129934 })(ts || (ts = {}));
129935 /* @internal */
129936 var ts;
129937 (function (ts) {
129938     var codefix;
129939     (function (codefix) {
129940         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];
129941         var fixId = "convertToTypeOnlyImport";
129942         codefix.registerCodeFix({
129943             errorCodes: errorCodes,
129944             getCodeActions: function (context) {
129945                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
129946                     var importDeclaration = getImportDeclarationForDiagnosticSpan(context.span, context.sourceFile);
129947                     fixSingleImportDeclaration(t, importDeclaration, context);
129948                 });
129949                 if (changes.length) {
129950                     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)];
129951                 }
129952             },
129953             fixIds: [fixId],
129954             getAllCodeActions: function (context) {
129955                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
129956                     var importDeclaration = getImportDeclarationForDiagnosticSpan(diag, context.sourceFile);
129957                     fixSingleImportDeclaration(changes, importDeclaration, context);
129958                 });
129959             }
129960         });
129961         function getImportDeclarationForDiagnosticSpan(span, sourceFile) {
129962             return ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start).parent, ts.isImportDeclaration);
129963         }
129964         function fixSingleImportDeclaration(changes, importDeclaration, context) {
129965             if (!(importDeclaration === null || importDeclaration === void 0 ? void 0 : importDeclaration.importClause)) {
129966                 return;
129967             }
129968             var importClause = importDeclaration.importClause;
129969             // `changes.insertModifierBefore` produces a range that might overlap further changes
129970             changes.insertText(context.sourceFile, importDeclaration.getStart() + "import".length, " type");
129971             // `import type foo, { Bar }` is not allowed, so move `foo` to new declaration
129972             if (importClause.name && importClause.namedBindings) {
129973                 changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings);
129974                 changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, 
129975                 /*decorators*/ undefined, 
129976                 /*modifiers*/ undefined, ts.createImportClause(importClause.name, 
129977                 /*namedBindings*/ undefined, 
129978                 /*isTypeOnly*/ true), importDeclaration.moduleSpecifier));
129979             }
129980         }
129981     })(codefix = ts.codefix || (ts.codefix = {}));
129982 })(ts || (ts = {}));
129983 /* @internal */
129984 var ts;
129985 (function (ts) {
129986     var codefix;
129987     (function (codefix) {
129988         var errorCodes = [
129989             ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code,
129990             ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code
129991         ];
129992         var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember?
129993         codefix.registerCodeFix({
129994             errorCodes: errorCodes,
129995             getCodeActions: function (context) {
129996                 var sourceFile = context.sourceFile, span = context.span;
129997                 var classDeclaration = getClass(sourceFile, span.start);
129998                 return ts.mapDefined(ts.getEffectiveImplementsTypeNodes(classDeclaration), function (implementedTypeNode) {
129999                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); });
130000                     return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces);
130001                 });
130002             },
130003             fixIds: [fixId],
130004             getAllCodeActions: function (context) {
130005                 var seenClassDeclarations = ts.createMap();
130006                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
130007                     var classDeclaration = getClass(diag.file, diag.start);
130008                     if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
130009                         for (var _i = 0, _a = ts.getEffectiveImplementsTypeNodes(classDeclaration); _i < _a.length; _i++) {
130010                             var implementedTypeNode = _a[_i];
130011                             addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences);
130012                         }
130013                     }
130014                 });
130015             },
130016         });
130017         function getClass(sourceFile, pos) {
130018             return ts.Debug.checkDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
130019         }
130020         function symbolPointsToNonPrivateMember(symbol) {
130021             return !symbol.valueDeclaration || !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */);
130022         }
130023         function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) {
130024             var checker = context.program.getTypeChecker();
130025             var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
130026             // Note that this is ultimately derived from a map indexed by symbol names,
130027             // so duplicates cannot occur.
130028             var implementedType = checker.getTypeAtLocation(implementedTypeNode);
130029             var implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
130030             var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); }));
130031             var classType = checker.getTypeAtLocation(classDeclaration);
130032             var constructor = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m); });
130033             if (!classType.getNumberIndexType()) {
130034                 createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */);
130035             }
130036             if (!classType.getStringIndexType()) {
130037                 createMissingIndexSignatureDeclaration(implementedType, 0 /* String */);
130038             }
130039             var importAdder = codefix.createImportAdder(sourceFile, context.program, preferences, context.host);
130040             codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, importAdder, function (member) { return insertInterfaceMemberNode(sourceFile, classDeclaration, member); });
130041             importAdder.writeFixes(changeTracker);
130042             function createMissingIndexSignatureDeclaration(type, kind) {
130043                 var indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
130044                 if (indexInfoOfKind) {
130045                     insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context)));
130046                 }
130047             }
130048             // Either adds the node at the top of the class, or if there's a constructor right after that
130049             function insertInterfaceMemberNode(sourceFile, cls, newElement) {
130050                 if (constructor) {
130051                     changeTracker.insertNodeAfter(sourceFile, constructor, newElement);
130052                 }
130053                 else {
130054                     changeTracker.insertNodeAtClassStart(sourceFile, cls, newElement);
130055                 }
130056             }
130057         }
130058         function getHeritageClauseSymbolTable(classDeclaration, checker) {
130059             var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration);
130060             if (!heritageClauseNode)
130061                 return ts.createSymbolTable();
130062             var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
130063             var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType);
130064             return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember));
130065         }
130066     })(codefix = ts.codefix || (ts.codefix = {}));
130067 })(ts || (ts = {}));
130068 /* @internal */
130069 var ts;
130070 (function (ts) {
130071     var codefix;
130072     (function (codefix) {
130073         codefix.importFixName = "import";
130074         var importFixId = "fixMissingImport";
130075         var errorCodes = [
130076             ts.Diagnostics.Cannot_find_name_0.code,
130077             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
130078             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
130079             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
130080             ts.Diagnostics.Cannot_find_namespace_0.code,
130081             ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
130082             ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
130083         ];
130084         codefix.registerCodeFix({
130085             errorCodes: errorCodes,
130086             getCodeActions: function (context) {
130087                 var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span;
130088                 var info = getFixesInfo(context, errorCode, span.start);
130089                 if (!info)
130090                     return undefined;
130091                 var fixes = info.fixes, symbolName = info.symbolName;
130092                 var quotePreference = ts.getQuotePreference(sourceFile, preferences);
130093                 return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); });
130094             },
130095             fixIds: [importFixId],
130096             getAllCodeActions: function (context) {
130097                 var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences, host = context.host;
130098                 var importAdder = createImportAdder(sourceFile, program, preferences, host);
130099                 codefix.eachDiagnostic(context, errorCodes, function (diag) { return importAdder.addImportFromDiagnostic(diag, context); });
130100                 return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, importAdder.writeFixes));
130101             },
130102         });
130103         function createImportAdder(sourceFile, program, preferences, host) {
130104             var compilerOptions = program.getCompilerOptions();
130105             // Namespace fixes don't conflict, so just build a list.
130106             var addToNamespace = [];
130107             var importType = [];
130108             // Keys are import clause node IDs.
130109             var addToExisting = ts.createMap();
130110             var newImports = ts.createMap();
130111             return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes };
130112             function addImportFromDiagnostic(diagnostic, context) {
130113                 var info = getFixesInfo(context, diagnostic.code, diagnostic.start);
130114                 if (!info || !info.fixes.length)
130115                     return;
130116                 addImport(info);
130117             }
130118             function addImportFromExportedSymbol(exportedSymbol, usageIsTypeOnly) {
130119                 var moduleSymbol = ts.Debug.checkDefined(exportedSymbol.parent);
130120                 var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions));
130121                 var checker = program.getTypeChecker();
130122                 var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker));
130123                 var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles());
130124                 var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */;
130125                 var useRequire = shouldUseRequire(sourceFile, compilerOptions);
130126                 var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences);
130127                 addImport({ fixes: [fix], symbolName: symbolName });
130128             }
130129             function addImport(info) {
130130                 var fixes = info.fixes, symbolName = info.symbolName;
130131                 var fix = ts.first(fixes);
130132                 switch (fix.kind) {
130133                     case 0 /* UseNamespace */:
130134                         addToNamespace.push(fix);
130135                         break;
130136                     case 1 /* ImportType */:
130137                         importType.push(fix);
130138                         break;
130139                     case 2 /* AddToExisting */: {
130140                         var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport;
130141                         var key = String(ts.getNodeId(importClauseOrBindingPattern));
130142                         var entry = addToExisting.get(key);
130143                         if (!entry) {
130144                             addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport });
130145                         }
130146                         if (importKind === 0 /* Named */) {
130147                             ts.pushIfUnique(entry.namedImports, symbolName);
130148                         }
130149                         else {
130150                             ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add to Existing) Default import should be missing or match symbolName");
130151                             entry.defaultImport = symbolName;
130152                         }
130153                         break;
130154                     }
130155                     case 3 /* AddNew */: {
130156                         var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly;
130157                         var entry = newImports.get(moduleSpecifier);
130158                         if (!entry) {
130159                             newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire });
130160                         }
130161                         else {
130162                             // An import clause can only be type-only if every import fix contributing to it can be type-only.
130163                             entry.typeOnly = entry.typeOnly && typeOnly;
130164                         }
130165                         switch (importKind) {
130166                             case 1 /* Default */:
130167                                 ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add new) Default import should be missing or match symbolName");
130168                                 entry.defaultImport = symbolName;
130169                                 break;
130170                             case 0 /* Named */:
130171                                 ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName);
130172                                 break;
130173                             case 3 /* CommonJS */:
130174                             case 2 /* Namespace */:
130175                                 ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName");
130176                                 entry.namespaceLikeImport = { importKind: importKind, name: symbolName };
130177                                 break;
130178                         }
130179                         break;
130180                     }
130181                     default:
130182                         ts.Debug.assertNever(fix, "fix wasn't never - got kind " + fix.kind);
130183                 }
130184             }
130185             function writeFixes(changeTracker) {
130186                 var quotePreference = ts.getQuotePreference(sourceFile, preferences);
130187                 for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) {
130188                     var fix = addToNamespace_1[_i];
130189                     addNamespaceQualifier(changeTracker, sourceFile, fix);
130190                 }
130191                 for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) {
130192                     var fix = importType_1[_a];
130193                     addImportType(changeTracker, sourceFile, fix, quotePreference);
130194                 }
130195                 addToExisting.forEach(function (_a) {
130196                     var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport;
130197                     doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport);
130198                 });
130199                 var newDeclarations;
130200                 newImports.forEach(function (_a, moduleSpecifier) {
130201                     var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]);
130202                     var getDeclarations = useRequire ? getNewRequires : getNewImports;
130203                     newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports));
130204                 });
130205                 if (newDeclarations) {
130206                     ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true);
130207                 }
130208             }
130209         }
130210         codefix.createImportAdder = createImportAdder;
130211         // Sorted with the preferred fix coming first.
130212         var ImportFixKind;
130213         (function (ImportFixKind) {
130214             ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace";
130215             ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType";
130216             ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting";
130217             ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew";
130218         })(ImportFixKind || (ImportFixKind = {}));
130219         var ImportKind;
130220         (function (ImportKind) {
130221             ImportKind[ImportKind["Named"] = 0] = "Named";
130222             ImportKind[ImportKind["Default"] = 1] = "Default";
130223             ImportKind[ImportKind["Namespace"] = 2] = "Namespace";
130224             ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS";
130225         })(ImportKind || (ImportKind = {}));
130226         function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) {
130227             var compilerOptions = program.getCompilerOptions();
130228             var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles());
130229             var useRequire = shouldUseRequire(sourceFile, compilerOptions);
130230             var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position));
130231             var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier;
130232             var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences);
130233             return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) };
130234         }
130235         codefix.getImportCompletionAction = getImportCompletionAction;
130236         function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) {
130237             ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol");
130238             // We sort the best codefixes first, so taking `first` is best.
130239             return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences));
130240         }
130241         function codeFixActionToCodeAction(_a) {
130242             var description = _a.description, changes = _a.changes, commands = _a.commands;
130243             return { description: description, changes: changes, commands: commands };
130244         }
130245         function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) {
130246             var result = [];
130247             forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) {
130248                 // Don't import from a re-export when looking "up" like to `./index` or `../index`.
130249                 if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) {
130250                     return;
130251                 }
130252                 var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions);
130253                 if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) {
130254                     result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) });
130255                 }
130256                 for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) {
130257                     var exported = _a[_i];
130258                     if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) {
130259                         result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) });
130260                     }
130261                 }
130262             });
130263             return result;
130264         }
130265         function isTypeOnlySymbol(s, checker) {
130266             return !(ts.skipAlias(s, checker).flags & 111551 /* Value */);
130267         }
130268         function isTypeOnlyPosition(sourceFile, position) {
130269             return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position));
130270         }
130271         function getFixForImport(exportInfos, symbolName, 
130272         /** undefined only for missing JSX namespace */
130273         position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) {
130274             var checker = program.getTypeChecker();
130275             var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); });
130276             var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker);
130277             var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position));
130278             // Don't bother providing an action to add a new import if we can add to an existing one.
130279             var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences);
130280             return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport);
130281         }
130282         function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) {
130283             // It is possible that multiple import statements with the same specifier exist in the file.
130284             // e.g.
130285             //
130286             //     import * as ns from "foo";
130287             //     import { member1, member2 } from "foo";
130288             //
130289             //     member3/**/ <-- cusor here
130290             //
130291             // in this case we should provie 2 actions:
130292             //     1. change "member3" to "ns.member3"
130293             //     2. add "member3" to the second import statement's import list
130294             // and it is up to the user to decide which one fits best.
130295             return ts.firstDefined(existingImports, function (_a) {
130296                 var declaration = _a.declaration;
130297                 var namespacePrefix = getNamespaceLikeImportText(declaration);
130298                 if (namespacePrefix) {
130299                     var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker);
130300                     if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) {
130301                         return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position };
130302                     }
130303                 }
130304             });
130305         }
130306         function getTargetModuleFromNamespaceLikeImport(declaration, checker) {
130307             var _a;
130308             switch (declaration.kind) {
130309                 case 242 /* VariableDeclaration */:
130310                     return checker.resolveExternalModuleName(declaration.initializer.arguments[0]);
130311                 case 253 /* ImportEqualsDeclaration */:
130312                     return checker.getAliasedSymbol(declaration.symbol);
130313                 case 254 /* ImportDeclaration */:
130314                     var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport);
130315                     return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol);
130316                 default:
130317                     return ts.Debug.assertNever(declaration);
130318             }
130319         }
130320         function getNamespaceLikeImportText(declaration) {
130321             var _a, _b, _c;
130322             switch (declaration.kind) {
130323                 case 242 /* VariableDeclaration */:
130324                     return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text;
130325                 case 253 /* ImportEqualsDeclaration */:
130326                     return declaration.name.text;
130327                 case 254 /* ImportDeclaration */:
130328                     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;
130329                 default:
130330                     return ts.Debug.assertNever(declaration);
130331             }
130332         }
130333         function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) {
130334             return ts.firstDefined(existingImports, function (_a) {
130335                 var declaration = _a.declaration, importKind = _a.importKind;
130336                 if (declaration.kind === 253 /* ImportEqualsDeclaration */)
130337                     return undefined;
130338                 if (declaration.kind === 242 /* VariableDeclaration */) {
130339                     return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */
130340                         ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false }
130341                         : undefined;
130342                 }
130343                 var importClause = declaration.importClause;
130344                 if (!importClause)
130345                     return undefined;
130346                 var name = importClause.name, namedBindings = importClause.namedBindings;
130347                 return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */)
130348                     ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport }
130349                     : undefined;
130350             });
130351         }
130352         function getExistingImportDeclarations(_a, checker, sourceFile) {
130353             var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
130354             // Can't use an es6 import for a type in JS.
130355             return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) {
130356                 var i = ts.importFromModuleSpecifier(moduleSpecifier);
130357                 if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) {
130358                     return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined;
130359                 }
130360                 if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) {
130361                     return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined;
130362                 }
130363             });
130364         }
130365         function shouldUseRequire(sourceFile, compilerOptions) {
130366             return ts.isSourceFileJS(sourceFile)
130367                 && !sourceFile.externalModuleIndicator
130368                 && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015);
130369         }
130370         function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) {
130371             var isJs = ts.isSourceFileJS(sourceFile);
130372             var compilerOptions = program.getCompilerOptions();
130373             var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier;
130374             var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
130375                 var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly;
130376                 return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences)
130377                     .map(function (moduleSpecifier) {
130378                     // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
130379                     return exportedSymbolIsTypeOnly && isJs
130380                         ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") }
130381                         : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport };
130382                 });
130383             });
130384             // Sort by presence in package.json, then shortest paths first
130385             return ts.sort(choicesForEachExportingModule, function (a, b) {
130386                 var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier);
130387                 var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier);
130388                 if (allowsImportingA && !allowsImportingB) {
130389                     return -1;
130390                 }
130391                 if (allowsImportingB && !allowsImportingA) {
130392                     return 1;
130393                 }
130394                 return a.moduleSpecifier.length - b.moduleSpecifier.length;
130395             });
130396         }
130397         function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) {
130398             var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); });
130399             return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences);
130400         }
130401         function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) {
130402             var declaration = _a.declaration, importKind = _a.importKind;
130403             var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier :
130404                 declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] :
130405                     declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression :
130406                         undefined;
130407             return moduleSpecifier && ts.isStringLiteral(moduleSpecifier)
130408                 ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire }
130409                 : undefined;
130410         }
130411         function getFixesInfo(context, errorCode, pos) {
130412             var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos);
130413             var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
130414                 ? getFixesInfoForUMDImport(context, symbolToken)
130415                 : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined;
130416             return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) });
130417         }
130418         function getFixesInfoForUMDImport(_a, token) {
130419             var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences;
130420             var checker = program.getTypeChecker();
130421             var umdSymbol = getUmdSymbol(token, checker);
130422             if (!umdSymbol)
130423                 return undefined;
130424             var symbol = checker.getAliasedSymbol(umdSymbol);
130425             var symbolName = umdSymbol.name;
130426             var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }];
130427             var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions());
130428             var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences);
130429             return { fixes: fixes, symbolName: symbolName };
130430         }
130431         function getUmdSymbol(token, checker) {
130432             // try the identifier to see if it is the umd symbol
130433             var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined;
130434             if (ts.isUMDExportSymbol(umdSymbol))
130435                 return umdSymbol;
130436             // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
130437             var parent = token.parent;
130438             return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent)
130439                 ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
130440                 : undefined;
130441         }
130442         function getUmdImportKind(importingFile, compilerOptions) {
130443             // Import a synthetic `default` if enabled.
130444             if (ts.getAllowSyntheticDefaultImports(compilerOptions)) {
130445                 return 1 /* Default */;
130446             }
130447             // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it.
130448             var moduleKind = ts.getEmitModuleKind(compilerOptions);
130449             switch (moduleKind) {
130450                 case ts.ModuleKind.AMD:
130451                 case ts.ModuleKind.CommonJS:
130452                 case ts.ModuleKind.UMD:
130453                     if (ts.isInJSFile(importingFile)) {
130454                         return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */;
130455                     }
130456                     return 3 /* CommonJS */;
130457                 case ts.ModuleKind.System:
130458                 case ts.ModuleKind.ES2015:
130459                 case ts.ModuleKind.ES2020:
130460                 case ts.ModuleKind.ESNext:
130461                 case ts.ModuleKind.None:
130462                     // Fall back to the `import * as ns` style import.
130463                     return 2 /* Namespace */;
130464                 default:
130465                     return ts.Debug.assertNever(moduleKind, "Unexpected moduleKind " + moduleKind);
130466             }
130467         }
130468         function getFixesInfoForNonUMDImport(_a, symbolToken) {
130469             var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences;
130470             var checker = program.getTypeChecker();
130471             // If we're at `<Foo/>`, we must check if `Foo` is already in scope, and if so, get an import for `React` instead.
130472             var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent)
130473                 && symbolToken.parent.tagName === symbolToken
130474                 && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false))
130475                 ? checker.getJsxNamespace(sourceFile)
130476                 : symbolToken.text;
130477             // "default" is a keyword and not a legal identifier for the import, so we don't expect it here
130478             ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here");
130479             var compilerOptions = program.getCompilerOptions();
130480             var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken);
130481             var useRequire = shouldUseRequire(sourceFile, compilerOptions);
130482             var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host);
130483             var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) {
130484                 var _ = _a[0], exportInfos = _a[1];
130485                 return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences);
130486             }));
130487             return { fixes: fixes, symbolName: symbolName };
130488         }
130489         // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported.
130490         function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program, host) {
130491             // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once.
130492             // Maps symbol id to info for modules providing that symbol (original export + re-exports).
130493             var originalSymbolToExportInfos = ts.createMultiMap();
130494             function addSymbol(moduleSymbol, exportedSymbol, importKind) {
130495                 originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) });
130496             }
130497             forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, function (moduleSymbol) {
130498                 cancellationToken.throwIfCancellationRequested();
130499                 var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, program.getCompilerOptions());
130500                 if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) {
130501                     addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind);
130502                 }
130503                 // check exports with the same name
130504                 var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
130505                 if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
130506                     addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */);
130507                 }
130508             });
130509             return originalSymbolToExportInfos;
130510         }
130511         function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) {
130512             var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions);
130513             if (!exported)
130514                 return undefined;
130515             var symbol = exported.symbol, kind = exported.kind;
130516             var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions);
130517             return info && __assign({ symbol: symbol, kind: kind }, info);
130518         }
130519         function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) {
130520             var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
130521             if (defaultExport)
130522                 return { symbol: defaultExport, kind: 1 /* Default */ };
130523             var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol);
130524             return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: getExportEqualsImportKind(importingFile, compilerOptions) };
130525         }
130526         function getExportEqualsImportKind(importingFile, compilerOptions) {
130527             var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions);
130528             // 1. 'import =' will not work in es2015+, so the decision is between a default
130529             //    and a namespace import, based on allowSyntheticDefaultImports/esModuleInterop.
130530             if (ts.getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
130531                 return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */;
130532             }
130533             // 2. 'import =' will not work in JavaScript, so the decision is between a default
130534             //    and const/require.
130535             if (ts.isInJSFile(importingFile)) {
130536                 return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */;
130537             }
130538             // 3. At this point the most correct choice is probably 'import =', but people
130539             //    really hate that, so look to see if the importing file has any precedent
130540             //    on how to handle it.
130541             for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) {
130542                 var statement = _a[_i];
130543                 if (ts.isImportEqualsDeclaration(statement)) {
130544                     return 3 /* CommonJS */;
130545                 }
130546             }
130547             // 4. We have no precedent to go on, so just use a default import if
130548             //    allowSyntheticDefaultImports/esModuleInterop is enabled.
130549             return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */;
130550         }
130551         function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) {
130552             var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
130553             if (localSymbol)
130554                 return { symbolForMeaning: localSymbol, name: localSymbol.name };
130555             var name = getNameForExportDefault(defaultExport);
130556             if (name !== undefined)
130557                 return { symbolForMeaning: defaultExport, name: name };
130558             if (defaultExport.flags & 2097152 /* Alias */) {
130559                 var aliased = checker.getImmediateAliasedSymbol(defaultExport);
130560                 return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.checkDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions);
130561             }
130562             if (defaultExport.escapedName !== "default" /* Default */ &&
130563                 defaultExport.escapedName !== "export=" /* ExportEquals */) {
130564                 return { symbolForMeaning: defaultExport, name: defaultExport.getName() };
130565             }
130566             return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) };
130567         }
130568         function getNameForExportDefault(symbol) {
130569             return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
130570                 if (ts.isExportAssignment(declaration)) {
130571                     if (ts.isIdentifier(declaration.expression)) {
130572                         return declaration.expression.text;
130573                     }
130574                 }
130575                 else if (ts.isExportSpecifier(declaration)) {
130576                     ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export");
130577                     return declaration.propertyName && declaration.propertyName.text;
130578                 }
130579             });
130580         }
130581         function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) {
130582             var diag;
130583             var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
130584                 diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference);
130585             });
130586             return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports);
130587         }
130588         function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) {
130589             switch (fix.kind) {
130590                 case 0 /* UseNamespace */:
130591                     addNamespaceQualifier(changes, sourceFile, fix);
130592                     return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName];
130593                 case 1 /* ImportType */:
130594                     addImportType(changes, sourceFile, fix, quotePreference);
130595                     return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName];
130596                 case 2 /* AddToExisting */: {
130597                     var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier;
130598                     doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport);
130599                     var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier);
130600                     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!
130601                 }
130602                 case 3 /* AddNew */: {
130603                     var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire;
130604                     var getDeclarations = useRequire ? getNewRequires : getNewImports;
130605                     var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } :
130606                         importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } :
130607                             { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly };
130608                     ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true);
130609                     return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier];
130610                 }
130611                 default:
130612                     return ts.Debug.assertNever(fix, "Unexpected fix kind " + fix.kind);
130613             }
130614         }
130615         function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) {
130616             if (clause.kind === 189 /* ObjectBindingPattern */) {
130617                 if (defaultImport) {
130618                     addElementToBindingPattern(clause, defaultImport, "default");
130619                 }
130620                 for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) {
130621                     var specifier = namedImports_1[_i];
130622                     addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined);
130623                 }
130624                 return;
130625             }
130626             var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly;
130627             if (defaultImport) {
130628                 ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one");
130629                 changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " });
130630             }
130631             if (namedImports.length) {
130632                 var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); });
130633                 if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) {
130634                     for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) {
130635                         var spec = specifiers_1[_a];
130636                         changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec);
130637                     }
130638                 }
130639                 else {
130640                     if (specifiers.length) {
130641                         var namedImports_2 = ts.createNamedImports(specifiers);
130642                         if (clause.namedBindings) {
130643                             changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2);
130644                         }
130645                         else {
130646                             changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2);
130647                         }
130648                     }
130649                 }
130650             }
130651             if (convertTypeOnlyToRegular) {
130652                 changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile));
130653             }
130654             function addElementToBindingPattern(bindingPattern, name, propertyName) {
130655                 var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name);
130656                 if (bindingPattern.elements.length) {
130657                     changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element);
130658                 }
130659                 else {
130660                     changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element]));
130661                 }
130662             }
130663         }
130664         function addNamespaceQualifier(changes, sourceFile, _a) {
130665             var namespacePrefix = _a.namespacePrefix, position = _a.position;
130666             changes.insertText(sourceFile, position, namespacePrefix + ".");
130667         }
130668         function addImportType(changes, sourceFile, _a, quotePreference) {
130669             var moduleSpecifier = _a.moduleSpecifier, position = _a.position;
130670             changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference));
130671         }
130672         function getImportTypePrefix(moduleSpecifier, quotePreference) {
130673             var quote = ts.getQuoteFromPreference(quotePreference);
130674             return "import(" + quote + moduleSpecifier + quote + ").";
130675         }
130676         function getNewImports(moduleSpecifier, quotePreference, imports) {
130677             var _a, _b;
130678             var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
130679             var statements;
130680             if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) {
130681                 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));
130682             }
130683             var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly;
130684             if (namespaceLikeImport) {
130685                 var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */
130686                     ? ts.createImportEqualsDeclaration(
130687                     /*decorators*/ undefined, 
130688                     /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier))
130689                     : ts.createImportDeclaration(
130690                     /*decorators*/ undefined, 
130691                     /*modifiers*/ undefined, ts.createImportClause(
130692                     /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier);
130693                 statements = ts.combine(statements, declaration);
130694             }
130695             return ts.Debug.checkDefined(statements);
130696         }
130697         function getNewRequires(moduleSpecifier, quotePreference, imports) {
130698             var _a, _b;
130699             var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
130700             var statements;
130701             // const { default: foo, bar, etc } = require('./mod');
130702             if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) {
130703                 var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || [];
130704                 if (imports.defaultImport) {
130705                     bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport));
130706                 }
130707                 var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier);
130708                 statements = ts.combine(statements, declaration);
130709             }
130710             // const foo = require('./mod');
130711             if (imports.namespaceLikeImport) {
130712                 var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier);
130713                 statements = ts.combine(statements, declaration);
130714             }
130715             return ts.Debug.checkDefined(statements);
130716         }
130717         function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) {
130718             return ts.createVariableStatement(
130719             /*modifiers*/ undefined, ts.createVariableDeclarationList([
130720                 ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, 
130721                 /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier]))
130722             ], 2 /* Const */));
130723         }
130724         function symbolHasMeaning(_a, meaning) {
130725             var declarations = _a.declarations;
130726             return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); });
130727         }
130728         function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, cb) {
130729             var filteredCount = 0;
130730             var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host);
130731             var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost);
130732             forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) {
130733                 if (sourceFile === undefined) {
130734                     if (!packageJson || packageJson.allowsImportingAmbientModule(module)) {
130735                         cb(module);
130736                     }
130737                     else if (packageJson) {
130738                         filteredCount++;
130739                     }
130740                 }
130741                 else if (sourceFile &&
130742                     sourceFile !== from &&
130743                     isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) {
130744                     if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) {
130745                         cb(module);
130746                     }
130747                     else if (packageJson) {
130748                         filteredCount++;
130749                     }
130750                 }
130751             });
130752             if (host.log) {
130753                 host.log("forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents");
130754             }
130755         }
130756         codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom;
130757         function forEachExternalModule(checker, allSourceFiles, cb) {
130758             for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) {
130759                 var ambient = _a[_i];
130760                 cb(ambient, /*sourceFile*/ undefined);
130761             }
130762             for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) {
130763                 var sourceFile = allSourceFiles_1[_b];
130764                 if (ts.isExternalOrCommonJsModule(sourceFile)) {
130765                     cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
130766                 }
130767             }
130768         }
130769         function isImportableFile(program, from, to, moduleSpecifierResolutionHost) {
130770             var _a;
130771             var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost);
130772             var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost);
130773             return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, 
130774             /*preferSymlinks*/ false, function (toPath) {
130775                 var toFile = program.getSourceFile(toPath);
130776                 // Determine to import using toPath only if toPath is what we were looking at
130777                 // or there doesnt exist the file in the program by the symlink
130778                 return (toFile === to || !toFile) &&
130779                     isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache);
130780             });
130781         }
130782         /**
130783          * Don't include something from a `node_modules` that isn't actually reachable by a global import.
130784          * A relative import to node_modules is usually a bad idea.
130785          */
130786         function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) {
130787             // If it's in a `node_modules` but is not reachable from here via a global import, don't bother.
130788             var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; });
130789             var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules));
130790             return toNodeModulesParent === undefined
130791                 || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent)
130792                 || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent));
130793         }
130794         function moduleSymbolToValidIdentifier(moduleSymbol, target) {
130795             return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target);
130796         }
130797         codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier;
130798         function moduleSpecifierToValidIdentifier(moduleSpecifier, target) {
130799             var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index"));
130800             var res = "";
130801             var lastCharWasValid = true;
130802             var firstCharCode = baseName.charCodeAt(0);
130803             if (ts.isIdentifierStart(firstCharCode, target)) {
130804                 res += String.fromCharCode(firstCharCode);
130805             }
130806             else {
130807                 lastCharWasValid = false;
130808             }
130809             for (var i = 1; i < baseName.length; i++) {
130810                 var ch = baseName.charCodeAt(i);
130811                 var isValid = ts.isIdentifierPart(ch, target);
130812                 if (isValid) {
130813                     var char = String.fromCharCode(ch);
130814                     if (!lastCharWasValid) {
130815                         char = char.toUpperCase();
130816                     }
130817                     res += char;
130818                 }
130819                 lastCharWasValid = isValid;
130820             }
130821             // Need `|| "_"` to ensure result isn't empty.
130822             return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res;
130823         }
130824         codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier;
130825         function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) {
130826             if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); }
130827             var packageJsons = host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host);
130828             var dependencyGroups = 1 /* Dependencies */ | 2 /* DevDependencies */ | 8 /* OptionalDependencies */;
130829             var usesNodeCoreModules;
130830             return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost };
130831             function moduleSpecifierIsCoveredByPackageJson(specifier) {
130832                 var packageName = getNodeModuleRootSpecifier(specifier);
130833                 for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) {
130834                     var packageJson = packageJsons_1[_i];
130835                     if (packageJson.has(packageName, dependencyGroups) || packageJson.has(ts.getTypesPackageName(packageName), dependencyGroups)) {
130836                         return true;
130837                     }
130838                 }
130839                 return false;
130840             }
130841             function allowsImportingAmbientModule(moduleSymbol) {
130842                 if (!packageJsons.length) {
130843                     return true;
130844                 }
130845                 var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
130846                 var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName);
130847                 if (typeof declaringNodeModuleName === "undefined") {
130848                     return true;
130849                 }
130850                 var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName());
130851                 if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) {
130852                     return true;
130853                 }
130854                 return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName)
130855                     || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
130856             }
130857             function allowsImportingSourceFile(sourceFile) {
130858                 if (!packageJsons.length) {
130859                     return true;
130860                 }
130861                 var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName);
130862                 if (!moduleSpecifier) {
130863                     return true;
130864                 }
130865                 return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
130866             }
130867             /**
130868              * Use for a specific module specifier that has already been resolved.
130869              * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve
130870              * the best module specifier for a given module _and_ determine if it’s importable.
130871              */
130872             function allowsImportingSpecifier(moduleSpecifier) {
130873                 if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) {
130874                     return true;
130875                 }
130876                 if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) {
130877                     return true;
130878                 }
130879                 return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
130880             }
130881             function isAllowedCoreNodeModulesImport(moduleSpecifier) {
130882                 // If we’re in JavaScript, it can be difficult to tell whether the user wants to import
130883                 // from Node core modules or not. We can start by seeing if the user is actually using
130884                 // any node core modules, as opposed to simply having @types/node accidentally as a
130885                 // dependency of a dependency.
130886                 if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) {
130887                     if (usesNodeCoreModules === undefined) {
130888                         usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile);
130889                     }
130890                     if (usesNodeCoreModules) {
130891                         return true;
130892                     }
130893                 }
130894                 return false;
130895             }
130896             function getNodeModulesPackageNameFromFileName(importedFileName) {
130897                 if (!ts.stringContains(importedFileName, "node_modules")) {
130898                     return undefined;
130899                 }
130900                 var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost);
130901                 if (!specifier) {
130902                     return undefined;
130903                 }
130904                 // Paths here are not node_modules, so we don’t care about them;
130905                 // returning anything will trigger a lookup in package.json.
130906                 if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) {
130907                     return getNodeModuleRootSpecifier(specifier);
130908                 }
130909             }
130910             function getNodeModuleRootSpecifier(fullSpecifier) {
130911                 var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1);
130912                 // Scoped packages
130913                 if (ts.startsWith(components[0], "@")) {
130914                     return components[0] + "/" + components[1];
130915                 }
130916                 return components[0];
130917             }
130918         }
130919     })(codefix = ts.codefix || (ts.codefix = {}));
130920 })(ts || (ts = {}));
130921 /* @internal */
130922 var ts;
130923 (function (ts) {
130924     var codefix;
130925     (function (codefix) {
130926         var fixId = "fixImplicitThis";
130927         var errorCodes = [ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code];
130928         codefix.registerCodeFix({
130929             errorCodes: errorCodes,
130930             getCodeActions: function (context) {
130931                 var sourceFile = context.sourceFile, program = context.program, span = context.span;
130932                 var diagnostic;
130933                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
130934                     diagnostic = doChange(t, sourceFile, span.start, program.getTypeChecker());
130935                 });
130936                 return diagnostic ? [codefix.createCodeFixAction(fixId, changes, diagnostic, fixId, ts.Diagnostics.Fix_all_implicit_this_errors)] : ts.emptyArray;
130937             },
130938             fixIds: [fixId],
130939             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
130940                 doChange(changes, diag.file, diag.start, context.program.getTypeChecker());
130941             }); },
130942         });
130943         function doChange(changes, sourceFile, pos, checker) {
130944             var token = ts.getTokenAtPosition(sourceFile, pos);
130945             ts.Debug.assert(token.kind === 104 /* ThisKeyword */);
130946             var fn = ts.getThisContainer(token, /*includeArrowFunctions*/ false);
130947             if (!ts.isFunctionDeclaration(fn) && !ts.isFunctionExpression(fn))
130948                 return undefined;
130949             if (!ts.isSourceFile(ts.getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function
130950                 var fnKeyword = ts.Debug.assertDefined(ts.findChildOfKind(fn, 94 /* FunctionKeyword */, sourceFile));
130951                 var name = fn.name;
130952                 var body = ts.Debug.assertDefined(fn.body); // Should be defined because the function contained a 'this' expression
130953                 if (ts.isFunctionExpression(fn)) {
130954                     if (name && ts.FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) {
130955                         // Function expression references itself. To fix we would have to extract it to a const.
130956                         return undefined;
130957                     }
130958                     // `function() {}` --> `() => {}`
130959                     changes.delete(sourceFile, fnKeyword);
130960                     if (name) {
130961                         changes.delete(sourceFile, name);
130962                     }
130963                     changes.insertText(sourceFile, body.pos, " =>");
130964                     return [ts.Diagnostics.Convert_function_expression_0_to_arrow_function, name ? name.text : ts.ANONYMOUS];
130965                 }
130966                 else {
130967                     // `function f() {}` => `const f = () => {}`
130968                     // `name` should be defined because we only do this in inner contexts, and name is only undefined for `export default function() {}`.
130969                     changes.replaceNode(sourceFile, fnKeyword, ts.createToken(81 /* ConstKeyword */));
130970                     changes.insertText(sourceFile, name.end, " = ");
130971                     changes.insertText(sourceFile, body.pos, " =>");
130972                     return [ts.Diagnostics.Convert_function_declaration_0_to_arrow_function, name.text];
130973                 }
130974             }
130975             // No outer 'this', add a @class tag if in a JS constructor function
130976             else if (ts.isSourceFileJS(sourceFile) && ts.isPropertyAccessExpression(token.parent) && ts.isAssignmentExpression(token.parent.parent)) {
130977                 codefix.addJSDocTags(changes, sourceFile, fn, [ts.createJSDocClassTag()]);
130978                 return ts.Diagnostics.Add_class_tag;
130979             }
130980         }
130981     })(codefix = ts.codefix || (ts.codefix = {}));
130982 })(ts || (ts = {}));
130983 /* @internal */
130984 var ts;
130985 (function (ts) {
130986     var codefix;
130987     (function (codefix) {
130988         var fixId = "fixSpelling";
130989         var errorCodes = [
130990             ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
130991             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
130992             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
130993             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code,
130994             ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code,
130995         ];
130996         codefix.registerCodeFix({
130997             errorCodes: errorCodes,
130998             getCodeActions: function (context) {
130999                 var sourceFile = context.sourceFile;
131000                 var info = getInfo(sourceFile, context.span.start, context);
131001                 if (!info)
131002                     return undefined;
131003                 var node = info.node, suggestedSymbol = info.suggestedSymbol;
131004                 var target = context.host.getCompilationSettings().target;
131005                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); });
131006                 return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)];
131007             },
131008             fixIds: [fixId],
131009             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131010                 var info = getInfo(diag.file, diag.start, context);
131011                 var target = context.host.getCompilationSettings().target;
131012                 if (info)
131013                     doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target);
131014             }); },
131015         });
131016         function getInfo(sourceFile, pos, context) {
131017             // This is the identifier of the misspelled word. eg:
131018             // this.speling = 1;
131019             //      ^^^^^^^
131020             var node = ts.getTokenAtPosition(sourceFile, pos);
131021             var parent = node.parent;
131022             var checker = context.program.getTypeChecker();
131023             var suggestedSymbol;
131024             if (ts.isPropertyAccessExpression(parent) && parent.name === node) {
131025                 ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)");
131026                 var containingType = checker.getTypeAtLocation(parent.expression);
131027                 if (parent.flags & 32 /* OptionalChain */) {
131028                     containingType = checker.getNonNullableType(containingType);
131029                 }
131030                 suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType);
131031             }
131032             else if (ts.isImportSpecifier(parent) && parent.name === node) {
131033                 ts.Debug.assertNode(node, ts.isIdentifier, "Expected an identifier for spelling (import)");
131034                 var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration);
131035                 var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration);
131036                 if (resolvedSourceFile && resolvedSourceFile.symbol) {
131037                     suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol);
131038                 }
131039             }
131040             else {
131041                 var meaning = ts.getMeaningFromLocation(node);
131042                 var name = ts.getTextOfNode(node);
131043                 ts.Debug.assert(name !== undefined, "name should be defined");
131044                 suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
131045             }
131046             return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol };
131047         }
131048         function doChange(changes, sourceFile, node, suggestedSymbol, target) {
131049             var suggestion = ts.symbolName(suggestedSymbol);
131050             if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) {
131051                 var valDecl = suggestedSymbol.valueDeclaration;
131052                 if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) {
131053                     changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
131054                 }
131055                 else {
131056                     changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion)));
131057                 }
131058             }
131059             else {
131060                 changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion));
131061             }
131062         }
131063         function convertSemanticMeaningToSymbolFlags(meaning) {
131064             var flags = 0;
131065             if (meaning & 4 /* Namespace */) {
131066                 flags |= 1920 /* Namespace */;
131067             }
131068             if (meaning & 2 /* Type */) {
131069                 flags |= 788968 /* Type */;
131070             }
131071             if (meaning & 1 /* Value */) {
131072                 flags |= 111551 /* Value */;
131073             }
131074             return flags;
131075         }
131076         function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) {
131077             if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier))
131078                 return undefined;
131079             var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text);
131080             if (!resolvedModule)
131081                 return undefined;
131082             return context.program.getSourceFile(resolvedModule.resolvedFileName);
131083         }
131084     })(codefix = ts.codefix || (ts.codefix = {}));
131085 })(ts || (ts = {}));
131086 /* @internal */
131087 var ts;
131088 (function (ts) {
131089     var codefix;
131090     (function (codefix) {
131091         var fixId = "returnValueCorrect";
131092         var fixIdAddReturnStatement = "fixAddReturnStatement";
131093         var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace";
131094         var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen";
131095         var errorCodes = [
131096             ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code,
131097             ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
131098             ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code
131099         ];
131100         var ProblemKind;
131101         (function (ProblemKind) {
131102             ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement";
131103             ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses";
131104         })(ProblemKind || (ProblemKind = {}));
131105         codefix.registerCodeFix({
131106             errorCodes: errorCodes,
131107             fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen],
131108             getCodeActions: function (context) {
131109                 var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode;
131110                 var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode);
131111                 if (!info)
131112                     return undefined;
131113                 if (info.kind === ProblemKind.MissingReturnStatement) {
131114                     return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined);
131115                 }
131116                 else {
131117                     return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)];
131118                 }
131119             },
131120             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131121                 var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code);
131122                 if (!info)
131123                     return undefined;
131124                 switch (context.fixId) {
131125                     case fixIdAddReturnStatement:
131126                         addReturnStatement(changes, diag.file, info.expression, info.statement);
131127                         break;
131128                     case fixIdRemoveBlockBodyBrace:
131129                         if (!ts.isArrowFunction(info.declaration))
131130                             return undefined;
131131                         removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false);
131132                         break;
131133                     case fixIdWrapTheBlockWithParen:
131134                         if (!ts.isArrowFunction(info.declaration))
131135                             return undefined;
131136                         wrapBlockWithParen(changes, diag.file, info.declaration, info.expression);
131137                         break;
131138                     default:
131139                         ts.Debug.fail(JSON.stringify(context.fixId));
131140                 }
131141             }); },
131142         });
131143         function getFixInfo(checker, declaration, expectType, isFunctionType) {
131144             if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1)
131145                 return undefined;
131146             var firstStatement = ts.first(declaration.body.statements);
131147             if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) {
131148                 return {
131149                     declaration: declaration,
131150                     kind: ProblemKind.MissingReturnStatement,
131151                     expression: firstStatement.expression,
131152                     statement: firstStatement,
131153                     commentSource: firstStatement.expression
131154                 };
131155             }
131156             else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) {
131157                 var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]);
131158                 if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) {
131159                     return ts.isArrowFunction(declaration) ? {
131160                         declaration: declaration,
131161                         kind: ProblemKind.MissingParentheses,
131162                         expression: node,
131163                         statement: firstStatement,
131164                         commentSource: firstStatement.statement.expression
131165                     } : {
131166                         declaration: declaration,
131167                         kind: ProblemKind.MissingReturnStatement,
131168                         expression: node,
131169                         statement: firstStatement,
131170                         commentSource: firstStatement.statement.expression
131171                     };
131172                 }
131173             }
131174             else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) {
131175                 var firstBlockStatement = ts.first(firstStatement.statements);
131176                 if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) {
131177                     var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]);
131178                     if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) {
131179                         return {
131180                             declaration: declaration,
131181                             kind: ProblemKind.MissingReturnStatement,
131182                             expression: node,
131183                             statement: firstStatement,
131184                             commentSource: firstBlockStatement
131185                         };
131186                     }
131187                 }
131188             }
131189             return undefined;
131190         }
131191         function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) {
131192             return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type);
131193         }
131194         function getInfo(checker, sourceFile, position, errorCode) {
131195             var node = ts.getTokenAtPosition(sourceFile, position);
131196             if (!node.parent)
131197                 return undefined;
131198             var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
131199             switch (errorCode) {
131200                 case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code:
131201                     if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node))
131202                         return undefined;
131203                     return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false);
131204                 case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code:
131205                     if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body)
131206                         return undefined;
131207                     var pos = declaration.parent.arguments.indexOf(declaration);
131208                     var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos);
131209                     if (!type)
131210                         return undefined;
131211                     return getFixInfo(checker, declaration, type, /* isFunctionType */ true);
131212                 case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code:
131213                     if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent))
131214                         return undefined;
131215                     var initializer = getVariableLikeInitializer(node.parent);
131216                     if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body)
131217                         return undefined;
131218                     return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true);
131219             }
131220             return undefined;
131221         }
131222         function getVariableLikeInitializer(declaration) {
131223             switch (declaration.kind) {
131224                 case 242 /* VariableDeclaration */:
131225                 case 156 /* Parameter */:
131226                 case 191 /* BindingElement */:
131227                 case 159 /* PropertyDeclaration */:
131228                 case 281 /* PropertyAssignment */:
131229                     return declaration.initializer;
131230                 case 273 /* JsxAttribute */:
131231                     return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined);
131232                 case 282 /* ShorthandPropertyAssignment */:
131233                 case 158 /* PropertySignature */:
131234                 case 284 /* EnumMember */:
131235                 case 323 /* JSDocPropertyTag */:
131236                 case 317 /* JSDocParameterTag */:
131237                     return undefined;
131238             }
131239         }
131240         function addReturnStatement(changes, sourceFile, expression, statement) {
131241             ts.suppressLeadingAndTrailingTrivia(expression);
131242             var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile);
131243             changes.replaceNode(sourceFile, statement, ts.createReturn(expression), {
131244                 leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
131245                 trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude,
131246                 suffix: probablyNeedSemi ? ";" : undefined
131247             });
131248         }
131249         function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) {
131250             var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression;
131251             ts.suppressLeadingAndTrailingTrivia(commentSource);
131252             ts.copyComments(commentSource, newBody);
131253             changes.replaceNode(sourceFile, declaration.body, newBody);
131254         }
131255         function wrapBlockWithParen(changes, sourceFile, declaration, expression) {
131256             changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression));
131257         }
131258         function getActionForfixAddReturnStatement(context, expression, statement) {
131259             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); });
131260             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement);
131261         }
131262         function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) {
131263             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); });
131264             return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces);
131265         }
131266         function getActionForfixWrapTheBlockWithParen(context, declaration, expression) {
131267             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); });
131268             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);
131269         }
131270     })(codefix = ts.codefix || (ts.codefix = {}));
131271 })(ts || (ts = {}));
131272 /* @internal */
131273 var ts;
131274 (function (ts) {
131275     var codefix;
131276     (function (codefix) {
131277         var fixName = "addMissingMember";
131278         var errorCodes = [
131279             ts.Diagnostics.Property_0_does_not_exist_on_type_1.code,
131280             ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
131281             ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code,
131282             ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code,
131283             ts.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code
131284         ];
131285         var fixId = "addMissingMember";
131286         codefix.registerCodeFix({
131287             errorCodes: errorCodes,
131288             getCodeActions: function (context) {
131289                 var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker(), context.program);
131290                 if (!info)
131291                     return undefined;
131292                 if (info.kind === 0 /* Enum */) {
131293                     var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration;
131294                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); });
131295                     return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)];
131296                 }
131297                 var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
131298                 var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs);
131299                 var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ?
131300                     ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) :
131301                     getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic);
131302                 return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember);
131303             },
131304             fixIds: [fixId],
131305             getAllCodeActions: function (context) {
131306                 var program = context.program;
131307                 var checker = program.getTypeChecker();
131308                 var seen = ts.createMap();
131309                 var typeDeclToMembers = new ts.NodeMap();
131310                 return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
131311                     codefix.eachDiagnostic(context, errorCodes, function (diag) {
131312                         var info = getInfo(diag.file, diag.start, checker, context.program);
131313                         if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
131314                             return;
131315                         }
131316                         if (info.kind === 0 /* Enum */) {
131317                             var token = info.token, parentDeclaration = info.parentDeclaration;
131318                             addEnumMemberDeclaration(changes, checker, token, parentDeclaration);
131319                         }
131320                         else {
131321                             var parentDeclaration = info.parentDeclaration, token_2 = info.token;
131322                             var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; });
131323                             if (!infos.some(function (i) { return i.token.text === token_2.text; }))
131324                                 infos.push(info);
131325                         }
131326                     });
131327                     typeDeclToMembers.forEach(function (infos, classDeclaration) {
131328                         var supers = getAllSupers(classDeclaration, checker);
131329                         var _loop_13 = function (info) {
131330                             // If some superclass added this property, don't add it again.
131331                             if (supers.some(function (superClassOrInterface) {
131332                                 var superInfos = typeDeclToMembers.get(superClassOrInterface);
131333                                 return !!superInfos && superInfos.some(function (_a) {
131334                                     var token = _a.token;
131335                                     return token.text === info.token.text;
131336                                 });
131337                             }))
131338                                 return "continue";
131339                             var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
131340                             // Always prefer to add a method declaration if possible.
131341                             if (call && !ts.isPrivateIdentifier(token)) {
131342                                 addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs);
131343                             }
131344                             else {
131345                                 if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) {
131346                                     addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, makeStatic);
131347                                 }
131348                                 else {
131349                                     var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token);
131350                                     addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic ? 32 /* Static */ : 0);
131351                                 }
131352                             }
131353                         };
131354                         for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
131355                             var info = infos_1[_i];
131356                             _loop_13(info);
131357                         }
131358                     });
131359                 }));
131360             },
131361         });
131362         function getAllSupers(decl, checker) {
131363             var res = [];
131364             while (decl) {
131365                 var superElement = ts.getClassExtendsHeritageElement(decl);
131366                 var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
131367                 var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike);
131368                 if (superDecl) {
131369                     res.push(superDecl);
131370                 }
131371                 decl = superDecl;
131372             }
131373             return res;
131374         }
131375         var InfoKind;
131376         (function (InfoKind) {
131377             InfoKind[InfoKind["Enum"] = 0] = "Enum";
131378             InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface";
131379         })(InfoKind || (InfoKind = {}));
131380         function getInfo(tokenSourceFile, tokenPos, checker, program) {
131381             // The identifier of the missing property. eg:
131382             // this.missing = 1;
131383             //      ^^^^^^^
131384             var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos);
131385             if (!ts.isIdentifier(token) && !ts.isPrivateIdentifier(token)) {
131386                 return undefined;
131387             }
131388             var parent = token.parent;
131389             if (!ts.isPropertyAccessExpression(parent))
131390                 return undefined;
131391             var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression));
131392             var symbol = leftExpressionType.symbol;
131393             if (!symbol || !symbol.declarations)
131394                 return undefined;
131395             var classDeclaration = ts.find(symbol.declarations, ts.isClassLike);
131396             // Don't suggest adding private identifiers to anything other than a class.
131397             if (!classDeclaration && ts.isPrivateIdentifier(token)) {
131398                 return undefined;
131399             }
131400             // Prefer to change the class instead of the interface if they are merged
131401             var classOrInterface = classDeclaration || ts.find(symbol.declarations, ts.isInterfaceDeclaration);
131402             if (classOrInterface && !program.isSourceFileFromExternalLibrary(classOrInterface.getSourceFile())) {
131403                 var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol);
131404                 if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(classOrInterface))) {
131405                     return undefined;
131406                 }
131407                 var declSourceFile = classOrInterface.getSourceFile();
131408                 var inJs = ts.isSourceFileJS(declSourceFile);
131409                 var call = ts.tryCast(parent.parent, ts.isCallExpression);
131410                 return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call };
131411             }
131412             var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration);
131413             if (enumDeclaration && !ts.isPrivateIdentifier(token) && !program.isSourceFileFromExternalLibrary(enumDeclaration.getSourceFile())) {
131414                 return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration };
131415             }
131416             return undefined;
131417         }
131418         function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
131419             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, token, makeStatic); });
131420             if (changes.length === 0) {
131421                 return undefined;
131422             }
131423             var diagnostic = makeStatic ? ts.Diagnostics.Initialize_static_property_0 :
131424                 ts.isPrivateIdentifier(token) ? ts.Diagnostics.Declare_a_private_field_named_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor;
131425             return codefix.createCodeFixAction(fixName, changes, [diagnostic, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
131426         }
131427         function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) {
131428             var tokenName = token.text;
131429             if (makeStatic) {
131430                 if (classDeclaration.kind === 214 /* ClassExpression */) {
131431                     return;
131432                 }
131433                 var className = classDeclaration.name.getText();
131434                 var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName);
131435                 changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization);
131436             }
131437             else if (ts.isPrivateIdentifier(token)) {
131438                 var property = ts.createProperty(
131439                 /*decorators*/ undefined, 
131440                 /*modifiers*/ undefined, tokenName, 
131441                 /*questionToken*/ undefined, 
131442                 /*type*/ undefined, 
131443                 /*initializer*/ undefined);
131444                 var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
131445                 if (lastProp) {
131446                     changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
131447                 }
131448                 else {
131449                     changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
131450                 }
131451             }
131452             else {
131453                 var classConstructor = ts.getFirstConstructorWithBody(classDeclaration);
131454                 if (!classConstructor) {
131455                     return;
131456                 }
131457                 var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName);
131458                 changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization);
131459             }
131460         }
131461         function initializePropertyToUndefined(obj, propertyName) {
131462             return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined")));
131463         }
131464         function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) {
131465             var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token);
131466             var actions = [createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, makeStatic ? 32 /* Static */ : 0)];
131467             if (makeStatic || ts.isPrivateIdentifier(token)) {
131468                 return actions;
131469             }
131470             if (ts.startsWithUnderscore(token.text)) {
131471                 actions.unshift(createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, 8 /* Private */));
131472             }
131473             actions.push(createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode));
131474             return actions;
131475         }
131476         function getTypeNode(checker, classDeclaration, token) {
131477             var typeNode;
131478             if (token.parent.parent.kind === 209 /* BinaryExpression */) {
131479                 var binaryExpression = token.parent.parent;
131480                 var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
131481                 var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression)));
131482                 typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined);
131483             }
131484             else {
131485                 var contextualType = checker.getContextualType(token.parent);
131486                 typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined;
131487             }
131488             return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */);
131489         }
131490         function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags) {
131491             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags); });
131492             if (modifierFlags & 8 /* Private */) {
131493                 return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Declare_private_property_0, tokenName]);
131494             }
131495             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);
131496         }
131497         function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags) {
131498             var property = ts.createProperty(
131499             /*decorators*/ undefined, 
131500             /*modifiers*/ modifierFlags ? ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined, tokenName, 
131501             /*questionToken*/ undefined, typeNode, 
131502             /*initializer*/ undefined);
131503             var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
131504             if (lastProp) {
131505                 changeTracker.insertNodeAfter(declSourceFile, lastProp, property);
131506             }
131507             else {
131508                 changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property);
131509             }
131510         }
131511         // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
131512         function getNodeToInsertPropertyAfter(cls) {
131513             var res;
131514             for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
131515                 var member = _a[_i];
131516                 if (!ts.isPropertyDeclaration(member))
131517                     break;
131518                 res = member;
131519             }
131520             return res;
131521         }
131522         function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) {
131523             // Index signatures cannot have the static modifier.
131524             var stringTypeNode = ts.createKeywordTypeNode(143 /* StringKeyword */);
131525             var indexingParameter = ts.createParameter(
131526             /*decorators*/ undefined, 
131527             /*modifiers*/ undefined, 
131528             /*dotDotDotToken*/ undefined, "x", 
131529             /*questionToken*/ undefined, stringTypeNode, 
131530             /*initializer*/ undefined);
131531             var indexSignature = ts.createIndexSignature(
131532             /*decorators*/ undefined, 
131533             /*modifiers*/ undefined, [indexingParameter], typeNode);
131534             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); });
131535             // No fixId here because code-fix-all currently only works on adding individual named properties.
131536             return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
131537         }
131538         function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) {
131539             // Private methods are not implemented yet.
131540             if (ts.isPrivateIdentifier(token)) {
131541                 return undefined;
131542             }
131543             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); });
131544             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);
131545         }
131546         function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) {
131547             var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host);
131548             var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder);
131549             var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */);
131550             if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) {
131551                 changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration);
131552             }
131553             else {
131554                 changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration);
131555             }
131556             importAdder.writeFixes(changeTracker);
131557         }
131558         function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) {
131559             /**
131560              * create initializer only literal enum that has string initializer.
131561              * value of initializer is a string literal that equal to name of enum member.
131562              * numeric enum or empty enum will not create initializer.
131563              */
131564             var hasStringInitializer = ts.some(enumDeclaration.members, function (member) {
131565                 var type = checker.getTypeAtLocation(member);
131566                 return !!(type && type.flags & 132 /* StringLike */);
131567             });
131568             var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined);
131569             changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))), {
131570                 leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
131571                 trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude
131572             });
131573         }
131574     })(codefix = ts.codefix || (ts.codefix = {}));
131575 })(ts || (ts = {}));
131576 /* @internal */
131577 var ts;
131578 (function (ts) {
131579     var codefix;
131580     (function (codefix) {
131581         var fixId = "addMissingNewOperator";
131582         var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
131583         codefix.registerCodeFix({
131584             errorCodes: errorCodes,
131585             getCodeActions: function (context) {
131586                 var sourceFile = context.sourceFile, span = context.span;
131587                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
131588                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
131589             },
131590             fixIds: [fixId],
131591             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131592                 return addMissingNewOperator(changes, context.sourceFile, diag);
131593             }); },
131594         });
131595         function addMissingNewOperator(changes, sourceFile, span) {
131596             var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
131597             var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
131598             changes.replaceNode(sourceFile, call, newExpression);
131599         }
131600         function findAncestorMatchingSpan(sourceFile, span) {
131601             var token = ts.getTokenAtPosition(sourceFile, span.start);
131602             var end = ts.textSpanEnd(span);
131603             while (token.end < end) {
131604                 token = token.parent;
131605             }
131606             return token;
131607         }
131608     })(codefix = ts.codefix || (ts.codefix = {}));
131609 })(ts || (ts = {}));
131610 /* @internal */
131611 var ts;
131612 (function (ts) {
131613     var codefix;
131614     (function (codefix) {
131615         var fixName = "fixCannotFindModule";
131616         var fixIdInstallTypesPackage = "installTypesPackage";
131617         var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code;
131618         var errorCodes = [
131619             errorCodeCannotFindModule,
131620             ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code,
131621         ];
131622         codefix.registerCodeFix({
131623             errorCodes: errorCodes,
131624             getCodeActions: function (context) {
131625                 var host = context.host, sourceFile = context.sourceFile, start = context.span.start;
131626                 var packageName = tryGetImportedPackageName(sourceFile, start);
131627                 if (packageName === undefined)
131628                     return undefined;
131629                 var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode);
131630                 return typesPackageName === undefined
131631                     ? []
131632                     : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))];
131633             },
131634             fixIds: [fixIdInstallTypesPackage],
131635             getAllCodeActions: function (context) {
131636                 return codefix.codeFixAll(context, errorCodes, function (_changes, diag, commands) {
131637                     var packageName = tryGetImportedPackageName(diag.file, diag.start);
131638                     if (packageName === undefined)
131639                         return undefined;
131640                     switch (context.fixId) {
131641                         case fixIdInstallTypesPackage: {
131642                             var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code);
131643                             if (pkg) {
131644                                 commands.push(getInstallCommand(diag.file.fileName, pkg));
131645                             }
131646                             break;
131647                         }
131648                         default:
131649                             ts.Debug.fail("Bad fixId: " + context.fixId);
131650                     }
131651                 });
131652             },
131653         });
131654         function getInstallCommand(fileName, packageName) {
131655             return { type: "install package", file: fileName, packageName: packageName };
131656         }
131657         function tryGetImportedPackageName(sourceFile, pos) {
131658             var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text;
131659             var packageName = ts.parsePackageName(moduleName).packageName;
131660             return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName;
131661         }
131662         function getTypesPackageNameToInstall(packageName, host, diagCode) {
131663             return diagCode === errorCodeCannotFindModule
131664                 ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
131665                 : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217
131666         }
131667     })(codefix = ts.codefix || (ts.codefix = {}));
131668 })(ts || (ts = {}));
131669 /* @internal */
131670 var ts;
131671 (function (ts) {
131672     var codefix;
131673     (function (codefix) {
131674         var errorCodes = [
131675             ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code,
131676             ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code,
131677         ];
131678         var fixId = "fixClassDoesntImplementInheritedAbstractMember";
131679         codefix.registerCodeFix({
131680             errorCodes: errorCodes,
131681             getCodeActions: function (context) {
131682                 var sourceFile = context.sourceFile, span = context.span;
131683                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
131684                     return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences);
131685                 });
131686                 return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)];
131687             },
131688             fixIds: [fixId],
131689             getAllCodeActions: function (context) {
131690                 var seenClassDeclarations = ts.createMap();
131691                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131692                     var classDeclaration = getClass(diag.file, diag.start);
131693                     if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) {
131694                         addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences);
131695                     }
131696                 });
131697             },
131698         });
131699         function getClass(sourceFile, pos) {
131700             // Token is the identifier in the case of a class declaration
131701             // or the class keyword token in the case of a class expression.
131702             var token = ts.getTokenAtPosition(sourceFile, pos);
131703             return ts.cast(token.parent, ts.isClassLike);
131704         }
131705         function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) {
131706             var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration);
131707             var checker = context.program.getTypeChecker();
131708             var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
131709             // Note that this is ultimately derived from a map indexed by symbol names,
131710             // so duplicates cannot occur.
131711             var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
131712             var importAdder = codefix.createImportAdder(sourceFile, context.program, preferences, context.host);
131713             codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, importAdder, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); });
131714             importAdder.writeFixes(changeTracker);
131715         }
131716         function symbolPointsToNonPrivateAndAbstractMember(symbol) {
131717             // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files
131718             // (now named `codeFixClassExtendAbstractPrivateProperty.ts`)
131719             var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations()));
131720             return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */);
131721         }
131722     })(codefix = ts.codefix || (ts.codefix = {}));
131723 })(ts || (ts = {}));
131724 /* @internal */
131725 var ts;
131726 (function (ts) {
131727     var codefix;
131728     (function (codefix) {
131729         var fixId = "classSuperMustPrecedeThisAccess";
131730         var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code];
131731         codefix.registerCodeFix({
131732             errorCodes: errorCodes,
131733             getCodeActions: function (context) {
131734                 var sourceFile = context.sourceFile, span = context.span;
131735                 var nodes = getNodes(sourceFile, span.start);
131736                 if (!nodes)
131737                     return undefined;
131738                 var constructor = nodes.constructor, superCall = nodes.superCall;
131739                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); });
131740                 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)];
131741             },
131742             fixIds: [fixId],
131743             getAllCodeActions: function (context) {
131744                 var sourceFile = context.sourceFile;
131745                 var seenClasses = ts.createMap(); // Ensure we only do this once per class.
131746                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131747                     var nodes = getNodes(diag.file, diag.start);
131748                     if (!nodes)
131749                         return;
131750                     var constructor = nodes.constructor, superCall = nodes.superCall;
131751                     if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) {
131752                         doChange(changes, sourceFile, constructor, superCall);
131753                     }
131754                 });
131755             },
131756         });
131757         function doChange(changes, sourceFile, constructor, superCall) {
131758             changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
131759             changes.delete(sourceFile, superCall);
131760         }
131761         function getNodes(sourceFile, pos) {
131762             var token = ts.getTokenAtPosition(sourceFile, pos);
131763             if (token.kind !== 104 /* ThisKeyword */)
131764                 return undefined;
131765             var constructor = ts.getContainingFunction(token);
131766             var superCall = findSuperCall(constructor.body);
131767             // figure out if the `this` access is actually inside the supercall
131768             // i.e. super(this.a), since in that case we won't suggest a fix
131769             return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined;
131770         }
131771         function findSuperCall(n) {
131772             return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression)
131773                 ? n
131774                 : ts.isFunctionLike(n)
131775                     ? undefined
131776                     : ts.forEachChild(n, findSuperCall);
131777         }
131778     })(codefix = ts.codefix || (ts.codefix = {}));
131779 })(ts || (ts = {}));
131780 /* @internal */
131781 var ts;
131782 (function (ts) {
131783     var codefix;
131784     (function (codefix) {
131785         var fixId = "constructorForDerivedNeedSuperCall";
131786         var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code];
131787         codefix.registerCodeFix({
131788             errorCodes: errorCodes,
131789             getCodeActions: function (context) {
131790                 var sourceFile = context.sourceFile, span = context.span;
131791                 var ctr = getNode(sourceFile, span.start);
131792                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); });
131793                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)];
131794             },
131795             fixIds: [fixId],
131796             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131797                 return doChange(changes, context.sourceFile, getNode(diag.file, diag.start));
131798             }); },
131799         });
131800         function getNode(sourceFile, pos) {
131801             var token = ts.getTokenAtPosition(sourceFile, pos);
131802             ts.Debug.assert(ts.isConstructorDeclaration(token.parent), "token should be at the constructor declaration");
131803             return token.parent;
131804         }
131805         function doChange(changes, sourceFile, ctr) {
131806             var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray));
131807             changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall);
131808         }
131809     })(codefix = ts.codefix || (ts.codefix = {}));
131810 })(ts || (ts = {}));
131811 /* @internal */
131812 var ts;
131813 (function (ts) {
131814     var codefix;
131815     (function (codefix) {
131816         var fixId = "enableExperimentalDecorators";
131817         var errorCodes = [
131818             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
131819         ];
131820         codefix.registerCodeFix({
131821             errorCodes: errorCodes,
131822             getCodeActions: function (context) {
131823                 var configFile = context.program.getCompilerOptions().configFile;
131824                 if (configFile === undefined) {
131825                     return undefined;
131826                 }
131827                 var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); });
131828                 return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
131829             },
131830             fixIds: [fixId],
131831             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) {
131832                 var configFile = context.program.getCompilerOptions().configFile;
131833                 if (configFile === undefined) {
131834                     return undefined;
131835                 }
131836                 doChange(changes, configFile);
131837             }); },
131838         });
131839         function doChange(changeTracker, configFile) {
131840             codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue());
131841         }
131842     })(codefix = ts.codefix || (ts.codefix = {}));
131843 })(ts || (ts = {}));
131844 /* @internal */
131845 var ts;
131846 (function (ts) {
131847     var codefix;
131848     (function (codefix) {
131849         var fixID = "fixEnableJsxFlag";
131850         var errorCodes = [ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code];
131851         codefix.registerCodeFix({
131852             errorCodes: errorCodes,
131853             getCodeActions: function (context) {
131854                 var configFile = context.program.getCompilerOptions().configFile;
131855                 if (configFile === undefined) {
131856                     return undefined;
131857                 }
131858                 var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) {
131859                     return doChange(changeTracker, configFile);
131860                 });
131861                 return [
131862                     codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file)
131863                 ];
131864             },
131865             fixIds: [fixID],
131866             getAllCodeActions: function (context) {
131867                 return codefix.codeFixAll(context, errorCodes, function (changes) {
131868                     var configFile = context.program.getCompilerOptions().configFile;
131869                     if (configFile === undefined) {
131870                         return undefined;
131871                     }
131872                     doChange(changes, configFile);
131873                 });
131874             }
131875         });
131876         function doChange(changeTracker, configFile) {
131877             codefix.setJsonCompilerOptionValue(changeTracker, configFile, "jsx", ts.createStringLiteral("react"));
131878         }
131879     })(codefix = ts.codefix || (ts.codefix = {}));
131880 })(ts || (ts = {}));
131881 /* @internal */
131882 var ts;
131883 (function (ts) {
131884     var codefix;
131885     (function (codefix) {
131886         codefix.registerCodeFix({
131887             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],
131888             getCodeActions: function (context) {
131889                 var compilerOptions = context.program.getCompilerOptions();
131890                 var configFile = compilerOptions.configFile;
131891                 if (configFile === undefined) {
131892                     return undefined;
131893                 }
131894                 var codeFixes = [];
131895                 var moduleKind = ts.getEmitModuleKind(compilerOptions);
131896                 var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext;
131897                 if (moduleOutOfRange) {
131898                     var changes = ts.textChanges.ChangeTracker.with(context, function (changes) {
131899                         codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext"));
131900                     });
131901                     codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"]));
131902                 }
131903                 var target = ts.getEmitScriptTarget(compilerOptions);
131904                 var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */;
131905                 if (targetOutOfRange) {
131906                     var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
131907                         var configObject = ts.getTsConfigObjectLiteralExpression(configFile);
131908                         if (!configObject)
131909                             return;
131910                         var options = [["target", ts.createStringLiteral("es2017")]];
131911                         if (moduleKind === ts.ModuleKind.CommonJS) {
131912                             // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015.
131913                             options.push(["module", ts.createStringLiteral("commonjs")]);
131914                         }
131915                         codefix.setJsonCompilerOptionValues(tracker, configFile, options);
131916                     });
131917                     codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"]));
131918                 }
131919                 return codeFixes.length ? codeFixes : undefined;
131920             }
131921         });
131922     })(codefix = ts.codefix || (ts.codefix = {}));
131923 })(ts || (ts = {}));
131924 /* @internal */
131925 var ts;
131926 (function (ts) {
131927     var codefix;
131928     (function (codefix) {
131929         var fixId = "extendsInterfaceBecomesImplements";
131930         var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
131931         codefix.registerCodeFix({
131932             errorCodes: errorCodes,
131933             getCodeActions: function (context) {
131934                 var sourceFile = context.sourceFile;
131935                 var nodes = getNodes(sourceFile, context.span.start);
131936                 if (!nodes)
131937                     return undefined;
131938                 var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses;
131939                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); });
131940                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)];
131941             },
131942             fixIds: [fixId],
131943             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
131944                 var nodes = getNodes(diag.file, diag.start);
131945                 if (nodes)
131946                     doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses);
131947             }); },
131948         });
131949         function getNodes(sourceFile, pos) {
131950             var token = ts.getTokenAtPosition(sourceFile, pos);
131951             var heritageClauses = ts.getContainingClass(token).heritageClauses;
131952             var extendsToken = heritageClauses[0].getFirstToken();
131953             return extendsToken.kind === 90 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined;
131954         }
131955         function doChanges(changes, sourceFile, extendsToken, heritageClauses) {
131956             changes.replaceNode(sourceFile, extendsToken, ts.createToken(113 /* ImplementsKeyword */));
131957             // If there is already an implements clause, replace the implements keyword with a comma.
131958             if (heritageClauses.length === 2 &&
131959                 heritageClauses[0].token === 90 /* ExtendsKeyword */ &&
131960                 heritageClauses[1].token === 113 /* ImplementsKeyword */) {
131961                 var implementsToken = heritageClauses[1].getFirstToken();
131962                 var implementsFullStart = implementsToken.getFullStart();
131963                 changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(27 /* CommaToken */));
131964                 // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive.
131965                 // (Trailing because leading might be indentation, which is more sensitive.)
131966                 var text = sourceFile.text;
131967                 var end = implementsToken.end;
131968                 while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) {
131969                     end++;
131970                 }
131971                 changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end });
131972             }
131973         }
131974     })(codefix = ts.codefix || (ts.codefix = {}));
131975 })(ts || (ts = {}));
131976 /* @internal */
131977 var ts;
131978 (function (ts) {
131979     var codefix;
131980     (function (codefix) {
131981         var fixId = "forgottenThisPropertyAccess";
131982         var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
131983         var errorCodes = [
131984             ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
131985             ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
131986             didYouMeanStaticMemberCode,
131987         ];
131988         codefix.registerCodeFix({
131989             errorCodes: errorCodes,
131990             getCodeActions: function (context) {
131991                 var sourceFile = context.sourceFile;
131992                 var info = getInfo(sourceFile, context.span.start, context.errorCode);
131993                 if (!info) {
131994                     return undefined;
131995                 }
131996                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
131997                 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)];
131998             },
131999             fixIds: [fixId],
132000             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
132001                 var info = getInfo(diag.file, diag.start, diag.code);
132002                 if (info)
132003                     doChange(changes, context.sourceFile, info);
132004             }); },
132005         });
132006         function getInfo(sourceFile, pos, diagCode) {
132007             var node = ts.getTokenAtPosition(sourceFile, pos);
132008             if (ts.isIdentifier(node)) {
132009                 return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined };
132010             }
132011         }
132012         function doChange(changes, sourceFile, _a) {
132013             var node = _a.node, className = _a.className;
132014             // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper
132015             ts.suppressLeadingAndTrailingTrivia(node);
132016             changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node));
132017         }
132018     })(codefix = ts.codefix || (ts.codefix = {}));
132019 })(ts || (ts = {}));
132020 /* @internal */
132021 var ts;
132022 (function (ts) {
132023     var codefix;
132024     (function (codefix) {
132025         var fixIdExpression = "fixInvalidJsxCharacters_expression";
132026         var fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity";
132027         var errorCodes = [
132028             ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt.code,
132029             ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code
132030         ];
132031         codefix.registerCodeFix({
132032             errorCodes: errorCodes,
132033             fixIds: [fixIdExpression, fixIdHtmlEntity],
132034             getCodeActions: function (context) {
132035                 var sourceFile = context.sourceFile, preferences = context.preferences, span = context.span;
132036                 var changeToExpression = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, preferences, sourceFile, span.start, /* useHtmlEntity */ false); });
132037                 var changeToHtmlEntity = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, preferences, sourceFile, span.start, /* useHtmlEntity */ true); });
132038                 return [
132039                     codefix.createCodeFixAction(fixIdExpression, changeToExpression, ts.Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, ts.Diagnostics.Wrap_all_invalid_characters_in_an_expression_container),
132040                     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)
132041                 ];
132042             },
132043             getAllCodeActions: function (context) {
132044                 return codefix.codeFixAll(context, errorCodes, function (changes, diagnostic) { return doChange(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity); });
132045             }
132046         });
132047         var htmlEntity = {
132048             ">": "&gt;",
132049             "}": "&rbrace;",
132050         };
132051         function isValidCharacter(character) {
132052             return ts.hasProperty(htmlEntity, character);
132053         }
132054         function doChange(changes, preferences, sourceFile, start, useHtmlEntity) {
132055             var character = sourceFile.getText()[start];
132056             // sanity check
132057             if (!isValidCharacter(character)) {
132058                 return;
132059             }
132060             var replacement = useHtmlEntity ? htmlEntity[character] : "{" + ts.quote(character, preferences) + "}";
132061             changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement);
132062         }
132063     })(codefix = ts.codefix || (ts.codefix = {}));
132064 })(ts || (ts = {}));
132065 /* @internal */
132066 var ts;
132067 (function (ts) {
132068     var codefix;
132069     (function (codefix) {
132070         var fixName = "unusedIdentifier";
132071         var fixIdPrefix = "unusedIdentifier_prefix";
132072         var fixIdDelete = "unusedIdentifier_delete";
132073         var fixIdInfer = "unusedIdentifier_infer";
132074         var errorCodes = [
132075             ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code,
132076             ts.Diagnostics._0_is_declared_but_never_used.code,
132077             ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
132078             ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
132079             ts.Diagnostics.All_destructured_elements_are_unused.code,
132080             ts.Diagnostics.All_variables_are_unused.code,
132081             ts.Diagnostics.All_type_parameters_are_unused.code,
132082         ];
132083         codefix.registerCodeFix({
132084             errorCodes: errorCodes,
132085             getCodeActions: function (context) {
132086                 var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program;
132087                 var checker = program.getTypeChecker();
132088                 var sourceFiles = program.getSourceFiles();
132089                 var token = ts.getTokenAtPosition(sourceFile, context.span.start);
132090                 if (ts.isJSDocTemplateTag(token)) {
132091                     return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)];
132092                 }
132093                 if (token.kind === 29 /* LessThanToken */) {
132094                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); });
132095                     return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)];
132096                 }
132097                 var importDecl = tryGetFullImport(token);
132098                 if (importDecl) {
132099                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); });
132100                     return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])];
132101                 }
132102                 var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) {
132103                     return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false);
132104                 });
132105                 if (delDestructure.length) {
132106                     return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)];
132107                 }
132108                 var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); });
132109                 if (delVar.length) {
132110                     return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)];
132111                 }
132112                 var result = [];
132113                 if (token.kind === 132 /* InferKeyword */) {
132114                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); });
132115                     var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text;
132116                     result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown));
132117                 }
132118                 else {
132119                     var deletion = ts.textChanges.ChangeTracker.with(context, function (t) {
132120                         return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false);
132121                     });
132122                     if (deletion.length) {
132123                         var name = ts.isComputedPropertyName(token.parent) ? token.parent : token;
132124                         result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)]));
132125                     }
132126                 }
132127                 var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); });
132128                 if (prefix.length) {
132129                     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));
132130                 }
132131                 return result;
132132             },
132133             fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer],
132134             getAllCodeActions: function (context) {
132135                 var sourceFile = context.sourceFile, program = context.program;
132136                 var checker = program.getTypeChecker();
132137                 var sourceFiles = program.getSourceFiles();
132138                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
132139                     var token = ts.getTokenAtPosition(sourceFile, diag.start);
132140                     switch (context.fixId) {
132141                         case fixIdPrefix:
132142                             tryPrefixDeclaration(changes, diag.code, sourceFile, token);
132143                             break;
132144                         case fixIdDelete: {
132145                             if (token.kind === 132 /* InferKeyword */)
132146                                 break; // Can't delete
132147                             var importDecl = tryGetFullImport(token);
132148                             if (importDecl) {
132149                                 changes.delete(sourceFile, importDecl);
132150                             }
132151                             else if (ts.isJSDocTemplateTag(token)) {
132152                                 changes.delete(sourceFile, token);
132153                             }
132154                             else if (token.kind === 29 /* LessThanToken */) {
132155                                 deleteTypeParameters(changes, sourceFile, token);
132156                             }
132157                             else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) &&
132158                                 !tryDeleteFullVariableStatement(sourceFile, token, changes)) {
132159                                 tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true);
132160                             }
132161                             break;
132162                         }
132163                         case fixIdInfer:
132164                             if (token.kind === 132 /* InferKeyword */) {
132165                                 changeInferToUnknown(changes, sourceFile, token);
132166                             }
132167                             break;
132168                         default:
132169                             ts.Debug.fail(JSON.stringify(context.fixId));
132170                     }
132171                 });
132172             },
132173         });
132174         function changeInferToUnknown(changes, sourceFile, token) {
132175             changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(148 /* UnknownKeyword */));
132176         }
132177         function createDeleteFix(changes, diag) {
132178             return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations);
132179         }
132180         function deleteTypeParameters(changes, sourceFile, token) {
132181             changes.delete(sourceFile, ts.Debug.checkDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
132182         }
132183         // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
132184         function tryGetFullImport(token) {
132185             return token.kind === 96 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined;
132186         }
132187         function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
132188             if (token.kind !== 18 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent))
132189                 return false;
132190             var decl = token.parent.parent;
132191             if (decl.kind === 156 /* Parameter */) {
132192                 tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll);
132193             }
132194             else {
132195                 changes.delete(sourceFile, decl);
132196             }
132197             return true;
132198         }
132199         function tryDeleteFullVariableStatement(sourceFile, token, changes) {
132200             var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList);
132201             if (declarationList && declarationList.getChildren(sourceFile)[0] === token) {
132202                 changes.delete(sourceFile, declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList);
132203                 return true;
132204             }
132205             return false;
132206         }
132207         function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
132208             // Don't offer to prefix a property.
132209             if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code)
132210                 return;
132211             if (token.kind === 132 /* InferKeyword */) {
132212                 token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name;
132213             }
132214             if (ts.isIdentifier(token) && canPrefix(token)) {
132215                 changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text));
132216                 if (ts.isParameter(token.parent)) {
132217                     ts.getJSDocParameterTags(token.parent).forEach(function (tag) {
132218                         if (ts.isIdentifier(tag.name)) {
132219                             changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text));
132220                         }
132221                     });
132222                 }
132223             }
132224         }
132225         function canPrefix(token) {
132226             switch (token.parent.kind) {
132227                 case 156 /* Parameter */:
132228                 case 155 /* TypeParameter */:
132229                     return true;
132230                 case 242 /* VariableDeclaration */: {
132231                     var varDecl = token.parent;
132232                     switch (varDecl.parent.parent.kind) {
132233                         case 232 /* ForOfStatement */:
132234                         case 231 /* ForInStatement */:
132235                             return true;
132236                     }
132237                 }
132238             }
132239             return false;
132240         }
132241         function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) {
132242             tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll);
132243             if (ts.isIdentifier(token))
132244                 deleteAssignments(changes, sourceFile, token, checker);
132245         }
132246         function deleteAssignments(changes, sourceFile, token, checker) {
132247             ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
132248                 if (ts.isPropertyAccessExpression(ref.parent) && ref.parent.name === ref)
132249                     ref = ref.parent;
132250                 if (ts.isBinaryExpression(ref.parent) && ts.isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) {
132251                     changes.delete(sourceFile, ref.parent.parent);
132252                 }
132253             });
132254         }
132255         function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
132256             var parent = token.parent;
132257             if (ts.isParameter(parent)) {
132258                 tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll);
132259             }
132260             else {
132261                 changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent);
132262             }
132263         }
132264         function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) {
132265             if (mayDeleteParameter(p, checker, isFixAll)) {
132266                 if (p.modifiers && p.modifiers.length > 0
132267                     && (!ts.isIdentifier(p.name) || ts.FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) {
132268                     p.modifiers.forEach(function (modifier) {
132269                         changes.deleteModifier(sourceFile, modifier);
132270                     });
132271                 }
132272                 else {
132273                     changes.delete(sourceFile, p);
132274                     deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker);
132275                 }
132276             }
132277         }
132278         function mayDeleteParameter(p, checker, isFixAll) {
132279             var parent = p.parent;
132280             switch (parent.kind) {
132281                 case 161 /* MethodDeclaration */:
132282                     // Don't remove a parameter if this overrides something.
132283                     var symbol = checker.getSymbolAtLocation(parent.name);
132284                     if (ts.isMemberSymbolInBaseType(symbol, checker))
132285                         return false;
132286                 // falls through
132287                 case 162 /* Constructor */:
132288                 case 244 /* FunctionDeclaration */:
132289                     return true;
132290                 case 201 /* FunctionExpression */:
132291                 case 202 /* ArrowFunction */: {
132292                     // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused.
132293                     var parameters = parent.parameters;
132294                     var index = parameters.indexOf(p);
132295                     ts.Debug.assert(index !== -1, "The parameter should already be in the list");
132296                     return isFixAll
132297                         ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 75 /* Identifier */ && !p.symbol.isReferenced; })
132298                         : index === parameters.length - 1;
132299                 }
132300                 case 164 /* SetAccessor */:
132301                     // Setter must have a parameter
132302                     return false;
132303                 default:
132304                     return ts.Debug.failBadSyntaxKind(parent);
132305             }
132306         }
132307         function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) {
132308             ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) {
132309                 var index = deletedParameter.parent.parameters.indexOf(deletedParameter);
132310                 if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments.
132311                     changes.delete(sourceFile, call.arguments[index]);
132312                 }
132313             });
132314         }
132315     })(codefix = ts.codefix || (ts.codefix = {}));
132316 })(ts || (ts = {}));
132317 /* @internal */
132318 var ts;
132319 (function (ts) {
132320     var codefix;
132321     (function (codefix) {
132322         var fixId = "fixUnreachableCode";
132323         var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
132324         codefix.registerCodeFix({
132325             errorCodes: errorCodes,
132326             getCodeActions: function (context) {
132327                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length, context.errorCode); });
132328                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
132329             },
132330             fixIds: [fixId],
132331             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length, diag.code); }); },
132332         });
132333         function doChange(changes, sourceFile, start, length, errorCode) {
132334             var token = ts.getTokenAtPosition(sourceFile, start);
132335             var statement = ts.findAncestor(token, ts.isStatement);
132336             if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) {
132337                 var logData = JSON.stringify({
132338                     statementKind: ts.Debug.formatSyntaxKind(statement.kind),
132339                     tokenKind: ts.Debug.formatSyntaxKind(token.kind),
132340                     errorCode: errorCode,
132341                     start: start,
132342                     length: length
132343                 });
132344                 ts.Debug.fail("Token and statement should start at the same point. " + logData);
132345             }
132346             var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent;
132347             if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) {
132348                 switch (container.kind) {
132349                     case 227 /* IfStatement */:
132350                         if (container.elseStatement) {
132351                             if (ts.isBlock(statement.parent)) {
132352                                 break;
132353                             }
132354                             else {
132355                                 changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
132356                             }
132357                             return;
132358                         }
132359                     // falls through
132360                     case 229 /* WhileStatement */:
132361                     case 230 /* ForStatement */:
132362                         changes.delete(sourceFile, container);
132363                         return;
132364                 }
132365             }
132366             if (ts.isBlock(statement.parent)) {
132367                 var end_3 = start + length;
132368                 var lastStatement = ts.Debug.checkDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_3; }), "Some statement should be last");
132369                 changes.deleteNodeRange(sourceFile, statement, lastStatement);
132370             }
132371             else {
132372                 changes.delete(sourceFile, statement);
132373             }
132374         }
132375         function lastWhere(a, pred) {
132376             var last;
132377             for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
132378                 var value = a_1[_i];
132379                 if (!pred(value))
132380                     break;
132381                 last = value;
132382             }
132383             return last;
132384         }
132385     })(codefix = ts.codefix || (ts.codefix = {}));
132386 })(ts || (ts = {}));
132387 /* @internal */
132388 var ts;
132389 (function (ts) {
132390     var codefix;
132391     (function (codefix) {
132392         var fixId = "fixUnusedLabel";
132393         var errorCodes = [ts.Diagnostics.Unused_label.code];
132394         codefix.registerCodeFix({
132395             errorCodes: errorCodes,
132396             getCodeActions: function (context) {
132397                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
132398                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
132399             },
132400             fixIds: [fixId],
132401             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
132402         });
132403         function doChange(changes, sourceFile, start) {
132404             var token = ts.getTokenAtPosition(sourceFile, start);
132405             var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
132406             var pos = token.getStart(sourceFile);
132407             var statementPos = labeledStatement.statement.getStart(sourceFile);
132408             // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
132409             var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
132410                 : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 58 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
132411             changes.deleteRange(sourceFile, { pos: pos, end: end });
132412         }
132413     })(codefix = ts.codefix || (ts.codefix = {}));
132414 })(ts || (ts = {}));
132415 /* @internal */
132416 var ts;
132417 (function (ts) {
132418     var codefix;
132419     (function (codefix) {
132420         var fixIdPlain = "fixJSDocTypes_plain";
132421         var fixIdNullable = "fixJSDocTypes_nullable";
132422         var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code];
132423         codefix.registerCodeFix({
132424             errorCodes: errorCodes,
132425             getCodeActions: function (context) {
132426                 var sourceFile = context.sourceFile;
132427                 var checker = context.program.getTypeChecker();
132428                 var info = getInfo(sourceFile, context.span.start, checker);
132429                 if (!info)
132430                     return undefined;
132431                 var typeNode = info.typeNode, type = info.type;
132432                 var original = typeNode.getText(sourceFile);
132433                 var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
132434                 if (typeNode.kind === 297 /* JSDocNullableType */) {
132435                     // for nullable types, suggest the flow-compatible `T | null | undefined`
132436                     // in addition to the jsdoc/closure-compatible `T | null`
132437                     actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
132438                 }
132439                 return actions;
132440                 function fix(type, fixId, fixAllDescription) {
132441                     var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); });
132442                     return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription);
132443                 }
132444             },
132445             fixIds: [fixIdPlain, fixIdNullable],
132446             getAllCodeActions: function (context) {
132447                 var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile;
132448                 var checker = program.getTypeChecker();
132449                 return codefix.codeFixAll(context, errorCodes, function (changes, err) {
132450                     var info = getInfo(err.file, err.start, checker);
132451                     if (!info)
132452                         return;
132453                     var typeNode = info.typeNode, type = info.type;
132454                     var fixedType = typeNode.kind === 297 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
132455                     doChange(changes, sourceFile, typeNode, fixedType, checker);
132456                 });
132457             }
132458         });
132459         function doChange(changes, sourceFile, oldTypeNode, newType, checker) {
132460             changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217
132461         }
132462         function getInfo(sourceFile, pos, checker) {
132463             var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer);
132464             var typeNode = decl && decl.type;
132465             return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) };
132466         }
132467         function isTypeContainer(node) {
132468             // NOTE: Some locations are not handled yet:
132469             // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments
132470             switch (node.kind) {
132471                 case 217 /* AsExpression */:
132472                 case 165 /* CallSignature */:
132473                 case 166 /* ConstructSignature */:
132474                 case 244 /* FunctionDeclaration */:
132475                 case 163 /* GetAccessor */:
132476                 case 167 /* IndexSignature */:
132477                 case 186 /* MappedType */:
132478                 case 161 /* MethodDeclaration */:
132479                 case 160 /* MethodSignature */:
132480                 case 156 /* Parameter */:
132481                 case 159 /* PropertyDeclaration */:
132482                 case 158 /* PropertySignature */:
132483                 case 164 /* SetAccessor */:
132484                 case 247 /* TypeAliasDeclaration */:
132485                 case 199 /* TypeAssertionExpression */:
132486                 case 242 /* VariableDeclaration */:
132487                     return true;
132488                 default:
132489                     return false;
132490             }
132491         }
132492     })(codefix = ts.codefix || (ts.codefix = {}));
132493 })(ts || (ts = {}));
132494 /* @internal */
132495 var ts;
132496 (function (ts) {
132497     var codefix;
132498     (function (codefix) {
132499         var fixId = "fixMissingCallParentheses";
132500         var errorCodes = [
132501             ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code,
132502         ];
132503         codefix.registerCodeFix({
132504             errorCodes: errorCodes,
132505             fixIds: [fixId],
132506             getCodeActions: function (context) {
132507                 var sourceFile = context.sourceFile, span = context.span;
132508                 var callName = getCallName(sourceFile, span.start);
132509                 if (!callName)
132510                     return;
132511                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, callName); });
132512                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_call_parentheses, fixId, ts.Diagnostics.Add_all_missing_call_parentheses)];
132513             },
132514             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
132515                 var callName = getCallName(diag.file, diag.start);
132516                 if (callName)
132517                     doChange(changes, diag.file, callName);
132518             }); }
132519         });
132520         function doChange(changes, sourceFile, name) {
132521             changes.replaceNodeWithText(sourceFile, name, name.text + "()");
132522         }
132523         function getCallName(sourceFile, start) {
132524             var token = ts.getTokenAtPosition(sourceFile, start);
132525             if (ts.isPropertyAccessExpression(token.parent)) {
132526                 var current = token.parent;
132527                 while (ts.isPropertyAccessExpression(current.parent)) {
132528                     current = current.parent;
132529                 }
132530                 return current.name;
132531             }
132532             if (ts.isIdentifier(token)) {
132533                 return token;
132534             }
132535             return undefined;
132536         }
132537     })(codefix = ts.codefix || (ts.codefix = {}));
132538 })(ts || (ts = {}));
132539 /* @internal */
132540 var ts;
132541 (function (ts) {
132542     var codefix;
132543     (function (codefix) {
132544         var fixId = "fixAwaitInSyncFunction";
132545         var errorCodes = [
132546             ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
132547             ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code,
132548         ];
132549         codefix.registerCodeFix({
132550             errorCodes: errorCodes,
132551             getCodeActions: function (context) {
132552                 var sourceFile = context.sourceFile, span = context.span;
132553                 var nodes = getNodes(sourceFile, span.start);
132554                 if (!nodes)
132555                     return undefined;
132556                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); });
132557                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)];
132558             },
132559             fixIds: [fixId],
132560             getAllCodeActions: function (context) {
132561                 var seen = ts.createMap();
132562                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
132563                     var nodes = getNodes(diag.file, diag.start);
132564                     if (!nodes || !ts.addToSeen(seen, ts.getNodeId(nodes.insertBefore)))
132565                         return;
132566                     doChange(changes, context.sourceFile, nodes);
132567                 });
132568             },
132569         });
132570         function getReturnType(expr) {
132571             if (expr.type) {
132572                 return expr.type;
132573             }
132574             if (ts.isVariableDeclaration(expr.parent) &&
132575                 expr.parent.type &&
132576                 ts.isFunctionTypeNode(expr.parent.type)) {
132577                 return expr.parent.type.type;
132578             }
132579         }
132580         function getNodes(sourceFile, start) {
132581             var token = ts.getTokenAtPosition(sourceFile, start);
132582             var containingFunction = ts.getContainingFunction(token);
132583             if (!containingFunction) {
132584                 return;
132585             }
132586             var insertBefore;
132587             switch (containingFunction.kind) {
132588                 case 161 /* MethodDeclaration */:
132589                     insertBefore = containingFunction.name;
132590                     break;
132591                 case 244 /* FunctionDeclaration */:
132592                 case 201 /* FunctionExpression */:
132593                     insertBefore = ts.findChildOfKind(containingFunction, 94 /* FunctionKeyword */, sourceFile);
132594                     break;
132595                 case 202 /* ArrowFunction */:
132596                     insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters);
132597                     break;
132598                 default:
132599                     return;
132600             }
132601             return insertBefore && {
132602                 insertBefore: insertBefore,
132603                 returnType: getReturnType(containingFunction)
132604             };
132605         }
132606         function doChange(changes, sourceFile, _a) {
132607             var insertBefore = _a.insertBefore, returnType = _a.returnType;
132608             if (returnType) {
132609                 var entityName = ts.getEntityNameFromTypeNode(returnType);
132610                 if (!entityName || entityName.kind !== 75 /* Identifier */ || entityName.text !== "Promise") {
132611                     changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType])));
132612                 }
132613             }
132614             changes.insertModifierBefore(sourceFile, 126 /* AsyncKeyword */, insertBefore);
132615         }
132616     })(codefix = ts.codefix || (ts.codefix = {}));
132617 })(ts || (ts = {}));
132618 /* @internal */
132619 var ts;
132620 (function (ts) {
132621     var codefix;
132622     (function (codefix) {
132623         var fixId = "inferFromUsage";
132624         var errorCodes = [
132625             // Variable declarations
132626             ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code,
132627             // Variable uses
132628             ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code,
132629             // Parameter declarations
132630             ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code,
132631             ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code,
132632             // Get Accessor declarations
132633             ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code,
132634             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code,
132635             // Set Accessor declarations
132636             ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code,
132637             // Property declarations
132638             ts.Diagnostics.Member_0_implicitly_has_an_1_type.code,
132639             //// Suggestions
132640             // Variable declarations
132641             ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code,
132642             // Variable uses
132643             ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
132644             // Parameter declarations
132645             ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
132646             ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code,
132647             // Get Accessor declarations
132648             ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code,
132649             ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code,
132650             // Set Accessor declarations
132651             ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code,
132652             // Property declarations
132653             ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code,
132654             // Function expressions and declarations
132655             ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code,
132656         ];
132657         codefix.registerCodeFix({
132658             errorCodes: errorCodes,
132659             getCodeActions: function (context) {
132660                 var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, preferences = context.preferences;
132661                 var token = ts.getTokenAtPosition(sourceFile, start);
132662                 var declaration;
132663                 var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, preferences); });
132664                 var name = declaration && ts.getNameOfDeclaration(declaration);
132665                 return !name || changes.length === 0 ? undefined
132666                     : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)];
132667             },
132668             fixIds: [fixId],
132669             getAllCodeActions: function (context) {
132670                 var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, preferences = context.preferences;
132671                 var markSeen = ts.nodeSeenTracker();
132672                 return codefix.codeFixAll(context, errorCodes, function (changes, err) {
132673                     doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences);
132674                 });
132675             },
132676         });
132677         function getDiagnostic(errorCode, token) {
132678             switch (errorCode) {
132679                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
132680                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132681                     return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217
132682                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
132683                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
132684                     return ts.Diagnostics.Infer_parameter_types_from_usage;
132685                 case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
132686                     return ts.Diagnostics.Infer_this_type_of_0_from_usage;
132687                 default:
132688                     return ts.Diagnostics.Infer_type_of_0_from_usage;
132689             }
132690         }
132691         /** Map suggestion code to error code */
132692         function mapSuggestionDiagnostic(errorCode) {
132693             switch (errorCode) {
132694                 case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code:
132695                     return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code;
132696                 case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132697                     return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code;
132698                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132699                     return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code;
132700                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code:
132701                     return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code;
132702                 case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code:
132703                     return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code;
132704                 case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code:
132705                     return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code;
132706                 case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code:
132707                     return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code;
132708                 case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code:
132709                     return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code;
132710             }
132711             return errorCode;
132712         }
132713         function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) {
132714             if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 104 /* ThisKeyword */) {
132715                 return undefined;
132716             }
132717             var parent = token.parent;
132718             var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host);
132719             errorCode = mapSuggestionDiagnostic(errorCode);
132720             switch (errorCode) {
132721                 // Variable and Property declarations
132722                 case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
132723                 case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
132724                     if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
132725                         annotateVariableDeclaration(changes, importAdder, sourceFile, parent, program, host, cancellationToken);
132726                         importAdder.writeFixes(changes);
132727                         return parent;
132728                     }
132729                     if (ts.isPropertyAccessExpression(parent)) {
132730                         var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
132731                         var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
132732                         if (typeNode) {
132733                             // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
132734                             var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
132735                             addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]);
132736                         }
132737                         importAdder.writeFixes(changes);
132738                         return parent;
132739                     }
132740                     return undefined;
132741                 case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
132742                     var symbol = program.getTypeChecker().getSymbolAtLocation(token);
132743                     if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
132744                         annotateVariableDeclaration(changes, importAdder, sourceFile, symbol.valueDeclaration, program, host, cancellationToken);
132745                         importAdder.writeFixes(changes);
132746                         return symbol.valueDeclaration;
132747                     }
132748                     return undefined;
132749                 }
132750             }
132751             var containingFunction = ts.getContainingFunction(token);
132752             if (containingFunction === undefined) {
132753                 return undefined;
132754             }
132755             var declaration;
132756             switch (errorCode) {
132757                 // Parameter declarations
132758                 case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
132759                     if (ts.isSetAccessorDeclaration(containingFunction)) {
132760                         annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
132761                         declaration = containingFunction;
132762                         break;
132763                     }
132764                 // falls through
132765                 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
132766                     if (markSeen(containingFunction)) {
132767                         var param = ts.cast(parent, ts.isParameter);
132768                         annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken);
132769                         declaration = param;
132770                     }
132771                     break;
132772                 // Get Accessor declarations
132773                 case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code:
132774                 case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code:
132775                     if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) {
132776                         annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host);
132777                         declaration = containingFunction;
132778                     }
132779                     break;
132780                 // Set Accessor declarations
132781                 case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
132782                     if (ts.isSetAccessorDeclaration(containingFunction)) {
132783                         annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken);
132784                         declaration = containingFunction;
132785                     }
132786                     break;
132787                 // Function 'this'
132788                 case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code:
132789                     if (ts.textChanges.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) {
132790                         annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken);
132791                         declaration = containingFunction;
132792                     }
132793                     break;
132794                 default:
132795                     return ts.Debug.fail(String(errorCode));
132796             }
132797             importAdder.writeFixes(changes);
132798             return declaration;
132799         }
132800         function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) {
132801             if (ts.isIdentifier(declaration.name)) {
132802                 annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host);
132803             }
132804         }
132805         function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) {
132806             if (!ts.isIdentifier(parameterDeclaration.name)) {
132807                 return;
132808             }
132809             var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken);
132810             ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match");
132811             if (ts.isInJSFile(containingFunction)) {
132812                 annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host);
132813             }
132814             else {
132815                 var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile);
132816                 if (needParens)
132817                     changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */));
132818                 for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) {
132819                     var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type;
132820                     if (declaration && !declaration.type && !declaration.initializer) {
132821                         annotate(changes, importAdder, sourceFile, declaration, type, program, host);
132822                     }
132823                 }
132824                 if (needParens)
132825                     changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */));
132826             }
132827         }
132828         function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) {
132829             var references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken);
132830             if (!references || !references.length) {
132831                 return;
132832             }
132833             var thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter();
132834             var typeNode = ts.getTypeNodeIfAccessible(thisInference, containingFunction, program, host);
132835             if (!typeNode) {
132836                 return;
132837             }
132838             if (ts.isInJSFile(containingFunction)) {
132839                 annotateJSDocThis(changes, sourceFile, containingFunction, typeNode);
132840             }
132841             else {
132842                 changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode);
132843             }
132844         }
132845         function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) {
132846             addJSDocTags(changes, sourceFile, containingFunction, [
132847                 ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)),
132848             ]);
132849         }
132850         function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) {
132851             var param = ts.firstOrUndefined(setAccessorDeclaration.parameters);
132852             if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) {
132853                 var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken);
132854                 if (type === program.getTypeChecker().getAnyType()) {
132855                     type = inferTypeForVariableFromUsage(param.name, program, cancellationToken);
132856                 }
132857                 if (ts.isInJSFile(setAccessorDeclaration)) {
132858                     annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host);
132859                 }
132860                 else {
132861                     annotate(changes, importAdder, sourceFile, param, type, program, host);
132862                 }
132863             }
132864         }
132865         function annotate(changes, importAdder, sourceFile, declaration, type, program, host) {
132866             var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
132867             if (typeNode) {
132868                 if (ts.isInJSFile(sourceFile) && declaration.kind !== 158 /* PropertySignature */) {
132869                     var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
132870                     if (!parent) {
132871                         return;
132872                     }
132873                     var typeExpression = ts.createJSDocTypeExpression(typeNode);
132874                     var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, "");
132875                     addJSDocTags(changes, sourceFile, parent, [typeTag]);
132876                 }
132877                 else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, type, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) {
132878                     changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
132879                 }
132880             }
132881         }
132882         function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, type, sourceFile, changes, importAdder, scriptTarget) {
132883             var importableReference = codefix.tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget);
132884             if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeReference)) {
132885                 ts.forEach(importableReference.symbols, function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); });
132886                 return true;
132887             }
132888             return false;
132889         }
132890         function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) {
132891             var signature = parameterInferences.length && parameterInferences[0].declaration.parent;
132892             if (!signature) {
132893                 return;
132894             }
132895             var paramTags = ts.mapDefined(parameterInferences, function (inference) {
132896                 var param = inference.declaration;
132897                 // only infer parameters that have (1) no type and (2) an accessible inferred type
132898                 if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
132899                     return;
132900                 var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
132901                 var name = ts.getSynthesizedClone(param.name);
132902                 ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
132903                 return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
132904             });
132905             addJSDocTags(changes, sourceFile, signature, paramTags);
132906         }
132907         function addJSDocTags(changes, sourceFile, parent, newTags) {
132908             var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; });
132909             var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; });
132910             var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) {
132911                 var merged = tryMergeJsdocTags(tag, newTag);
132912                 if (merged)
132913                     oldTags[i] = merged;
132914                 return !!merged;
132915             }); });
132916             var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray(__spreadArrays((oldTags || ts.emptyArray), unmergedNewTags)));
132917             var jsDocNode = parent.kind === 202 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
132918             jsDocNode.jsDoc = parent.jsDoc;
132919             jsDocNode.jsDocCache = parent.jsDocCache;
132920             changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
132921         }
132922         codefix.addJSDocTags = addJSDocTags;
132923         function getJsDocNodeForArrowFunction(signature) {
132924             if (signature.parent.kind === 159 /* PropertyDeclaration */) {
132925                 return signature.parent;
132926             }
132927             return signature.parent.parent;
132928         }
132929         function tryMergeJsdocTags(oldTag, newTag) {
132930             if (oldTag.kind !== newTag.kind) {
132931                 return undefined;
132932             }
132933             switch (oldTag.kind) {
132934                 case 317 /* JSDocParameterTag */: {
132935                     var oldParam = oldTag;
132936                     var newParam = newTag;
132937                     return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
132938                         ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
132939                         : undefined;
132940                 }
132941                 case 318 /* JSDocReturnTag */:
132942                     return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
132943             }
132944         }
132945         function getReferences(token, program, cancellationToken) {
132946             // Position shouldn't matter since token is not a SourceFile.
132947             return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
132948                 return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined;
132949             });
132950         }
132951         function inferTypeForVariableFromUsage(token, program, cancellationToken) {
132952             var references = getReferences(token, program, cancellationToken);
132953             return inferTypeFromReferences(program, references, cancellationToken).single();
132954         }
132955         function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) {
132956             var references = getFunctionReferences(func, sourceFile, program, cancellationToken);
132957             return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) ||
132958                 func.parameters.map(function (p) { return ({
132959                     declaration: p,
132960                     type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType()
132961                 }); });
132962         }
132963         function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) {
132964             var searchToken;
132965             switch (containingFunction.kind) {
132966                 case 162 /* Constructor */:
132967                     searchToken = ts.findChildOfKind(containingFunction, 129 /* ConstructorKeyword */, sourceFile);
132968                     break;
132969                 case 202 /* ArrowFunction */:
132970                 case 201 /* FunctionExpression */:
132971                     var parent = containingFunction.parent;
132972                     searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ?
132973                         parent.name :
132974                         containingFunction.name;
132975                     break;
132976                 case 244 /* FunctionDeclaration */:
132977                 case 161 /* MethodDeclaration */:
132978                     searchToken = containingFunction.name;
132979                     break;
132980             }
132981             if (!searchToken) {
132982                 return undefined;
132983             }
132984             return getReferences(searchToken, program, cancellationToken);
132985         }
132986         function inferTypeFromReferences(program, references, cancellationToken) {
132987             var checker = program.getTypeChecker();
132988             var builtinConstructors = {
132989                 string: function () { return checker.getStringType(); },
132990                 number: function () { return checker.getNumberType(); },
132991                 Array: function (t) { return checker.createArrayType(t); },
132992                 Promise: function (t) { return checker.createPromiseType(t); },
132993             };
132994             var builtins = [
132995                 checker.getStringType(),
132996                 checker.getNumberType(),
132997                 checker.createArrayType(checker.getAnyType()),
132998                 checker.createPromiseType(checker.getAnyType()),
132999             ];
133000             return {
133001                 single: single,
133002                 parameters: parameters,
133003                 thisParameter: thisParameter,
133004             };
133005             function createEmptyUsage() {
133006                 return {
133007                     isNumber: undefined,
133008                     isString: undefined,
133009                     isNumberOrString: undefined,
133010                     candidateTypes: undefined,
133011                     properties: undefined,
133012                     calls: undefined,
133013                     constructs: undefined,
133014                     numberIndex: undefined,
133015                     stringIndex: undefined,
133016                     candidateThisTypes: undefined,
133017                     inferredTypes: undefined,
133018                 };
133019             }
133020             function combineUsages(usages) {
133021                 var combinedProperties = ts.createUnderscoreEscapedMap();
133022                 for (var _i = 0, usages_1 = usages; _i < usages_1.length; _i++) {
133023                     var u = usages_1[_i];
133024                     if (u.properties) {
133025                         u.properties.forEach(function (p, name) {
133026                             if (!combinedProperties.has(name)) {
133027                                 combinedProperties.set(name, []);
133028                             }
133029                             combinedProperties.get(name).push(p);
133030                         });
133031                     }
133032                 }
133033                 var properties = ts.createUnderscoreEscapedMap();
133034                 combinedProperties.forEach(function (ps, name) {
133035                     properties.set(name, combineUsages(ps));
133036                 });
133037                 return {
133038                     isNumber: usages.some(function (u) { return u.isNumber; }),
133039                     isString: usages.some(function (u) { return u.isString; }),
133040                     isNumberOrString: usages.some(function (u) { return u.isNumberOrString; }),
133041                     candidateTypes: ts.flatMap(usages, function (u) { return u.candidateTypes; }),
133042                     properties: properties,
133043                     calls: ts.flatMap(usages, function (u) { return u.calls; }),
133044                     constructs: ts.flatMap(usages, function (u) { return u.constructs; }),
133045                     numberIndex: ts.forEach(usages, function (u) { return u.numberIndex; }),
133046                     stringIndex: ts.forEach(usages, function (u) { return u.stringIndex; }),
133047                     candidateThisTypes: ts.flatMap(usages, function (u) { return u.candidateThisTypes; }),
133048                     inferredTypes: undefined,
133049                 };
133050             }
133051             function single() {
133052                 return combineTypes(inferTypesFromReferencesSingle(references));
133053             }
133054             function parameters(declaration) {
133055                 if (references.length === 0 || !declaration.parameters) {
133056                     return undefined;
133057                 }
133058                 var usage = createEmptyUsage();
133059                 for (var _i = 0, references_2 = references; _i < references_2.length; _i++) {
133060                     var reference = references_2[_i];
133061                     cancellationToken.throwIfCancellationRequested();
133062                     calculateUsageOfNode(reference, usage);
133063                 }
133064                 var calls = __spreadArrays(usage.constructs || [], usage.calls || []);
133065                 return declaration.parameters.map(function (parameter, parameterIndex) {
133066                     var types = [];
133067                     var isRest = ts.isRestParameter(parameter);
133068                     var isOptional = false;
133069                     for (var _i = 0, calls_1 = calls; _i < calls_1.length; _i++) {
133070                         var call = calls_1[_i];
133071                         if (call.argumentTypes.length <= parameterIndex) {
133072                             isOptional = ts.isInJSFile(declaration);
133073                             types.push(checker.getUndefinedType());
133074                         }
133075                         else if (isRest) {
133076                             for (var i = parameterIndex; i < call.argumentTypes.length; i++) {
133077                                 types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i]));
133078                             }
133079                         }
133080                         else {
133081                             types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex]));
133082                         }
133083                     }
133084                     if (ts.isIdentifier(parameter.name)) {
133085                         var inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken));
133086                         types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
133087                     }
133088                     var type = combineTypes(types);
133089                     return {
133090                         type: isRest ? checker.createArrayType(type) : type,
133091                         isOptional: isOptional && !isRest,
133092                         declaration: parameter
133093                     };
133094                 });
133095             }
133096             function thisParameter() {
133097                 var usage = createEmptyUsage();
133098                 for (var _i = 0, references_3 = references; _i < references_3.length; _i++) {
133099                     var reference = references_3[_i];
133100                     cancellationToken.throwIfCancellationRequested();
133101                     calculateUsageOfNode(reference, usage);
133102                 }
133103                 return combineTypes(usage.candidateThisTypes || ts.emptyArray);
133104             }
133105             function inferTypesFromReferencesSingle(references) {
133106                 var usage = createEmptyUsage();
133107                 for (var _i = 0, references_4 = references; _i < references_4.length; _i++) {
133108                     var reference = references_4[_i];
133109                     cancellationToken.throwIfCancellationRequested();
133110                     calculateUsageOfNode(reference, usage);
133111                 }
133112                 return inferTypes(usage);
133113             }
133114             function calculateUsageOfNode(node, usage) {
133115                 while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
133116                     node = node.parent;
133117                 }
133118                 switch (node.parent.kind) {
133119                     case 226 /* ExpressionStatement */:
133120                         inferTypeFromExpressionStatement(node, usage);
133121                         break;
133122                     case 208 /* PostfixUnaryExpression */:
133123                         usage.isNumber = true;
133124                         break;
133125                     case 207 /* PrefixUnaryExpression */:
133126                         inferTypeFromPrefixUnaryExpression(node.parent, usage);
133127                         break;
133128                     case 209 /* BinaryExpression */:
133129                         inferTypeFromBinaryExpression(node, node.parent, usage);
133130                         break;
133131                     case 277 /* CaseClause */:
133132                     case 278 /* DefaultClause */:
133133                         inferTypeFromSwitchStatementLabel(node.parent, usage);
133134                         break;
133135                     case 196 /* CallExpression */:
133136                     case 197 /* NewExpression */:
133137                         if (node.parent.expression === node) {
133138                             inferTypeFromCallExpression(node.parent, usage);
133139                         }
133140                         else {
133141                             inferTypeFromContextualType(node, usage);
133142                         }
133143                         break;
133144                     case 194 /* PropertyAccessExpression */:
133145                         inferTypeFromPropertyAccessExpression(node.parent, usage);
133146                         break;
133147                     case 195 /* ElementAccessExpression */:
133148                         inferTypeFromPropertyElementExpression(node.parent, node, usage);
133149                         break;
133150                     case 281 /* PropertyAssignment */:
133151                     case 282 /* ShorthandPropertyAssignment */:
133152                         inferTypeFromPropertyAssignment(node.parent, usage);
133153                         break;
133154                     case 159 /* PropertyDeclaration */:
133155                         inferTypeFromPropertyDeclaration(node.parent, usage);
133156                         break;
133157                     case 242 /* VariableDeclaration */: {
133158                         var _a = node.parent, name = _a.name, initializer = _a.initializer;
133159                         if (node === name) {
133160                             if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error.
133161                                 addCandidateType(usage, checker.getTypeAtLocation(initializer));
133162                             }
133163                             break;
133164                         }
133165                     }
133166                     // falls through
133167                     default:
133168                         return inferTypeFromContextualType(node, usage);
133169                 }
133170             }
133171             function inferTypeFromContextualType(node, usage) {
133172                 if (ts.isExpressionNode(node)) {
133173                     addCandidateType(usage, checker.getContextualType(node));
133174                 }
133175             }
133176             function inferTypeFromExpressionStatement(node, usage) {
133177                 addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType());
133178             }
133179             function inferTypeFromPrefixUnaryExpression(node, usage) {
133180                 switch (node.operator) {
133181                     case 45 /* PlusPlusToken */:
133182                     case 46 /* MinusMinusToken */:
133183                     case 40 /* MinusToken */:
133184                     case 54 /* TildeToken */:
133185                         usage.isNumber = true;
133186                         break;
133187                     case 39 /* PlusToken */:
133188                         usage.isNumberOrString = true;
133189                         break;
133190                     // case SyntaxKind.ExclamationToken:
133191                     // no inferences here;
133192                 }
133193             }
133194             function inferTypeFromBinaryExpression(node, parent, usage) {
133195                 switch (parent.operatorToken.kind) {
133196                     // ExponentiationOperator
133197                     case 42 /* AsteriskAsteriskToken */:
133198                     // MultiplicativeOperator
133199                     // falls through
133200                     case 41 /* AsteriskToken */:
133201                     case 43 /* SlashToken */:
133202                     case 44 /* PercentToken */:
133203                     // ShiftOperator
133204                     // falls through
133205                     case 47 /* LessThanLessThanToken */:
133206                     case 48 /* GreaterThanGreaterThanToken */:
133207                     case 49 /* GreaterThanGreaterThanGreaterThanToken */:
133208                     // BitwiseOperator
133209                     // falls through
133210                     case 50 /* AmpersandToken */:
133211                     case 51 /* BarToken */:
133212                     case 52 /* CaretToken */:
133213                     // CompoundAssignmentOperator
133214                     // falls through
133215                     case 64 /* MinusEqualsToken */:
133216                     case 66 /* AsteriskAsteriskEqualsToken */:
133217                     case 65 /* AsteriskEqualsToken */:
133218                     case 67 /* SlashEqualsToken */:
133219                     case 68 /* PercentEqualsToken */:
133220                     case 72 /* AmpersandEqualsToken */:
133221                     case 73 /* BarEqualsToken */:
133222                     case 74 /* CaretEqualsToken */:
133223                     case 69 /* LessThanLessThanEqualsToken */:
133224                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
133225                     case 70 /* GreaterThanGreaterThanEqualsToken */:
133226                     // AdditiveOperator
133227                     // falls through
133228                     case 40 /* MinusToken */:
133229                     // RelationalOperator
133230                     // falls through
133231                     case 29 /* LessThanToken */:
133232                     case 32 /* LessThanEqualsToken */:
133233                     case 31 /* GreaterThanToken */:
133234                     case 33 /* GreaterThanEqualsToken */:
133235                         var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
133236                         if (operandType.flags & 1056 /* EnumLike */) {
133237                             addCandidateType(usage, operandType);
133238                         }
133239                         else {
133240                             usage.isNumber = true;
133241                         }
133242                         break;
133243                     case 63 /* PlusEqualsToken */:
133244                     case 39 /* PlusToken */:
133245                         var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left);
133246                         if (otherOperandType.flags & 1056 /* EnumLike */) {
133247                             addCandidateType(usage, otherOperandType);
133248                         }
133249                         else if (otherOperandType.flags & 296 /* NumberLike */) {
133250                             usage.isNumber = true;
133251                         }
133252                         else if (otherOperandType.flags & 132 /* StringLike */) {
133253                             usage.isString = true;
133254                         }
133255                         else if (otherOperandType.flags & 1 /* Any */) {
133256                             // do nothing, maybe we'll learn something elsewhere
133257                         }
133258                         else {
133259                             usage.isNumberOrString = true;
133260                         }
133261                         break;
133262                     //  AssignmentOperators
133263                     case 62 /* EqualsToken */:
133264                     case 34 /* EqualsEqualsToken */:
133265                     case 36 /* EqualsEqualsEqualsToken */:
133266                     case 37 /* ExclamationEqualsEqualsToken */:
133267                     case 35 /* ExclamationEqualsToken */:
133268                         addCandidateType(usage, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left));
133269                         break;
133270                     case 97 /* InKeyword */:
133271                         if (node === parent.left) {
133272                             usage.isString = true;
133273                         }
133274                         break;
133275                     // LogicalOperator Or NullishCoalescing
133276                     case 56 /* BarBarToken */:
133277                     case 60 /* QuestionQuestionToken */:
133278                         if (node === parent.left &&
133279                             (node.parent.parent.kind === 242 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
133280                             // var x = x || {};
133281                             // TODO: use getFalsyflagsOfType
133282                             addCandidateType(usage, checker.getTypeAtLocation(parent.right));
133283                         }
133284                         break;
133285                     case 55 /* AmpersandAmpersandToken */:
133286                     case 27 /* CommaToken */:
133287                     case 98 /* InstanceOfKeyword */:
133288                         // nothing to infer here
133289                         break;
133290                 }
133291             }
133292             function inferTypeFromSwitchStatementLabel(parent, usage) {
133293                 addCandidateType(usage, checker.getTypeAtLocation(parent.parent.parent.expression));
133294             }
133295             function inferTypeFromCallExpression(parent, usage) {
133296                 var call = {
133297                     argumentTypes: [],
133298                     return_: createEmptyUsage()
133299                 };
133300                 if (parent.arguments) {
133301                     for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) {
133302                         var argument = _a[_i];
133303                         call.argumentTypes.push(checker.getTypeAtLocation(argument));
133304                     }
133305                 }
133306                 calculateUsageOfNode(parent, call.return_);
133307                 if (parent.kind === 196 /* CallExpression */) {
133308                     (usage.calls || (usage.calls = [])).push(call);
133309                 }
133310                 else {
133311                     (usage.constructs || (usage.constructs = [])).push(call);
133312                 }
133313             }
133314             function inferTypeFromPropertyAccessExpression(parent, usage) {
133315                 var name = ts.escapeLeadingUnderscores(parent.name.text);
133316                 if (!usage.properties) {
133317                     usage.properties = ts.createUnderscoreEscapedMap();
133318                 }
133319                 var propertyUsage = usage.properties.get(name) || createEmptyUsage();
133320                 calculateUsageOfNode(parent, propertyUsage);
133321                 usage.properties.set(name, propertyUsage);
133322             }
133323             function inferTypeFromPropertyElementExpression(parent, node, usage) {
133324                 if (node === parent.argumentExpression) {
133325                     usage.isNumberOrString = true;
133326                     return;
133327                 }
133328                 else {
133329                     var indexType = checker.getTypeAtLocation(parent.argumentExpression);
133330                     var indexUsage = createEmptyUsage();
133331                     calculateUsageOfNode(parent, indexUsage);
133332                     if (indexType.flags & 296 /* NumberLike */) {
133333                         usage.numberIndex = indexUsage;
133334                     }
133335                     else {
133336                         usage.stringIndex = indexUsage;
133337                     }
133338                 }
133339             }
133340             function inferTypeFromPropertyAssignment(assignment, usage) {
133341                 var nodeWithRealType = ts.isVariableDeclaration(assignment.parent.parent) ?
133342                     assignment.parent.parent :
133343                     assignment.parent;
133344                 addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType));
133345             }
133346             function inferTypeFromPropertyDeclaration(declaration, usage) {
133347                 addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent));
133348             }
133349             function removeLowPriorityInferences(inferences, priorities) {
133350                 var toRemove = [];
133351                 for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
133352                     var i = inferences_1[_i];
133353                     for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
133354                         var _b = priorities_1[_a], high = _b.high, low = _b.low;
133355                         if (high(i)) {
133356                             ts.Debug.assert(!low(i), "Priority can't have both low and high");
133357                             toRemove.push(low);
133358                         }
133359                     }
133360                 }
133361                 return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); });
133362             }
133363             function combineFromUsage(usage) {
133364                 return combineTypes(inferTypes(usage));
133365             }
133366             function combineTypes(inferences) {
133367                 if (!inferences.length)
133368                     return checker.getAnyType();
133369                 // 1. string or number individually override string | number
133370                 // 2. non-any, non-void overrides any or void
133371                 // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types
133372                 var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]);
133373                 var priorities = [
133374                     {
133375                         high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); },
133376                         low: function (t) { return t === stringNumber; }
133377                     },
133378                     {
133379                         high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); },
133380                         low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); }
133381                     },
133382                     {
133383                         high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(ts.getObjectFlags(t) & 16 /* Anonymous */); },
133384                         low: function (t) { return !!(ts.getObjectFlags(t) & 16 /* Anonymous */); }
133385                     }
133386                 ];
133387                 var good = removeLowPriorityInferences(inferences, priorities);
133388                 var anons = good.filter(function (i) { return ts.getObjectFlags(i) & 16 /* Anonymous */; });
133389                 if (anons.length) {
133390                     good = good.filter(function (i) { return !(ts.getObjectFlags(i) & 16 /* Anonymous */); });
133391                     good.push(combineAnonymousTypes(anons));
133392                 }
133393                 return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */));
133394             }
133395             function combineAnonymousTypes(anons) {
133396                 if (anons.length === 1) {
133397                     return anons[0];
133398                 }
133399                 var calls = [];
133400                 var constructs = [];
133401                 var stringIndices = [];
133402                 var numberIndices = [];
133403                 var stringIndexReadonly = false;
133404                 var numberIndexReadonly = false;
133405                 var props = ts.createMultiMap();
133406                 for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) {
133407                     var anon = anons_1[_i];
133408                     for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) {
133409                         var p = _b[_a];
133410                         props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration));
133411                     }
133412                     calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */));
133413                     constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */));
133414                     if (anon.stringIndexInfo) {
133415                         stringIndices.push(anon.stringIndexInfo.type);
133416                         stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly;
133417                     }
133418                     if (anon.numberIndexInfo) {
133419                         numberIndices.push(anon.numberIndexInfo.type);
133420                         numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly;
133421                     }
133422                 }
133423                 var members = ts.mapEntries(props, function (name, types) {
133424                     var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0;
133425                     var s = checker.createSymbol(4 /* Property */ | isOptional, name);
133426                     s.type = checker.getUnionType(types);
133427                     return [name, s];
133428                 });
133429                 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);
133430             }
133431             function inferTypes(usage) {
133432                 var _a, _b, _c;
133433                 var types = [];
133434                 if (usage.isNumber) {
133435                     types.push(checker.getNumberType());
133436                 }
133437                 if (usage.isString) {
133438                     types.push(checker.getStringType());
133439                 }
133440                 if (usage.isNumberOrString) {
133441                     types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
133442                 }
133443                 if (usage.numberIndex) {
133444                     types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
133445                 }
133446                 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) {
133447                     types.push(inferStructuralType(usage));
133448                 }
133449                 types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
133450                 types.push.apply(types, inferNamedTypesFromProperties(usage));
133451                 return types;
133452             }
133453             function inferStructuralType(usage) {
133454                 var members = ts.createUnderscoreEscapedMap();
133455                 if (usage.properties) {
133456                     usage.properties.forEach(function (u, name) {
133457                         var symbol = checker.createSymbol(4 /* Property */, name);
133458                         symbol.type = combineFromUsage(u);
133459                         members.set(name, symbol);
133460                     });
133461                 }
133462                 var callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : [];
133463                 var constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : [];
133464                 var stringIndexInfo = usage.stringIndex && checker.createIndexInfo(combineFromUsage(usage.stringIndex), /*isReadonly*/ false);
133465                 return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined);
133466             }
133467             function inferNamedTypesFromProperties(usage) {
133468                 if (!usage.properties || !usage.properties.size)
133469                     return [];
133470                 var types = builtins.filter(function (t) { return allPropertiesAreAssignableToUsage(t, usage); });
133471                 if (0 < types.length && types.length < 3) {
133472                     return types.map(function (t) { return inferInstantiationFromUsage(t, usage); });
133473                 }
133474                 return [];
133475             }
133476             function allPropertiesAreAssignableToUsage(type, usage) {
133477                 if (!usage.properties)
133478                     return false;
133479                 return !ts.forEachEntry(usage.properties, function (propUsage, name) {
133480                     var source = checker.getTypeOfPropertyOfType(type, name);
133481                     if (!source) {
133482                         return true;
133483                     }
133484                     if (propUsage.calls) {
133485                         var sigs = checker.getSignaturesOfType(source, 0 /* Call */);
133486                         return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls));
133487                     }
133488                     else {
133489                         return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage));
133490                     }
133491                 });
133492             }
133493             /**
133494              * inference is limited to
133495              * 1. generic types with a single parameter
133496              * 2. inference to/from calls with a single signature
133497              */
133498             function inferInstantiationFromUsage(type, usage) {
133499                 if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !usage.properties) {
133500                     return type;
133501                 }
133502                 var generic = type.target;
133503                 var singleTypeParameter = ts.singleOrUndefined(generic.typeParameters);
133504                 if (!singleTypeParameter)
133505                     return type;
133506                 var types = [];
133507                 usage.properties.forEach(function (propUsage, name) {
133508                     var genericPropertyType = checker.getTypeOfPropertyOfType(generic, name);
133509                     ts.Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
133510                     types.push.apply(types, inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter));
133511                 });
133512                 return builtinConstructors[type.symbol.escapedName](combineTypes(types));
133513             }
133514             function inferTypeParameters(genericType, usageType, typeParameter) {
133515                 if (genericType === typeParameter) {
133516                     return [usageType];
133517                 }
133518                 else if (genericType.flags & 3145728 /* UnionOrIntersection */) {
133519                     return ts.flatMap(genericType.types, function (t) { return inferTypeParameters(t, usageType, typeParameter); });
133520                 }
133521                 else if (ts.getObjectFlags(genericType) & 4 /* Reference */ && ts.getObjectFlags(usageType) & 4 /* Reference */) {
133522                     // this is wrong because we need a reference to the targetType to, so we can check that it's also a reference
133523                     var genericArgs = checker.getTypeArguments(genericType);
133524                     var usageArgs = checker.getTypeArguments(usageType);
133525                     var types = [];
133526                     if (genericArgs && usageArgs) {
133527                         for (var i = 0; i < genericArgs.length; i++) {
133528                             if (usageArgs[i]) {
133529                                 types.push.apply(types, inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter));
133530                             }
133531                         }
133532                     }
133533                     return types;
133534                 }
133535                 var genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */);
133536                 var usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */);
133537                 if (genericSigs.length === 1 && usageSigs.length === 1) {
133538                     return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter);
133539                 }
133540                 return [];
133541             }
133542             function inferFromSignatures(genericSig, usageSig, typeParameter) {
133543                 var types = [];
133544                 for (var i = 0; i < genericSig.parameters.length; i++) {
133545                     var genericParam = genericSig.parameters[i];
133546                     var usageParam = usageSig.parameters[i];
133547                     var isRest = genericSig.declaration && ts.isRestParameter(genericSig.declaration.parameters[i]);
133548                     if (!usageParam) {
133549                         break;
133550                     }
133551                     var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration);
133552                     var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType);
133553                     if (elementType) {
133554                         genericParamType = elementType;
133555                     }
133556                     var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration);
133557                     types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter));
133558                 }
133559                 var genericReturn = checker.getReturnTypeOfSignature(genericSig);
133560                 var usageReturn = checker.getReturnTypeOfSignature(usageSig);
133561                 types.push.apply(types, inferTypeParameters(genericReturn, usageReturn, typeParameter));
133562                 return types;
133563             }
133564             function getFunctionFromCalls(calls) {
133565                 return checker.createAnonymousType(/*symbol*/ undefined, ts.createSymbolTable(), [getSignatureFromCalls(calls)], ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
133566             }
133567             function getSignatureFromCalls(calls) {
133568                 var parameters = [];
133569                 var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; }));
133570                 var _loop_14 = function (i) {
133571                     var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i));
133572                     symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); }));
133573                     if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) {
133574                         symbol.flags |= 16777216 /* Optional */;
133575                     }
133576                     parameters.push(symbol);
133577                 };
133578                 for (var i = 0; i < length; i++) {
133579                     _loop_14(i);
133580                 }
133581                 var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; })));
133582                 // TODO: GH#18217
133583                 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */);
133584             }
133585             function addCandidateType(usage, type) {
133586                 if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
133587                     (usage.candidateTypes || (usage.candidateTypes = [])).push(type);
133588                 }
133589             }
133590             function addCandidateThisType(usage, type) {
133591                 if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) {
133592                     (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type);
133593                 }
133594             }
133595         }
133596     })(codefix = ts.codefix || (ts.codefix = {}));
133597 })(ts || (ts = {}));
133598 /* @internal */
133599 var ts;
133600 (function (ts) {
133601     var codefix;
133602     (function (codefix) {
133603         var fixName = "disableJsDiagnostics";
133604         var fixId = "disableJsDiagnostics";
133605         var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) {
133606             var diag = ts.Diagnostics[key];
133607             return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined;
133608         });
133609         codefix.registerCodeFix({
133610             errorCodes: errorCodes,
133611             getCodeActions: function (context) {
133612                 var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext;
133613                 if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
133614                     return undefined;
133615                 }
133616                 var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options);
133617                 var fixes = [
133618                     // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
133619                     codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [
133620                             ts.createTextChange(sourceFile.checkJsDirective
133621                                 ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end)
133622                                 : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter),
133623                         ])], ts.Diagnostics.Disable_checking_for_this_file),
133624                 ];
133625                 if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) {
133626                     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));
133627                 }
133628                 return fixes;
133629             },
133630             fixIds: [fixId],
133631             getAllCodeActions: function (context) {
133632                 var seenLines = ts.createMap();
133633                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
133634                     if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) {
133635                         makeChange(changes, diag.file, diag.start, seenLines);
133636                     }
133637                 });
133638             },
133639         });
133640         function makeChange(changes, sourceFile, position, seenLines) {
133641             var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line;
133642             // Only need to add `// @ts-ignore` for a line once.
133643             if (!seenLines || ts.addToSeen(seenLines, lineNumber)) {
133644                 changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
133645             }
133646         }
133647     })(codefix = ts.codefix || (ts.codefix = {}));
133648 })(ts || (ts = {}));
133649 /* @internal */
133650 var ts;
133651 (function (ts) {
133652     var codefix;
133653     (function (codefix) {
133654         /**
133655          * Finds members of the resolved type that are missing in the class pointed to by class decl
133656          * and generates source code for the missing members.
133657          * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
133658          * @param importAdder If provided, type annotations will use identifier type references instead of ImportTypeNodes, and the missing imports will be added to the importAdder.
133659          * @returns Empty string iff there are no member insertions.
133660          */
133661         function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, importAdder, addClassElement) {
133662             var classMembers = classDeclaration.symbol.members;
133663             for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) {
133664                 var symbol = possiblyMissingSymbols_1[_i];
133665                 if (!classMembers.has(symbol.escapedName)) {
133666                     addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, importAdder, addClassElement);
133667                 }
133668             }
133669         }
133670         codefix.createMissingMemberNodes = createMissingMemberNodes;
133671         function getNoopSymbolTrackerWithResolver(context) {
133672             return {
133673                 trackSymbol: ts.noop,
133674                 moduleResolverHost: ts.getModuleSpecifierResolverHost(context.program, context.host),
133675             };
133676         }
133677         codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver;
133678         /**
133679          * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
133680          */
133681         function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, importAdder, addClassElement) {
133682             var declarations = symbol.getDeclarations();
133683             if (!(declarations && declarations.length)) {
133684                 return undefined;
133685             }
133686             var checker = context.program.getTypeChecker();
133687             var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
133688             var declaration = declarations[0];
133689             var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false);
133690             var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration));
133691             var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined;
133692             var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
133693             var optional = !!(symbol.flags & 16777216 /* Optional */);
133694             var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */);
133695             switch (declaration.kind) {
133696                 case 158 /* PropertySignature */:
133697                 case 159 /* PropertyDeclaration */:
133698                     var flags = preferences.quotePreference === "single" ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined;
133699                     var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context));
133700                     if (importAdder) {
133701                         var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget);
133702                         if (importableReference) {
133703                             typeNode = importableReference.typeReference;
133704                             importSymbols(importAdder, importableReference.symbols);
133705                         }
133706                     }
133707                     addClassElement(ts.createProperty(
133708                     /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeNode, 
133709                     /*initializer*/ undefined));
133710                     break;
133711                 case 163 /* GetAccessor */:
133712                 case 164 /* SetAccessor */: {
133713                     var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context));
133714                     var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration);
133715                     var orderedAccessors = allAccessors.secondAccessor
133716                         ? [allAccessors.firstAccessor, allAccessors.secondAccessor]
133717                         : [allAccessors.firstAccessor];
133718                     if (importAdder) {
133719                         var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode_1, type, scriptTarget);
133720                         if (importableReference) {
133721                             typeNode_1 = importableReference.typeReference;
133722                             importSymbols(importAdder, importableReference.symbols);
133723                         }
133724                     }
133725                     for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) {
133726                         var accessor = orderedAccessors_1[_i];
133727                         if (ts.isGetAccessorDeclaration(accessor)) {
133728                             addClassElement(ts.createGetAccessor(
133729                             /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(preferences)));
133730                         }
133731                         else {
133732                             ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter");
133733                             var parameter = ts.getSetAccessorValueParameter(accessor);
133734                             var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined;
133735                             addClassElement(ts.createSetAccessor(
133736                             /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(preferences)));
133737                         }
133738                     }
133739                     break;
133740                 }
133741                 case 160 /* MethodSignature */:
133742                 case 161 /* MethodDeclaration */:
133743                     // The signature for the implementation appears as an entry in `signatures` iff
133744                     // there is only one signature.
133745                     // If there are overloads and an implementation signature, it appears as an
133746                     // extra declaration that isn't a signature for `type`.
133747                     // If there is more than one overload but no implementation signature
133748                     // (eg: an abstract method or interface declaration), there is a 1-1
133749                     // correspondence of declarations and signatures.
133750                     var signatures = checker.getSignaturesOfType(type, 0 /* Call */);
133751                     if (!ts.some(signatures)) {
133752                         break;
133753                     }
133754                     if (declarations.length === 1) {
133755                         ts.Debug.assert(signatures.length === 1, "One declaration implies one signature");
133756                         var signature = signatures[0];
133757                         outputMethod(signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(preferences));
133758                         break;
133759                     }
133760                     for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) {
133761                         var signature = signatures_1[_a];
133762                         // Need to ensure nodes are fresh each time so they can have different positions.
133763                         outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
133764                     }
133765                     if (!ambient) {
133766                         if (declarations.length > signatures.length) {
133767                             var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
133768                             outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
133769                         }
133770                         else {
133771                             ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count");
133772                             addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences));
133773                         }
133774                     }
133775                     break;
133776             }
133777             function outputMethod(signature, modifiers, name, body) {
133778                 var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body, importAdder);
133779                 if (method)
133780                     addClassElement(method);
133781             }
133782         }
133783         function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body, importAdder) {
133784             var program = context.program;
133785             var checker = program.getTypeChecker();
133786             var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions());
133787             var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 161 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context));
133788             if (!signatureDeclaration) {
133789                 return undefined;
133790             }
133791             if (importAdder) {
133792                 if (signatureDeclaration.typeParameters) {
133793                     ts.forEach(signatureDeclaration.typeParameters, function (typeParameterDecl, i) {
133794                         var typeParameter = signature.typeParameters[i];
133795                         if (typeParameterDecl.constraint) {
133796                             var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeParameterDecl.constraint, typeParameter.constraint, scriptTarget);
133797                             if (importableReference) {
133798                                 typeParameterDecl.constraint = importableReference.typeReference;
133799                                 importSymbols(importAdder, importableReference.symbols);
133800                             }
133801                         }
133802                         if (typeParameterDecl.default) {
133803                             var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeParameterDecl.default, typeParameter.default, scriptTarget);
133804                             if (importableReference) {
133805                                 typeParameterDecl.default = importableReference.typeReference;
133806                                 importSymbols(importAdder, importableReference.symbols);
133807                             }
133808                         }
133809                     });
133810                 }
133811                 ts.forEach(signatureDeclaration.parameters, function (parameterDecl, i) {
133812                     var parameter = signature.parameters[i];
133813                     var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(parameterDecl.type, checker.getTypeAtLocation(parameter.valueDeclaration), scriptTarget);
133814                     if (importableReference) {
133815                         parameterDecl.type = importableReference.typeReference;
133816                         importSymbols(importAdder, importableReference.symbols);
133817                     }
133818                 });
133819                 if (signatureDeclaration.type) {
133820                     var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(signatureDeclaration.type, signature.resolvedReturnType, scriptTarget);
133821                     if (importableReference) {
133822                         signatureDeclaration.type = importableReference.typeReference;
133823                         importSymbols(importAdder, importableReference.symbols);
133824                     }
133825                 }
133826             }
133827             signatureDeclaration.decorators = undefined;
133828             signatureDeclaration.modifiers = modifiers;
133829             signatureDeclaration.name = name;
133830             signatureDeclaration.questionToken = optional ? ts.createToken(57 /* QuestionToken */) : undefined;
133831             signatureDeclaration.body = body;
133832             return signatureDeclaration;
133833         }
133834         function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) {
133835             var body = !ts.isInterfaceDeclaration(contextNode);
133836             var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent;
133837             var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
133838             var checker = context.program.getTypeChecker();
133839             var tracker = getNoopSymbolTrackerWithResolver(context);
133840             var types = ts.map(args, function (arg) {
133841                 return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker);
133842             });
133843             var names = ts.map(args, function (arg) {
133844                 return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined;
133845             });
133846             var contextualType = checker.getContextualType(call);
133847             var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
133848             return ts.createMethod(
133849             /*decorators*/ undefined, 
133850             /*modifiers*/ makeStatic ? [ts.createToken(120 /* StaticKeyword */)] : undefined, 
133851             /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(41 /* AsteriskToken */) : undefined, methodName, 
133852             /*questionToken*/ undefined, 
133853             /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) {
133854                 return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
133855             }), 
133856             /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), 
133857             /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined);
133858         }
133859         codefix.createMethodFromCallExpression = createMethodFromCallExpression;
133860         function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) {
133861             var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker);
133862             if (typeNode && ts.isImportTypeNode(typeNode)) {
133863                 var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget);
133864                 if (importableReference) {
133865                     importSymbols(importAdder, importableReference.symbols);
133866                     return importableReference.typeReference;
133867                 }
133868             }
133869             return typeNode;
133870         }
133871         codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode;
133872         function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
133873             var parameters = [];
133874             for (var i = 0; i < argCount; i++) {
133875                 var newParameter = ts.createParameter(
133876                 /*decorators*/ undefined, 
133877                 /*modifiers*/ undefined, 
133878                 /*dotDotDotToken*/ undefined, 
133879                 /*name*/ names && names[i] || "arg" + i, 
133880                 /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(57 /* QuestionToken */) : undefined, 
133881                 /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(125 /* AnyKeyword */), 
133882                 /*initializer*/ undefined);
133883                 parameters.push(newParameter);
133884             }
133885             return parameters;
133886         }
133887         function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) {
133888             /** This is *a* signature with the maximal number of arguments,
133889              * such that if there is a "maximal" signature without rest arguments,
133890              * this is one of them.
133891              */
133892             var maxArgsSignature = signatures[0];
133893             var minArgumentCount = signatures[0].minArgumentCount;
133894             var someSigHasRestParameter = false;
133895             for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
133896                 var sig = signatures_2[_i];
133897                 minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
133898                 if (ts.signatureHasRestParameter(sig)) {
133899                     someSigHasRestParameter = true;
133900                 }
133901                 if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) {
133902                     maxArgsSignature = sig;
133903                 }
133904             }
133905             var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0);
133906             var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; });
133907             var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false);
133908             if (someSigHasRestParameter) {
133909                 var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(125 /* AnyKeyword */));
133910                 var restParameter = ts.createParameter(
133911                 /*decorators*/ undefined, 
133912                 /*modifiers*/ undefined, ts.createToken(25 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", 
133913                 /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(57 /* QuestionToken */) : undefined, anyArrayType, 
133914                 /*initializer*/ undefined);
133915                 parameters.push(restParameter);
133916             }
133917             return createStubbedMethod(modifiers, name, optional, 
133918             /*typeParameters*/ undefined, parameters, 
133919             /*returnType*/ undefined, preferences);
133920         }
133921         function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) {
133922             return ts.createMethod(
133923             /*decorators*/ undefined, modifiers, 
133924             /*asteriskToken*/ undefined, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences));
133925         }
133926         function createStubbedMethodBody(preferences) {
133927             return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), 
133928                 /*typeArguments*/ undefined, 
133929                 // TODO Handle auto quote preference.
133930                 [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], 
133931             /*multiline*/ true);
133932         }
133933         function createVisibilityModifier(flags) {
133934             if (flags & 4 /* Public */) {
133935                 return ts.createToken(119 /* PublicKeyword */);
133936             }
133937             else if (flags & 16 /* Protected */) {
133938                 return ts.createToken(118 /* ProtectedKeyword */);
133939             }
133940             return undefined;
133941         }
133942         function setJsonCompilerOptionValues(changeTracker, configFile, options) {
133943             var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile);
133944             if (!tsconfigObjectLiteral)
133945                 return undefined;
133946             var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
133947             if (compilerOptionsProperty === undefined) {
133948                 changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) {
133949                     var optionName = _a[0], optionValue = _a[1];
133950                     return createJsonPropertyAssignment(optionName, optionValue);
133951                 }), /*multiLine*/ true)));
133952                 return;
133953             }
133954             var compilerOptions = compilerOptionsProperty.initializer;
133955             if (!ts.isObjectLiteralExpression(compilerOptions)) {
133956                 return;
133957             }
133958             for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
133959                 var _a = options_1[_i], optionName = _a[0], optionValue = _a[1];
133960                 var optionProperty = findJsonProperty(compilerOptions, optionName);
133961                 if (optionProperty === undefined) {
133962                     changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue));
133963                 }
133964                 else {
133965                     changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue);
133966                 }
133967             }
133968         }
133969         codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues;
133970         function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) {
133971             setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]);
133972         }
133973         codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue;
133974         function createJsonPropertyAssignment(name, initializer) {
133975             return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer);
133976         }
133977         codefix.createJsonPropertyAssignment = createJsonPropertyAssignment;
133978         function findJsonProperty(obj, name) {
133979             return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; });
133980         }
133981         codefix.findJsonProperty = findJsonProperty;
133982         /**
133983          * Given an ImportTypeNode 'import("./a").SomeType<import("./b").OtherType<...>>',
133984          * returns an equivalent type reference node with any nested ImportTypeNodes also replaced
133985          * with type references, and a list of symbols that must be imported to use the type reference.
133986          */
133987         function tryGetAutoImportableReferenceFromImportTypeNode(importTypeNode, type, scriptTarget) {
133988             if (importTypeNode && ts.isLiteralImportTypeNode(importTypeNode) && importTypeNode.qualifier && (!type || type.symbol)) {
133989                 // Symbol for the left-most thing after the dot
133990                 var firstIdentifier = ts.getFirstIdentifier(importTypeNode.qualifier);
133991                 var name = ts.getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget);
133992                 var qualifier = name !== firstIdentifier.text
133993                     ? replaceFirstIdentifierOfEntityName(importTypeNode.qualifier, ts.createIdentifier(name))
133994                     : importTypeNode.qualifier;
133995                 var symbols_4 = [firstIdentifier.symbol];
133996                 var typeArguments_1 = [];
133997                 if (importTypeNode.typeArguments) {
133998                     importTypeNode.typeArguments.forEach(function (arg) {
133999                         var ref = tryGetAutoImportableReferenceFromImportTypeNode(arg, /*undefined*/ type, scriptTarget);
134000                         if (ref) {
134001                             symbols_4.push.apply(symbols_4, ref.symbols);
134002                             typeArguments_1.push(ref.typeReference);
134003                         }
134004                         else {
134005                             typeArguments_1.push(arg);
134006                         }
134007                     });
134008                 }
134009                 return {
134010                     symbols: symbols_4,
134011                     typeReference: ts.createTypeReferenceNode(qualifier, typeArguments_1)
134012                 };
134013             }
134014         }
134015         codefix.tryGetAutoImportableReferenceFromImportTypeNode = tryGetAutoImportableReferenceFromImportTypeNode;
134016         function replaceFirstIdentifierOfEntityName(name, newIdentifier) {
134017             if (name.kind === 75 /* Identifier */) {
134018                 return newIdentifier;
134019             }
134020             return ts.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right);
134021         }
134022         function importSymbols(importAdder, symbols) {
134023             symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); });
134024         }
134025         codefix.importSymbols = importSymbols;
134026     })(codefix = ts.codefix || (ts.codefix = {}));
134027 })(ts || (ts = {}));
134028 /* @internal */
134029 var ts;
134030 (function (ts) {
134031     var codefix;
134032     (function (codefix) {
134033         var fixName = "invalidImportSyntax";
134034         function getCodeFixesForImportDeclaration(context, node) {
134035             var sourceFile = ts.getSourceFileOfNode(node);
134036             var namespace = ts.getNamespaceDeclarationNode(node);
134037             var opts = context.program.getCompilerOptions();
134038             var variations = [];
134039             // import Bluebird from "bluebird";
134040             variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences))));
134041             if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
134042                 // import Bluebird = require("bluebird");
134043                 variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
134044                 /*decorators*/ undefined, 
134045                 /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier))));
134046             }
134047             return variations;
134048         }
134049         function createAction(context, sourceFile, node, replacement) {
134050             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); });
134051             return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]);
134052         }
134053         codefix.registerCodeFix({
134054             errorCodes: [
134055                 ts.Diagnostics.This_expression_is_not_callable.code,
134056                 ts.Diagnostics.This_expression_is_not_constructable.code,
134057             ],
134058             getCodeActions: getActionsForUsageOfInvalidImport
134059         });
134060         function getActionsForUsageOfInvalidImport(context) {
134061             var sourceFile = context.sourceFile;
134062             var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 196 /* CallExpression */ : 197 /* NewExpression */;
134063             var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; });
134064             if (!node) {
134065                 return [];
134066             }
134067             var expr = node.expression;
134068             return getImportCodeFixesForExpression(context, expr);
134069         }
134070         codefix.registerCodeFix({
134071             errorCodes: [
134072                 // The following error codes cover pretty much all assignability errors that could involve an expression
134073                 ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code,
134074                 ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code,
134075                 ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code,
134076                 ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code,
134077                 ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code,
134078                 ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code,
134079                 ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code,
134080                 ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code,
134081                 ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code,
134082                 ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code,
134083                 ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code,
134084                 ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code,
134085             ],
134086             getCodeActions: getActionsForInvalidImportLocation
134087         });
134088         function getActionsForInvalidImportLocation(context) {
134089             var sourceFile = context.sourceFile;
134090             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); });
134091             if (!node) {
134092                 return [];
134093             }
134094             return getImportCodeFixesForExpression(context, node);
134095         }
134096         function getImportCodeFixesForExpression(context, expr) {
134097             var type = context.program.getTypeChecker().getTypeAtLocation(expr);
134098             if (!(type.symbol && type.symbol.originatingImport)) {
134099                 return [];
134100             }
134101             var fixes = [];
134102             var relatedImport = type.symbol.originatingImport; // TODO: GH#18217
134103             if (!ts.isImportCall(relatedImport)) {
134104                 ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
134105             }
134106             if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
134107                 var sourceFile_1 = context.sourceFile;
134108                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
134109                 fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
134110             }
134111             return fixes;
134112         }
134113     })(codefix = ts.codefix || (ts.codefix = {}));
134114 })(ts || (ts = {}));
134115 /* @internal */
134116 var ts;
134117 (function (ts) {
134118     var codefix;
134119     (function (codefix) {
134120         var fixName = "strictClassInitialization";
134121         var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions";
134122         var fixIdAddUndefinedType = "addMissingPropertyUndefinedType";
134123         var fixIdAddInitializer = "addMissingPropertyInitializer";
134124         var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code];
134125         codefix.registerCodeFix({
134126             errorCodes: errorCodes,
134127             getCodeActions: function (context) {
134128                 var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start);
134129                 if (!propertyDeclaration)
134130                     return;
134131                 var result = [
134132                     getActionForAddMissingUndefinedType(context, propertyDeclaration),
134133                     getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration)
134134                 ];
134135                 ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration));
134136                 return result;
134137             },
134138             fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer],
134139             getAllCodeActions: function (context) {
134140                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
134141                     var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start);
134142                     if (!propertyDeclaration)
134143                         return;
134144                     switch (context.fixId) {
134145                         case fixIdAddDefiniteAssignmentAssertions:
134146                             addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration);
134147                             break;
134148                         case fixIdAddUndefinedType:
134149                             addUndefinedType(changes, diag.file, propertyDeclaration);
134150                             break;
134151                         case fixIdAddInitializer:
134152                             var checker = context.program.getTypeChecker();
134153                             var initializer = getInitializer(checker, propertyDeclaration);
134154                             if (!initializer)
134155                                 return;
134156                             addInitializer(changes, diag.file, propertyDeclaration, initializer);
134157                             break;
134158                         default:
134159                             ts.Debug.fail(JSON.stringify(context.fixId));
134160                     }
134161                 });
134162             },
134163         });
134164         function getPropertyDeclaration(sourceFile, pos) {
134165             var token = ts.getTokenAtPosition(sourceFile, pos);
134166             return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
134167         }
134168         function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) {
134169             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); });
134170             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);
134171         }
134172         function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
134173             var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(53 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer);
134174             changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
134175         }
134176         function getActionForAddMissingUndefinedType(context, propertyDeclaration) {
134177             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); });
134178             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);
134179         }
134180         function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) {
134181             var undefinedTypeNode = ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
134182             var type = propertyDeclaration.type; // TODO: GH#18217
134183             var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode];
134184             changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types));
134185         }
134186         function getActionForAddMissingInitializer(context, propertyDeclaration) {
134187             var checker = context.program.getTypeChecker();
134188             var initializer = getInitializer(checker, propertyDeclaration);
134189             if (!initializer)
134190                 return undefined;
134191             var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); });
134192             return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties);
134193         }
134194         function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) {
134195             var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer);
134196             changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property);
134197         }
134198         function getInitializer(checker, propertyDeclaration) {
134199             return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217
134200         }
134201         function getDefaultValueFromType(checker, type) {
134202             if (type.flags & 512 /* BooleanLiteral */) {
134203                 return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue();
134204             }
134205             else if (type.isLiteral()) {
134206                 return ts.createLiteral(type.value);
134207             }
134208             else if (type.isUnion()) {
134209                 return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); });
134210             }
134211             else if (type.isClass()) {
134212                 var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
134213                 if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */))
134214                     return undefined;
134215                 var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration);
134216                 if (constructorDeclaration && constructorDeclaration.parameters.length)
134217                     return undefined;
134218                 return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
134219             }
134220             else if (checker.isArrayLikeType(type)) {
134221                 return ts.createArrayLiteral();
134222             }
134223             return undefined;
134224         }
134225     })(codefix = ts.codefix || (ts.codefix = {}));
134226 })(ts || (ts = {}));
134227 /* @internal */
134228 var ts;
134229 (function (ts) {
134230     var codefix;
134231     (function (codefix) {
134232         var fixId = "requireInTs";
134233         var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code];
134234         codefix.registerCodeFix({
134235             errorCodes: errorCodes,
134236             getCodeActions: function (context) {
134237                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); });
134238                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)];
134239             },
134240             fixIds: [fixId],
134241             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); },
134242         });
134243         function doChange(changes, sourceFile, pos, program) {
134244             var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required;
134245             changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())
134246                 ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required)
134247                 : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required)));
134248         }
134249         function getInfo(sourceFile, pos) {
134250             var parent = ts.getTokenAtPosition(sourceFile, pos).parent;
134251             if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true))
134252                 throw ts.Debug.failBadSyntaxKind(parent);
134253             var decl = ts.cast(parent.parent, ts.isVariableDeclaration);
134254             return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] };
134255         }
134256     })(codefix = ts.codefix || (ts.codefix = {}));
134257 })(ts || (ts = {}));
134258 /* @internal */
134259 var ts;
134260 (function (ts) {
134261     var codefix;
134262     (function (codefix) {
134263         var fixId = "useDefaultImport";
134264         var errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code];
134265         codefix.registerCodeFix({
134266             errorCodes: errorCodes,
134267             getCodeActions: function (context) {
134268                 var sourceFile = context.sourceFile, start = context.span.start;
134269                 var info = getInfo(sourceFile, start);
134270                 if (!info)
134271                     return undefined;
134272                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); });
134273                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)];
134274             },
134275             fixIds: [fixId],
134276             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
134277                 var info = getInfo(diag.file, diag.start);
134278                 if (info)
134279                     doChange(changes, diag.file, info, context.preferences);
134280             }); },
134281         });
134282         function getInfo(sourceFile, pos) {
134283             var name = ts.getTokenAtPosition(sourceFile, pos);
134284             if (!ts.isIdentifier(name))
134285                 return undefined; // bad input
134286             var parent = name.parent;
134287             if (ts.isImportEqualsDeclaration(parent) && ts.isExternalModuleReference(parent.moduleReference)) {
134288                 return { importNode: parent, name: name, moduleSpecifier: parent.moduleReference.expression };
134289             }
134290             else if (ts.isNamespaceImport(parent)) {
134291                 var importNode = parent.parent.parent;
134292                 return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier };
134293             }
134294         }
134295         function doChange(changes, sourceFile, info, preferences) {
134296             changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences)));
134297         }
134298     })(codefix = ts.codefix || (ts.codefix = {}));
134299 })(ts || (ts = {}));
134300 /* @internal */
134301 var ts;
134302 (function (ts) {
134303     var codefix;
134304     (function (codefix) {
134305         var fixId = "useBigintLiteral";
134306         var errorCodes = [
134307             ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code,
134308         ];
134309         codefix.registerCodeFix({
134310             errorCodes: errorCodes,
134311             getCodeActions: function (context) {
134312                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); });
134313                 if (changes.length > 0) {
134314                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_a_bigint_numeric_literal, fixId, ts.Diagnostics.Convert_all_to_bigint_numeric_literals)];
134315                 }
134316             },
134317             fixIds: [fixId],
134318             getAllCodeActions: function (context) {
134319                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag); });
134320             },
134321         });
134322         function makeChange(changeTracker, sourceFile, span) {
134323             var numericLiteral = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), ts.isNumericLiteral);
134324             if (!numericLiteral) {
134325                 return;
134326             }
134327             // We use .getText to overcome parser inaccuracies: https://github.com/microsoft/TypeScript/issues/33298
134328             var newText = numericLiteral.getText(sourceFile) + "n";
134329             changeTracker.replaceNode(sourceFile, numericLiteral, ts.createBigIntLiteral(newText));
134330         }
134331     })(codefix = ts.codefix || (ts.codefix = {}));
134332 })(ts || (ts = {}));
134333 /* @internal */
134334 var ts;
134335 (function (ts) {
134336     var codefix;
134337     (function (codefix) {
134338         var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
134339         var fixId = fixIdAddMissingTypeof;
134340         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];
134341         codefix.registerCodeFix({
134342             errorCodes: errorCodes,
134343             getCodeActions: function (context) {
134344                 var sourceFile = context.sourceFile, span = context.span;
134345                 var importType = getImportTypeNode(sourceFile, span.start);
134346                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
134347                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
134348             },
134349             fixIds: [fixId],
134350             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
134351                 return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
134352             }); },
134353         });
134354         function getImportTypeNode(sourceFile, pos) {
134355             var token = ts.getTokenAtPosition(sourceFile, pos);
134356             ts.Debug.assert(token.kind === 96 /* ImportKeyword */, "This token should be an ImportKeyword");
134357             ts.Debug.assert(token.parent.kind === 188 /* ImportType */, "Token parent should be an ImportType");
134358             return token.parent;
134359         }
134360         function doChange(changes, sourceFile, importType) {
134361             var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
134362             changes.replaceNode(sourceFile, importType, newTypeNode);
134363         }
134364     })(codefix = ts.codefix || (ts.codefix = {}));
134365 })(ts || (ts = {}));
134366 /* @internal */
134367 var ts;
134368 (function (ts) {
134369     var codefix;
134370     (function (codefix) {
134371         var fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
134372         var fixId = fixIdAddMissingTypeof;
134373         var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
134374         codefix.registerCodeFix({
134375             errorCodes: errorCodes,
134376             getCodeActions: function (context) {
134377                 var sourceFile = context.sourceFile, span = context.span;
134378                 var info = getInfo(sourceFile, span.start);
134379                 if (!info)
134380                     return undefined;
134381                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
134382                 var name = ts.idText(info.container.name);
134383                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])];
134384             },
134385             fixIds: [fixId],
134386             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
134387                 var info = getInfo(diag.file, diag.start);
134388                 if (info)
134389                     doChange(changes, diag.file, info);
134390             }); }
134391         });
134392         function getInfo(sourceFile, pos) {
134393             var token = ts.getTokenAtPosition(sourceFile, pos);
134394             var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration);
134395             if (ts.isClassDeclaration(indexSignature.parent))
134396                 return undefined;
134397             var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration);
134398             return { indexSignature: indexSignature, container: container };
134399         }
134400         function createTypeAliasFromInterface(declaration, type) {
134401             return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
134402         }
134403         function doChange(changes, sourceFile, _a) {
134404             var indexSignature = _a.indexSignature, container = _a.container;
134405             var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members;
134406             var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); });
134407             var parameter = ts.first(indexSignature.parameters);
134408             var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type);
134409             var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(138 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type);
134410             var intersectionType = ts.createIntersectionTypeNode(__spreadArrays(ts.getAllSuperTypeNodes(container), [
134411                 mappedIntersectionType
134412             ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray)));
134413             changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType));
134414         }
134415     })(codefix = ts.codefix || (ts.codefix = {}));
134416 })(ts || (ts = {}));
134417 /* @internal */
134418 var ts;
134419 (function (ts) {
134420     var codefix;
134421     (function (codefix) {
134422         var fixId = "removeUnnecessaryAwait";
134423         var errorCodes = [
134424             ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code,
134425         ];
134426         codefix.registerCodeFix({
134427             errorCodes: errorCodes,
134428             getCodeActions: function (context) {
134429                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); });
134430                 if (changes.length > 0) {
134431                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unnecessary_await, fixId, ts.Diagnostics.Remove_all_unnecessary_uses_of_await)];
134432                 }
134433             },
134434             fixIds: [fixId],
134435             getAllCodeActions: function (context) {
134436                 return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag); });
134437             },
134438         });
134439         function makeChange(changeTracker, sourceFile, span) {
134440             var awaitKeyword = ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start), function (node) { return node.kind === 127 /* AwaitKeyword */; });
134441             var awaitExpression = awaitKeyword && ts.tryCast(awaitKeyword.parent, ts.isAwaitExpression);
134442             if (!awaitExpression) {
134443                 return;
134444             }
134445             var expressionToReplace = awaitExpression;
134446             var hasSurroundingParens = ts.isParenthesizedExpression(awaitExpression.parent);
134447             if (hasSurroundingParens) {
134448                 var leftMostExpression = ts.getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ false);
134449                 if (ts.isIdentifier(leftMostExpression)) {
134450                     var precedingToken = ts.findPrecedingToken(awaitExpression.parent.pos, sourceFile);
134451                     if (precedingToken && precedingToken.kind !== 99 /* NewKeyword */) {
134452                         expressionToReplace = awaitExpression.parent;
134453                     }
134454                 }
134455             }
134456             changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression);
134457         }
134458     })(codefix = ts.codefix || (ts.codefix = {}));
134459 })(ts || (ts = {}));
134460 /* @internal */
134461 var ts;
134462 (function (ts) {
134463     var codefix;
134464     (function (codefix) {
134465         var errorCodes = [ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code];
134466         var fixId = "splitTypeOnlyImport";
134467         codefix.registerCodeFix({
134468             errorCodes: errorCodes,
134469             fixIds: [fixId],
134470             getCodeActions: function (context) {
134471                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
134472                     return splitTypeOnlyImport(t, getImportDeclaration(context.sourceFile, context.span), context);
134473                 });
134474                 if (changes.length) {
134475                     return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Split_into_two_separate_import_declarations, fixId, ts.Diagnostics.Split_all_invalid_type_only_imports)];
134476                 }
134477             },
134478             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, error) {
134479                 splitTypeOnlyImport(changes, getImportDeclaration(context.sourceFile, error), context);
134480             }); },
134481         });
134482         function getImportDeclaration(sourceFile, span) {
134483             return ts.findAncestor(ts.getTokenAtPosition(sourceFile, span.start), ts.isImportDeclaration);
134484         }
134485         function splitTypeOnlyImport(changes, importDeclaration, context) {
134486             if (!importDeclaration) {
134487                 return;
134488             }
134489             var importClause = ts.Debug.checkDefined(importDeclaration.importClause);
134490             changes.replaceNode(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, importClause.name, /*namedBindings*/ undefined, importClause.isTypeOnly), importDeclaration.moduleSpecifier));
134491             changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.createImportDeclaration(
134492             /*decorators*/ undefined, 
134493             /*modifiers*/ undefined, ts.updateImportClause(importClause, /*name*/ undefined, importClause.namedBindings, importClause.isTypeOnly), importDeclaration.moduleSpecifier));
134494         }
134495     })(codefix = ts.codefix || (ts.codefix = {}));
134496 })(ts || (ts = {}));
134497 /* @internal */
134498 var ts;
134499 (function (ts) {
134500     var codefix;
134501     (function (codefix) {
134502         var fixId = "fixConvertConstToLet";
134503         var errorCodes = [ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];
134504         codefix.registerCodeFix({
134505             errorCodes: errorCodes,
134506             getCodeActions: function (context) {
134507                 var sourceFile = context.sourceFile, span = context.span, program = context.program;
134508                 var variableStatement = getVariableStatement(sourceFile, span.start, program);
134509                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, variableStatement); });
134510                 return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_const_to_let, fixId, ts.Diagnostics.Convert_const_to_let)];
134511             },
134512             fixIds: [fixId]
134513         });
134514         function getVariableStatement(sourceFile, pos, program) {
134515             var token = ts.getTokenAtPosition(sourceFile, pos);
134516             var checker = program.getTypeChecker();
134517             var symbol = checker.getSymbolAtLocation(token);
134518             if (symbol) {
134519                 return symbol.valueDeclaration.parent.parent;
134520             }
134521         }
134522         function doChange(changes, sourceFile, variableStatement) {
134523             if (!variableStatement) {
134524                 return;
134525             }
134526             var start = variableStatement.getStart();
134527             changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 5 }, "let");
134528         }
134529     })(codefix = ts.codefix || (ts.codefix = {}));
134530 })(ts || (ts = {}));
134531 /* @internal */
134532 var ts;
134533 (function (ts) {
134534     var codefix;
134535     (function (codefix) {
134536         var fixId = "fixExpectedComma";
134537         var expectedErrorCode = ts.Diagnostics._0_expected.code;
134538         var errorCodes = [expectedErrorCode];
134539         codefix.registerCodeFix({
134540             errorCodes: errorCodes,
134541             getCodeActions: function (context) {
134542                 var sourceFile = context.sourceFile;
134543                 var info = getInfo(sourceFile, context.span.start, context.errorCode);
134544                 if (!info) {
134545                     return undefined;
134546                 }
134547                 var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); });
134548                 return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Change_0_to_1, ";", ","], fixId, [ts.Diagnostics.Change_0_to_1, ";", ","])];
134549             },
134550             fixIds: [fixId],
134551             getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
134552                 var info = getInfo(diag.file, diag.start, diag.code);
134553                 if (info)
134554                     doChange(changes, context.sourceFile, info);
134555             }); },
134556         });
134557         function getInfo(sourceFile, pos, _) {
134558             var node = ts.getTokenAtPosition(sourceFile, pos);
134559             return (node.kind === 26 /* SemicolonToken */ &&
134560                 node.parent &&
134561                 (ts.isObjectLiteralExpression(node.parent) ||
134562                     ts.isArrayLiteralExpression(node.parent))) ? { node: node } : undefined;
134563         }
134564         function doChange(changes, sourceFile, _a) {
134565             var node = _a.node;
134566             var newNode = ts.createNode(27 /* CommaToken */);
134567             changes.replaceNode(sourceFile, node, newNode);
134568         }
134569     })(codefix = ts.codefix || (ts.codefix = {}));
134570 })(ts || (ts = {}));
134571 /* @internal */
134572 var ts;
134573 (function (ts) {
134574     var refactor;
134575     (function (refactor) {
134576         var refactorName = "Convert export";
134577         var actionNameDefaultToNamed = "Convert default export to named export";
134578         var actionNameNamedToDefault = "Convert named export to default export";
134579         refactor.registerRefactor(refactorName, {
134580             getAvailableActions: function (context) {
134581                 var info = getInfo(context);
134582                 if (!info)
134583                     return ts.emptyArray;
134584                 var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message;
134585                 var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault;
134586                 return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
134587             },
134588             getEditsForAction: function (context, actionName) {
134589                 ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault, "Unexpected action name");
134590                 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); });
134591                 return { edits: edits, renameFilename: undefined, renameLocation: undefined };
134592             },
134593         });
134594         function getInfo(context) {
134595             var file = context.file;
134596             var span = ts.getRefactorContextSpan(context);
134597             var token = ts.getTokenAtPosition(file, span.start);
134598             var exportNode = ts.getParentNodeInSpan(token, file, span);
134599             if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) {
134600                 return undefined;
134601             }
134602             var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol;
134603             var flags = ts.getModifierFlags(exportNode);
134604             var wasDefault = !!(flags & 512 /* Default */);
134605             // If source file already has a default export, don't offer refactor.
134606             if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
134607                 return undefined;
134608             }
134609             switch (exportNode.kind) {
134610                 case 244 /* FunctionDeclaration */:
134611                 case 245 /* ClassDeclaration */:
134612                 case 246 /* InterfaceDeclaration */:
134613                 case 248 /* EnumDeclaration */:
134614                 case 247 /* TypeAliasDeclaration */:
134615                 case 249 /* ModuleDeclaration */: {
134616                     var node = exportNode;
134617                     return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
134618                 }
134619                 case 225 /* VariableStatement */: {
134620                     var vs = exportNode;
134621                     // Must be `export const x = something;`.
134622                     if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
134623                         return undefined;
134624                     }
134625                     var decl = ts.first(vs.declarationList.declarations);
134626                     if (!decl.initializer)
134627                         return undefined;
134628                     ts.Debug.assert(!wasDefault, "Can't have a default flag here");
134629                     return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
134630                 }
134631                 default:
134632                     return undefined;
134633             }
134634         }
134635         function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
134636             changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
134637             changeImports(program, info, changes, cancellationToken);
134638         }
134639         function changeExport(exportingSourceFile, _a, changes, checker) {
134640             var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName;
134641             if (wasDefault) {
134642                 changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 84 /* DefaultKeyword */), "Should find a default keyword in modifier list"));
134643             }
134644             else {
134645                 var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 89 /* ExportKeyword */), "Should find an export keyword in modifier list");
134646                 switch (exportNode.kind) {
134647                     case 244 /* FunctionDeclaration */:
134648                     case 245 /* ClassDeclaration */:
134649                     case 246 /* InterfaceDeclaration */:
134650                         changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(84 /* DefaultKeyword */));
134651                         break;
134652                     case 225 /* VariableStatement */:
134653                         // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;`
134654                         if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) {
134655                             // We checked in `getInfo` that an initializer exists.
134656                             changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.checkDefined(ts.first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present")));
134657                             break;
134658                         }
134659                     // falls through
134660                     case 248 /* EnumDeclaration */:
134661                     case 247 /* TypeAliasDeclaration */:
134662                     case 249 /* ModuleDeclaration */:
134663                         // `export type T = number;` -> `type T = number; export default T;`
134664                         changes.deleteModifier(exportingSourceFile, exportKeyword);
134665                         changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text)));
134666                         break;
134667                     default:
134668                         ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind);
134669                 }
134670             }
134671         }
134672         function changeImports(program, _a, changes, cancellationToken) {
134673             var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol;
134674             var checker = program.getTypeChecker();
134675             var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
134676             ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) {
134677                 var importingSourceFile = ref.getSourceFile();
134678                 if (wasDefault) {
134679                     changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
134680                 }
134681                 else {
134682                     changeNamedToDefaultImport(importingSourceFile, ref, changes);
134683                 }
134684             });
134685         }
134686         function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
134687             var parent = ref.parent;
134688             switch (parent.kind) {
134689                 case 194 /* PropertyAccessExpression */:
134690                     // `a.default` --> `a.foo`
134691                     changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName));
134692                     break;
134693                 case 258 /* ImportSpecifier */:
134694                 case 263 /* ExportSpecifier */: {
134695                     var spec = parent;
134696                     // `default as foo` --> `foo`, `default as bar` --> `foo as bar`
134697                     changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
134698                     break;
134699                 }
134700                 case 255 /* ImportClause */: {
134701                     var clause = parent;
134702                     ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref");
134703                     var spec = makeImportSpecifier(exportName, ref.text);
134704                     var namedBindings = clause.namedBindings;
134705                     if (!namedBindings) {
134706                         // `import foo from "./a";` --> `import { foo } from "./a";`
134707                         changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec]));
134708                     }
134709                     else if (namedBindings.kind === 256 /* NamespaceImport */) {
134710                         // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";`
134711                         changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
134712                         var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
134713                         var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference);
134714                         changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
134715                     }
134716                     else {
134717                         // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";`
134718                         changes.delete(importingSourceFile, ref);
134719                         changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
134720                     }
134721                     break;
134722                 }
134723                 default:
134724                     ts.Debug.failBadSyntaxKind(parent);
134725             }
134726         }
134727         function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
134728             var parent = ref.parent;
134729             switch (parent.kind) {
134730                 case 194 /* PropertyAccessExpression */:
134731                     // `a.foo` --> `a.default`
134732                     changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default"));
134733                     break;
134734                 case 258 /* ImportSpecifier */: {
134735                     // `import { foo } from "./a";` --> `import foo from "./a";`
134736                     // `import { foo as bar } from "./a";` --> `import bar from "./a";`
134737                     var defaultImport = ts.createIdentifier(parent.name.text);
134738                     if (parent.parent.elements.length === 1) {
134739                         changes.replaceNode(importingSourceFile, parent.parent, defaultImport);
134740                     }
134741                     else {
134742                         changes.delete(importingSourceFile, parent);
134743                         changes.insertNodeBefore(importingSourceFile, parent.parent, defaultImport);
134744                     }
134745                     break;
134746                 }
134747                 case 263 /* ExportSpecifier */: {
134748                     // `export { foo } from "./a";` --> `export { default as foo } from "./a";`
134749                     // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";`
134750                     // `export { foo as default } from "./a";` --> `export { default } from "./a";`
134751                     // (Because `export foo from "./a";` isn't valid syntax.)
134752                     changes.replaceNode(importingSourceFile, parent, makeExportSpecifier("default", parent.name.text));
134753                     break;
134754                 }
134755                 default:
134756                     ts.Debug.assertNever(parent, "Unexpected parent kind " + parent.kind);
134757             }
134758         }
134759         function makeImportSpecifier(propertyName, name) {
134760             return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
134761         }
134762         function makeExportSpecifier(propertyName, name) {
134763             return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
134764         }
134765     })(refactor = ts.refactor || (ts.refactor = {}));
134766 })(ts || (ts = {}));
134767 /* @internal */
134768 var ts;
134769 (function (ts) {
134770     var refactor;
134771     (function (refactor) {
134772         var refactorName = "Convert import";
134773         var actionNameNamespaceToNamed = "Convert namespace import to named imports";
134774         var actionNameNamedToNamespace = "Convert named imports to namespace import";
134775         refactor.registerRefactor(refactorName, {
134776             getAvailableActions: function (context) {
134777                 var i = getImportToConvert(context);
134778                 if (!i)
134779                     return ts.emptyArray;
134780                 var description = i.kind === 256 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
134781                 var actionName = i.kind === 256 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
134782                 return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
134783             },
134784             getEditsForAction: function (context, actionName) {
134785                 ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace, "Unexpected action name");
134786                 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")); });
134787                 return { edits: edits, renameFilename: undefined, renameLocation: undefined };
134788             }
134789         });
134790         // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`.
134791         function getImportToConvert(context) {
134792             var file = context.file;
134793             var span = ts.getRefactorContextSpan(context);
134794             var token = ts.getTokenAtPosition(file, span.start);
134795             var importDecl = ts.getParentNodeInSpan(token, file, span);
134796             if (!importDecl || !ts.isImportDeclaration(importDecl))
134797                 return undefined;
134798             var importClause = importDecl.importClause;
134799             return importClause && importClause.namedBindings;
134800         }
134801         function doChange(sourceFile, program, changes, toConvert) {
134802             var checker = program.getTypeChecker();
134803             if (toConvert.kind === 256 /* NamespaceImport */) {
134804                 doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()));
134805             }
134806             else {
134807                 doChangeNamedToNamespace(sourceFile, checker, changes, toConvert);
134808             }
134809         }
134810         function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
134811             var usedAsNamespaceOrDefault = false;
134812             var nodesToReplace = [];
134813             var conflictingNames = ts.createMap();
134814             ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
134815                 if (!ts.isPropertyAccessExpression(id.parent)) {
134816                     usedAsNamespaceOrDefault = true;
134817                 }
134818                 else {
134819                     var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
134820                     var exportName = parent.name.text;
134821                     if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
134822                         conflictingNames.set(exportName, true);
134823                     }
134824                     ts.Debug.assert(parent.expression === id, "Parent expression should match id");
134825                     nodesToReplace.push(parent);
134826                 }
134827             });
134828             // We may need to change `mod.x` to `_x` to avoid a name conflict.
134829             var exportNameToImportName = ts.createMap();
134830             for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
134831                 var propertyAccess = nodesToReplace_1[_i];
134832                 var exportName = propertyAccess.name.text;
134833                 var importName = exportNameToImportName.get(exportName);
134834                 if (importName === undefined) {
134835                     exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
134836                 }
134837                 changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName));
134838             }
134839             var importSpecifiers = [];
134840             exportNameToImportName.forEach(function (name, propertyName) {
134841                 importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)));
134842             });
134843             var importDecl = toConvert.parent.parent;
134844             if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
134845                 // Need to leave the namespace import alone
134846                 changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers));
134847             }
134848             else {
134849                 changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
134850             }
134851         }
134852         function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) {
134853             var importDecl = toConvert.parent.parent;
134854             var moduleSpecifier = importDecl.moduleSpecifier;
134855             var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module";
134856             var namespaceNameConflicts = toConvert.elements.some(function (element) {
134857                 return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
134858                     return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true);
134859                 }) || false;
134860             });
134861             var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
134862             var neededNamedImports = [];
134863             var _loop_15 = function (element) {
134864                 var propertyName = (element.propertyName || element.name).text;
134865                 ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
134866                     var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
134867                     if (ts.isShorthandPropertyAssignment(id.parent)) {
134868                         changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access));
134869                     }
134870                     else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) {
134871                         if (!neededNamedImports.some(function (n) { return n.name === element.name; })) {
134872                             neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text)));
134873                         }
134874                     }
134875                     else {
134876                         changes.replaceNode(sourceFile, id, access);
134877                     }
134878                 });
134879             };
134880             for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
134881                 var element = _a[_i];
134882                 _loop_15(element);
134883             }
134884             changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
134885             if (neededNamedImports.length) {
134886                 changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports));
134887             }
134888         }
134889         function updateImport(old, defaultImportName, elements) {
134890             return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier);
134891         }
134892     })(refactor = ts.refactor || (ts.refactor = {}));
134893 })(ts || (ts = {}));
134894 /* @internal */
134895 var ts;
134896 (function (ts) {
134897     var refactor;
134898     (function (refactor) {
134899         var extractSymbol;
134900         (function (extractSymbol) {
134901             var refactorName = "Extract Symbol";
134902             refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction });
134903             /**
134904              * Compute the associated code actions
134905              * Exported for tests.
134906              */
134907             function getAvailableActions(context) {
134908                 var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
134909                 var targetRange = rangeToExtract.targetRange;
134910                 if (targetRange === undefined) {
134911                     return ts.emptyArray;
134912                 }
134913                 var extractions = getPossibleExtractions(targetRange, context);
134914                 if (extractions === undefined) {
134915                     // No extractions possible
134916                     return ts.emptyArray;
134917                 }
134918                 var functionActions = [];
134919                 var usedFunctionNames = ts.createMap();
134920                 var constantActions = [];
134921                 var usedConstantNames = ts.createMap();
134922                 var i = 0;
134923                 for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) {
134924                     var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction;
134925                     // Skip these since we don't have a way to report errors yet
134926                     if (functionExtraction.errors.length === 0) {
134927                         // Don't issue refactorings with duplicated names.
134928                         // Scopes come back in "innermost first" order, so extractions will
134929                         // preferentially go into nearer scopes
134930                         var description = functionExtraction.description;
134931                         if (!usedFunctionNames.has(description)) {
134932                             usedFunctionNames.set(description, true);
134933                             functionActions.push({
134934                                 description: description,
134935                                 name: "function_scope_" + i
134936                             });
134937                         }
134938                     }
134939                     // Skip these since we don't have a way to report errors yet
134940                     if (constantExtraction.errors.length === 0) {
134941                         // Don't issue refactorings with duplicated names.
134942                         // Scopes come back in "innermost first" order, so extractions will
134943                         // preferentially go into nearer scopes
134944                         var description = constantExtraction.description;
134945                         if (!usedConstantNames.has(description)) {
134946                             usedConstantNames.set(description, true);
134947                             constantActions.push({
134948                                 description: description,
134949                                 name: "constant_scope_" + i
134950                             });
134951                         }
134952                     }
134953                     // *do* increment i anyway because we'll look for the i-th scope
134954                     // later when actually doing the refactoring if the user requests it
134955                     i++;
134956                 }
134957                 var infos = [];
134958                 if (constantActions.length) {
134959                     infos.push({
134960                         name: refactorName,
134961                         description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant),
134962                         actions: constantActions
134963                     });
134964                 }
134965                 if (functionActions.length) {
134966                     infos.push({
134967                         name: refactorName,
134968                         description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function),
134969                         actions: functionActions
134970                     });
134971                 }
134972                 return infos.length ? infos : ts.emptyArray;
134973             }
134974             extractSymbol.getAvailableActions = getAvailableActions;
134975             /* Exported for tests */
134976             function getEditsForAction(context, actionName) {
134977                 var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
134978                 var targetRange = rangeToExtract.targetRange; // TODO:GH#18217
134979                 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
134980                 if (parsedFunctionIndexMatch) {
134981                     var index = +parsedFunctionIndexMatch[1];
134982                     ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
134983                     return getFunctionExtractionAtIndex(targetRange, context, index);
134984                 }
134985                 var parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName);
134986                 if (parsedConstantIndexMatch) {
134987                     var index = +parsedConstantIndexMatch[1];
134988                     ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
134989                     return getConstantExtractionAtIndex(targetRange, context, index);
134990                 }
134991                 ts.Debug.fail("Unrecognized action name");
134992             }
134993             extractSymbol.getEditsForAction = getEditsForAction;
134994             // Move these into diagnostic messages if they become user-facing
134995             var Messages;
134996             (function (Messages) {
134997                 function createMessage(message) {
134998                     return { message: message, code: 0, category: ts.DiagnosticCategory.Message, key: message };
134999                 }
135000                 Messages.cannotExtractRange = createMessage("Cannot extract range.");
135001                 Messages.cannotExtractImport = createMessage("Cannot extract import statement.");
135002                 Messages.cannotExtractSuper = createMessage("Cannot extract super call.");
135003                 Messages.cannotExtractJSDoc = createMessage("Cannot extract JSDoc.");
135004                 Messages.cannotExtractEmpty = createMessage("Cannot extract empty range.");
135005                 Messages.expressionExpected = createMessage("expression expected.");
135006                 Messages.uselessConstantType = createMessage("No reason to extract constant of type.");
135007                 Messages.statementOrExpressionExpected = createMessage("Statement or expression expected.");
135008                 Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements.");
135009                 Messages.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement.");
135010                 Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
135011                 Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
135012                 Messages.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
135013                 Messages.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
135014                 Messages.cannotExtractIdentifier = createMessage("Select more than a single identifier.");
135015                 Messages.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
135016                 Messages.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
135017                 Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
135018                 Messages.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
135019                 Messages.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
135020                 Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
135021                 Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
135022                 Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
135023             })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {}));
135024             var RangeFacts;
135025             (function (RangeFacts) {
135026                 RangeFacts[RangeFacts["None"] = 0] = "None";
135027                 RangeFacts[RangeFacts["HasReturn"] = 1] = "HasReturn";
135028                 RangeFacts[RangeFacts["IsGenerator"] = 2] = "IsGenerator";
135029                 RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction";
135030                 RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis";
135031                 /**
135032                  * The range is in a function which needs the 'static' modifier in a class
135033                  */
135034                 RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion";
135035             })(RangeFacts || (RangeFacts = {}));
135036             /**
135037              * getRangeToExtract takes a span inside a text file and returns either an expression or an array
135038              * of statements representing the minimum set of nodes needed to extract the entire span. This
135039              * process may fail, in which case a set of errors is returned instead (these are currently
135040              * not shown to the user, but can be used by us diagnostically)
135041              */
135042             // exported only for tests
135043             function getRangeToExtract(sourceFile, span) {
135044                 var length = span.length;
135045                 if (length === 0) {
135046                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] };
135047                 }
135048                 // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
135049                 // This may fail (e.g. you select two statements in the root of a source file)
135050                 var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span);
135051                 // Do the same for the ending position
135052                 var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span);
135053                 var declarations = [];
135054                 // We'll modify these flags as we walk the tree to collect data
135055                 // about what things need to be done as part of the extraction.
135056                 var rangeFacts = RangeFacts.None;
135057                 if (!start || !end) {
135058                     // cannot find either start or end node
135059                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
135060                 }
135061                 if (start.parent !== end.parent) {
135062                     // start and end nodes belong to different subtrees
135063                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
135064                 }
135065                 if (start !== end) {
135066                     // start and end should be statements and parent should be either block or a source file
135067                     if (!isBlockLike(start.parent)) {
135068                         return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
135069                     }
135070                     var statements = [];
135071                     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
135072                     for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) {
135073                         var statement = _a[_i];
135074                         if (statement === start || statements.length) {
135075                             var errors_1 = checkNode(statement);
135076                             if (errors_1) {
135077                                 return { errors: errors_1 };
135078                             }
135079                             statements.push(statement);
135080                         }
135081                         if (statement === end) {
135082                             break;
135083                         }
135084                     }
135085                     if (!statements.length) {
135086                         // https://github.com/Microsoft/TypeScript/issues/20559
135087                         // Ranges like [|case 1: break;|] will fail to populate `statements` because
135088                         // they will never find `start` in `start.parent.statements`.
135089                         // Consider: We could support ranges like [|case 1:|] by refining them to just
135090                         // the expression.
135091                         return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
135092                     }
135093                     return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } };
135094                 }
135095                 if (ts.isJSDoc(start)) {
135096                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] };
135097                 }
135098                 if (ts.isReturnStatement(start) && !start.expression) {
135099                     // Makes no sense to extract an expression-less return statement.
135100                     return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
135101                 }
135102                 // We have a single node (start)
135103                 var node = refineNode(start);
135104                 var errors = checkRootNode(node) || checkNode(node);
135105                 if (errors) {
135106                     return { errors: errors };
135107                 }
135108                 return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217
135109                 /**
135110                  * Attempt to refine the extraction node (generally, by shrinking it) to produce better results.
135111                  * @param node The unrefined extraction node.
135112                  */
135113                 function refineNode(node) {
135114                     if (ts.isReturnStatement(node)) {
135115                         if (node.expression) {
135116                             return node.expression;
135117                         }
135118                     }
135119                     else if (ts.isVariableStatement(node)) {
135120                         var numInitializers = 0;
135121                         var lastInitializer = void 0;
135122                         for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
135123                             var declaration = _a[_i];
135124                             if (declaration.initializer) {
135125                                 numInitializers++;
135126                                 lastInitializer = declaration.initializer;
135127                             }
135128                         }
135129                         if (numInitializers === 1) {
135130                             return lastInitializer;
135131                         }
135132                         // No special handling if there are multiple initializers.
135133                     }
135134                     else if (ts.isVariableDeclaration(node)) {
135135                         if (node.initializer) {
135136                             return node.initializer;
135137                         }
135138                     }
135139                     return node;
135140                 }
135141                 function checkRootNode(node) {
135142                     if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) {
135143                         return [ts.createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
135144                     }
135145                     return undefined;
135146                 }
135147                 function checkForStaticContext(nodeToCheck, containingClass) {
135148                     var current = nodeToCheck;
135149                     while (current !== containingClass) {
135150                         if (current.kind === 159 /* PropertyDeclaration */) {
135151                             if (ts.hasModifier(current, 32 /* Static */)) {
135152                                 rangeFacts |= RangeFacts.InStaticRegion;
135153                             }
135154                             break;
135155                         }
135156                         else if (current.kind === 156 /* Parameter */) {
135157                             var ctorOrMethod = ts.getContainingFunction(current);
135158                             if (ctorOrMethod.kind === 162 /* Constructor */) {
135159                                 rangeFacts |= RangeFacts.InStaticRegion;
135160                             }
135161                             break;
135162                         }
135163                         else if (current.kind === 161 /* MethodDeclaration */) {
135164                             if (ts.hasModifier(current, 32 /* Static */)) {
135165                                 rangeFacts |= RangeFacts.InStaticRegion;
135166                             }
135167                         }
135168                         current = current.parent;
135169                     }
135170                 }
135171                 // Verifies whether we can actually extract this node or not.
135172                 function checkNode(nodeToCheck) {
135173                     var PermittedJumps;
135174                     (function (PermittedJumps) {
135175                         PermittedJumps[PermittedJumps["None"] = 0] = "None";
135176                         PermittedJumps[PermittedJumps["Break"] = 1] = "Break";
135177                         PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue";
135178                         PermittedJumps[PermittedJumps["Return"] = 4] = "Return";
135179                     })(PermittedJumps || (PermittedJumps = {}));
135180                     // We believe it's true because the node is from the (unmodified) tree.
135181                     ts.Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)");
135182                     // For understanding how skipTrivia functioned:
135183                     ts.Debug.assert(!ts.positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)");
135184                     if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) {
135185                         return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
135186                     }
135187                     if (nodeToCheck.flags & 8388608 /* Ambient */) {
135188                         return [ts.createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
135189                     }
135190                     // If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)
135191                     var containingClass = ts.getContainingClass(nodeToCheck);
135192                     if (containingClass) {
135193                         checkForStaticContext(nodeToCheck, containingClass);
135194                     }
135195                     var errors;
135196                     var permittedJumps = 4 /* Return */;
135197                     var seenLabels;
135198                     visit(nodeToCheck);
135199                     return errors;
135200                     function visit(node) {
135201                         if (errors) {
135202                             // already found an error - can stop now
135203                             return true;
135204                         }
135205                         if (ts.isDeclaration(node)) {
135206                             var declaringNode = (node.kind === 242 /* VariableDeclaration */) ? node.parent.parent : node;
135207                             if (ts.hasModifier(declaringNode, 1 /* Export */)) {
135208                                 // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)
135209                                 // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!
135210                                 // Also TODO: GH#19956
135211                                 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
135212                                 return true;
135213                             }
135214                             declarations.push(node.symbol);
135215                         }
135216                         // Some things can't be extracted in certain situations
135217                         switch (node.kind) {
135218                             case 254 /* ImportDeclaration */:
135219                                 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport));
135220                                 return true;
135221                             case 102 /* SuperKeyword */:
135222                                 // For a super *constructor call*, we have to be extracting the entire class,
135223                                 // but a super *method call* simply implies a 'this' reference
135224                                 if (node.parent.kind === 196 /* CallExpression */) {
135225                                     // Super constructor call
135226                                     var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217
135227                                     if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) {
135228                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper));
135229                                         return true;
135230                                     }
135231                                 }
135232                                 else {
135233                                     rangeFacts |= RangeFacts.UsesThis;
135234                                 }
135235                                 break;
135236                         }
135237                         if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) {
135238                             switch (node.kind) {
135239                                 case 244 /* FunctionDeclaration */:
135240                                 case 245 /* ClassDeclaration */:
135241                                     if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
135242                                         // You cannot extract global declarations
135243                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
135244                                     }
135245                                     break;
135246                             }
135247                             // do not dive into functions or classes
135248                             return false;
135249                         }
135250                         var savedPermittedJumps = permittedJumps;
135251                         switch (node.kind) {
135252                             case 227 /* IfStatement */:
135253                                 permittedJumps = 0 /* None */;
135254                                 break;
135255                             case 240 /* TryStatement */:
135256                                 // forbid all jumps inside try blocks
135257                                 permittedJumps = 0 /* None */;
135258                                 break;
135259                             case 223 /* Block */:
135260                                 if (node.parent && node.parent.kind === 240 /* TryStatement */ && node.parent.finallyBlock === node) {
135261                                     // allow unconditional returns from finally blocks
135262                                     permittedJumps = 4 /* Return */;
135263                                 }
135264                                 break;
135265                             case 278 /* DefaultClause */:
135266                             case 277 /* CaseClause */:
135267                                 // allow unlabeled break inside case clauses
135268                                 permittedJumps |= 1 /* Break */;
135269                                 break;
135270                             default:
135271                                 if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) {
135272                                     // allow unlabeled break/continue inside loops
135273                                     permittedJumps |= 1 /* Break */ | 2 /* Continue */;
135274                                 }
135275                                 break;
135276                         }
135277                         switch (node.kind) {
135278                             case 183 /* ThisType */:
135279                             case 104 /* ThisKeyword */:
135280                                 rangeFacts |= RangeFacts.UsesThis;
135281                                 break;
135282                             case 238 /* LabeledStatement */: {
135283                                 var label = node.label;
135284                                 (seenLabels || (seenLabels = [])).push(label.escapedText);
135285                                 ts.forEachChild(node, visit);
135286                                 seenLabels.pop();
135287                                 break;
135288                             }
135289                             case 234 /* BreakStatement */:
135290                             case 233 /* ContinueStatement */: {
135291                                 var label = node.label;
135292                                 if (label) {
135293                                     if (!ts.contains(seenLabels, label.escapedText)) {
135294                                         // attempts to jump to label that is not in range to be extracted
135295                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
135296                                     }
135297                                 }
135298                                 else {
135299                                     if (!(permittedJumps & (node.kind === 234 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
135300                                         // attempt to break or continue in a forbidden context
135301                                         (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
135302                                     }
135303                                 }
135304                                 break;
135305                             }
135306                             case 206 /* AwaitExpression */:
135307                                 rangeFacts |= RangeFacts.IsAsyncFunction;
135308                                 break;
135309                             case 212 /* YieldExpression */:
135310                                 rangeFacts |= RangeFacts.IsGenerator;
135311                                 break;
135312                             case 235 /* ReturnStatement */:
135313                                 if (permittedJumps & 4 /* Return */) {
135314                                     rangeFacts |= RangeFacts.HasReturn;
135315                                 }
135316                                 else {
135317                                     (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement));
135318                                 }
135319                                 break;
135320                             default:
135321                                 ts.forEachChild(node, visit);
135322                                 break;
135323                         }
135324                         permittedJumps = savedPermittedJumps;
135325                     }
135326                 }
135327             }
135328             extractSymbol.getRangeToExtract = getRangeToExtract;
135329             function getStatementOrExpressionRange(node) {
135330                 if (ts.isStatement(node)) {
135331                     return [node];
135332                 }
135333                 else if (ts.isExpressionNode(node)) {
135334                     // If our selection is the expression in an ExpressionStatement, expand
135335                     // the selection to include the enclosing Statement (this stops us
135336                     // from trying to care about the return value of the extracted function
135337                     // and eliminates double semicolon insertion in certain scenarios)
135338                     return ts.isExpressionStatement(node.parent) ? [node.parent] : node;
135339                 }
135340                 return undefined;
135341             }
135342             function isScope(node) {
135343                 return ts.isFunctionLikeDeclaration(node) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node);
135344             }
135345             /**
135346              * Computes possible places we could extract the function into. For example,
135347              * you may be able to extract into a class method *or* local closure *or* namespace function,
135348              * depending on what's in the extracted body.
135349              */
135350             function collectEnclosingScopes(range) {
135351                 var current = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
135352                 if (range.facts & RangeFacts.UsesThis) {
135353                     // 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
135354                     var containingClass = ts.getContainingClass(current);
135355                     if (containingClass) {
135356                         var containingFunction = ts.findAncestor(current, ts.isFunctionLikeDeclaration);
135357                         return containingFunction
135358                             ? [containingFunction, containingClass]
135359                             : [containingClass];
135360                     }
135361                 }
135362                 var scopes = [];
135363                 while (true) {
135364                     current = current.parent;
135365                     // A function parameter's initializer is actually in the outer scope, not the function declaration
135366                     if (current.kind === 156 /* Parameter */) {
135367                         // Skip all the way to the outer scope of the function that declared this parameter
135368                         current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent;
135369                     }
135370                     // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of.
135371                     // Walk up to the closest parent of a place where we can logically put a sibling:
135372                     //  * Function declaration
135373                     //  * Class declaration or expression
135374                     //  * Module/namespace or source file
135375                     if (isScope(current)) {
135376                         scopes.push(current);
135377                         if (current.kind === 290 /* SourceFile */) {
135378                             return scopes;
135379                         }
135380                     }
135381                 }
135382             }
135383             function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) {
135384                 var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
135385                 ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
135386                 context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217
135387                 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
135388             }
135389             function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) {
135390                 var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, constantErrorsPerScope = _b.constantErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations;
135391                 ts.Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
135392                 ts.Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
135393                 context.cancellationToken.throwIfCancellationRequested();
135394                 var expression = ts.isExpression(target)
135395                     ? target
135396                     : target.statements[0].expression;
135397                 return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
135398             }
135399             /**
135400              * Given a piece of text to extract ('targetRange'), computes a list of possible extractions.
135401              * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes
135402              * or an error explaining why we can't extract into that scope.
135403              */
135404             function getPossibleExtractions(targetRange, context) {
135405                 var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, functionErrorsPerScope = _b.functionErrorsPerScope, constantErrorsPerScope = _b.constantErrorsPerScope;
135406                 // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547
135407                 var extractions = scopes.map(function (scope, i) {
135408                     var functionDescriptionPart = getDescriptionForFunctionInScope(scope);
135409                     var constantDescriptionPart = getDescriptionForConstantInScope(scope);
135410                     var scopeDescription = ts.isFunctionLikeDeclaration(scope)
135411                         ? getDescriptionForFunctionLikeDeclaration(scope)
135412                         : ts.isClassLike(scope)
135413                             ? getDescriptionForClassLikeDeclaration(scope)
135414                             : getDescriptionForModuleLikeDeclaration(scope);
135415                     var functionDescription;
135416                     var constantDescription;
135417                     if (scopeDescription === 1 /* Global */) {
135418                         functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
135419                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
135420                     }
135421                     else if (scopeDescription === 0 /* Module */) {
135422                         functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
135423                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
135424                     }
135425                     else {
135426                         functionDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
135427                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
135428                     }
135429                     // Customize the phrasing for the innermost scope to increase clarity.
135430                     if (i === 0 && !ts.isClassLike(scope)) {
135431                         constantDescription = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
135432                     }
135433                     return {
135434                         functionExtraction: {
135435                             description: functionDescription,
135436                             errors: functionErrorsPerScope[i],
135437                         },
135438                         constantExtraction: {
135439                             description: constantDescription,
135440                             errors: constantErrorsPerScope[i],
135441                         },
135442                     };
135443                 });
135444                 return extractions;
135445             }
135446             function getPossibleExtractionsWorker(targetRange, context) {
135447                 var sourceFile = context.file;
135448                 var scopes = collectEnclosingScopes(targetRange);
135449                 var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
135450                 var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken);
135451                 return { scopes: scopes, readsAndWrites: readsAndWrites };
135452             }
135453             function getDescriptionForFunctionInScope(scope) {
135454                 return ts.isFunctionLikeDeclaration(scope)
135455                     ? "inner function"
135456                     : ts.isClassLike(scope)
135457                         ? "method"
135458                         : "function";
135459             }
135460             function getDescriptionForConstantInScope(scope) {
135461                 return ts.isClassLike(scope)
135462                     ? "readonly field"
135463                     : "constant";
135464             }
135465             function getDescriptionForFunctionLikeDeclaration(scope) {
135466                 switch (scope.kind) {
135467                     case 162 /* Constructor */:
135468                         return "constructor";
135469                     case 201 /* FunctionExpression */:
135470                     case 244 /* FunctionDeclaration */:
135471                         return scope.name
135472                             ? "function '" + scope.name.text + "'"
135473                             : ts.ANONYMOUS;
135474                     case 202 /* ArrowFunction */:
135475                         return "arrow function";
135476                     case 161 /* MethodDeclaration */:
135477                         return "method '" + scope.name.getText() + "'";
135478                     case 163 /* GetAccessor */:
135479                         return "'get " + scope.name.getText() + "'";
135480                     case 164 /* SetAccessor */:
135481                         return "'set " + scope.name.getText() + "'";
135482                     default:
135483                         throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind);
135484                 }
135485             }
135486             function getDescriptionForClassLikeDeclaration(scope) {
135487                 return scope.kind === 245 /* ClassDeclaration */
135488                     ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration"
135489                     : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression";
135490             }
135491             function getDescriptionForModuleLikeDeclaration(scope) {
135492                 return scope.kind === 250 /* ModuleBlock */
135493                     ? "namespace '" + scope.parent.name.getText() + "'"
135494                     : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
135495             }
135496             var SpecialScope;
135497             (function (SpecialScope) {
135498                 SpecialScope[SpecialScope["Module"] = 0] = "Module";
135499                 SpecialScope[SpecialScope["Global"] = 1] = "Global";
135500             })(SpecialScope || (SpecialScope = {}));
135501             /**
135502              * Result of 'extractRange' operation for a specific scope.
135503              * Stores either a list of changes that should be applied to extract a range or a list of errors
135504              */
135505             function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) {
135506                 var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions;
135507                 var checker = context.program.getTypeChecker();
135508                 var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions());
135509                 var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host);
135510                 // Make a unique name for the extracted function
135511                 var file = scope.getSourceFile();
135512                 var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file);
135513                 var isJS = ts.isInJSFile(scope);
135514                 var functionName = ts.createIdentifier(functionNameText);
135515                 var returnType;
135516                 var parameters = [];
135517                 var callArguments = [];
135518                 var writes;
135519                 usagesInScope.forEach(function (usage, name) {
135520                     var typeNode;
135521                     if (!isJS) {
135522                         var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
135523                         // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
135524                         type = checker.getBaseTypeOfLiteralType(type);
135525                         typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */);
135526                     }
135527                     var paramDecl = ts.createParameter(
135528                     /*decorators*/ undefined, 
135529                     /*modifiers*/ undefined, 
135530                     /*dotDotDotToken*/ undefined, 
135531                     /*name*/ name, 
135532                     /*questionToken*/ undefined, typeNode);
135533                     parameters.push(paramDecl);
135534                     if (usage.usage === 2 /* Write */) {
135535                         (writes || (writes = [])).push(usage);
135536                     }
135537                     callArguments.push(ts.createIdentifier(name));
135538                 });
135539                 var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); });
135540                 var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
135541                 var typeParameters = sortedTypeParametersAndDeclarations.length === 0
135542                     ? undefined
135543                     : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; });
135544                 // Strictly speaking, we should check whether each name actually binds to the appropriate type
135545                 // parameter.  In cases of shadowing, they may not.
135546                 var callTypeArguments = typeParameters !== undefined
135547                     ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); })
135548                     : undefined;
135549                 // Provide explicit return types for contextually-typed functions
135550                 // to avoid problems when there are literal types present
135551                 if (ts.isExpression(node) && !isJS) {
135552                     var contextualType = checker.getContextualType(node);
135553                     returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217
135554                 }
135555                 var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty;
135556                 ts.suppressLeadingAndTrailingTrivia(body);
135557                 var newFunction;
135558                 if (ts.isClassLike(scope)) {
135559                     // always create private method in TypeScript files
135560                     var modifiers = isJS ? [] : [ts.createToken(117 /* PrivateKeyword */)];
135561                     if (range.facts & RangeFacts.InStaticRegion) {
135562                         modifiers.push(ts.createToken(120 /* StaticKeyword */));
135563                     }
135564                     if (range.facts & RangeFacts.IsAsyncFunction) {
135565                         modifiers.push(ts.createToken(126 /* AsyncKeyword */));
135566                     }
135567                     newFunction = ts.createMethod(
135568                     /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(41 /* AsteriskToken */) : undefined, functionName, 
135569                     /*questionToken*/ undefined, typeParameters, parameters, returnType, body);
135570                 }
135571                 else {
135572                     newFunction = ts.createFunctionDeclaration(
135573                     /*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);
135574                 }
135575                 var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
135576                 var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end;
135577                 var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
135578                 if (nodeToInsertBefore) {
135579                     changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true);
135580                 }
135581                 else {
135582                     changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
135583                 }
135584                 importAdder.writeFixes(changeTracker);
135585                 var newNodes = [];
135586                 // replace range with function call
135587                 var called = getCalledExpression(scope, range, functionNameText);
135588                 var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference
135589                 callArguments);
135590                 if (range.facts & RangeFacts.IsGenerator) {
135591                     call = ts.createYield(ts.createToken(41 /* AsteriskToken */), call);
135592                 }
135593                 if (range.facts & RangeFacts.IsAsyncFunction) {
135594                     call = ts.createAwait(call);
135595                 }
135596                 if (exposedVariableDeclarations.length && !writes) {
135597                     // No need to mix declarations and writes.
135598                     // How could any variables be exposed if there's a return statement?
135599                     ts.Debug.assert(!returnValueProperty, "Expected no returnValueProperty");
135600                     ts.Debug.assert(!(range.facts & RangeFacts.HasReturn), "Expected RangeFacts.HasReturn flag to be unset");
135601                     if (exposedVariableDeclarations.length === 1) {
135602                         // Declaring exactly one variable: let x = newFunction();
135603                         var variableDeclaration = exposedVariableDeclarations[0];
135604                         newNodes.push(ts.createVariableStatement(
135605                         /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(variableDeclaration.name), /*type*/ ts.getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], // TODO (acasey): test binding patterns
135606                         variableDeclaration.parent.flags)));
135607                     }
135608                     else {
135609                         // Declaring multiple variables / return properties:
135610                         //   let {x, y} = newFunction();
135611                         var bindingElements = [];
135612                         var typeElements = [];
135613                         var commonNodeFlags = exposedVariableDeclarations[0].parent.flags;
135614                         var sawExplicitType = false;
135615                         for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) {
135616                             var variableDeclaration = exposedVariableDeclarations_1[_i];
135617                             bindingElements.push(ts.createBindingElement(
135618                             /*dotDotDotToken*/ undefined, 
135619                             /*propertyName*/ undefined, 
135620                             /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name)));
135621                             // Being returned through an object literal will have widened the type.
135622                             var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */);
135623                             typeElements.push(ts.createPropertySignature(
135624                             /*modifiers*/ undefined, 
135625                             /*name*/ variableDeclaration.symbol.name, 
135626                             /*questionToken*/ undefined, 
135627                             /*type*/ variableType, 
135628                             /*initializer*/ undefined));
135629                             sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined;
135630                             commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags;
135631                         }
135632                         var typeLiteral = sawExplicitType ? ts.createTypeLiteralNode(typeElements) : undefined;
135633                         if (typeLiteral) {
135634                             ts.setEmitFlags(typeLiteral, 1 /* SingleLine */);
135635                         }
135636                         newNodes.push(ts.createVariableStatement(
135637                         /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.createObjectBindingPattern(bindingElements), 
135638                             /*type*/ typeLiteral, 
135639                             /*initializer*/ call)], commonNodeFlags)));
135640                     }
135641                 }
135642                 else if (exposedVariableDeclarations.length || writes) {
135643                     if (exposedVariableDeclarations.length) {
135644                         // CONSIDER: we're going to create one statement per variable, but we could actually preserve their original grouping.
135645                         for (var _c = 0, exposedVariableDeclarations_2 = exposedVariableDeclarations; _c < exposedVariableDeclarations_2.length; _c++) {
135646                             var variableDeclaration = exposedVariableDeclarations_2[_c];
135647                             var flags = variableDeclaration.parent.flags;
135648                             if (flags & 2 /* Const */) {
135649                                 flags = (flags & ~2 /* Const */) | 1 /* Let */;
135650                             }
135651                             newNodes.push(ts.createVariableStatement(
135652                             /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(variableDeclaration.symbol.name, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags)));
135653                         }
135654                     }
135655                     if (returnValueProperty) {
135656                         // has both writes and return, need to create variable declaration to hold return value;
135657                         newNodes.push(ts.createVariableStatement(
135658                         /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(returnValueProperty, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */)));
135659                     }
135660                     var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
135661                     if (returnValueProperty) {
135662                         assignments.unshift(ts.createShorthandPropertyAssignment(returnValueProperty));
135663                     }
135664                     // propagate writes back
135665                     if (assignments.length === 1) {
135666                         // We would only have introduced a return value property if there had been
135667                         // other assignments to make.
135668                         ts.Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here");
135669                         newNodes.push(ts.createStatement(ts.createAssignment(assignments[0].name, call)));
135670                         if (range.facts & RangeFacts.HasReturn) {
135671                             newNodes.push(ts.createReturn());
135672                         }
135673                     }
135674                     else {
135675                         // emit e.g.
135676                         //   { a, b, __return } = newFunction(a, b);
135677                         //   return __return;
135678                         newNodes.push(ts.createStatement(ts.createAssignment(ts.createObjectLiteral(assignments), call)));
135679                         if (returnValueProperty) {
135680                             newNodes.push(ts.createReturn(ts.createIdentifier(returnValueProperty)));
135681                         }
135682                     }
135683                 }
135684                 else {
135685                     if (range.facts & RangeFacts.HasReturn) {
135686                         newNodes.push(ts.createReturn(call));
135687                     }
135688                     else if (isReadonlyArray(range.range)) {
135689                         newNodes.push(ts.createStatement(call));
135690                     }
135691                     else {
135692                         newNodes.push(call);
135693                     }
135694                 }
135695                 if (isReadonlyArray(range.range)) {
135696                     changeTracker.replaceNodeRangeWithNodes(context.file, ts.first(range.range), ts.last(range.range), newNodes);
135697                 }
135698                 else {
135699                     changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes);
135700                 }
135701                 var edits = changeTracker.getChanges();
135702                 var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range;
135703                 var renameFilename = renameRange.getSourceFile().fileName;
135704                 var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false);
135705                 return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
135706                 function getTypeDeepCloneUnionUndefined(typeNode) {
135707                     if (typeNode === undefined) {
135708                         return undefined;
135709                     }
135710                     var clone = ts.getSynthesizedDeepClone(typeNode);
135711                     var withoutParens = clone;
135712                     while (ts.isParenthesizedTypeNode(withoutParens)) {
135713                         withoutParens = withoutParens.type;
135714                     }
135715                     return ts.isUnionTypeNode(withoutParens) && ts.find(withoutParens.types, function (t) { return t.kind === 146 /* UndefinedKeyword */; })
135716                         ? clone
135717                         : ts.createUnionTypeNode([clone, ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
135718                 }
135719             }
135720             /**
135721              * Result of 'extractRange' operation for a specific scope.
135722              * Stores either a list of changes that should be applied to extract a range or a list of errors
135723              */
135724             function extractConstantInScope(node, scope, _a, rangeFacts, context) {
135725                 var _b;
135726                 var substitutions = _a.substitutions;
135727                 var checker = context.program.getTypeChecker();
135728                 // Make a unique name for the extracted variable
135729                 var file = scope.getSourceFile();
135730                 var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file);
135731                 var isJS = ts.isInJSFile(scope);
135732                 var variableType = isJS || !checker.isContextSensitive(node)
135733                     ? undefined
135734                     : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217
135735                 var initializer = transformConstantInitializer(node, substitutions);
135736                 (_b = transformFunctionInitializerAndType(variableType, initializer), variableType = _b.variableType, initializer = _b.initializer);
135737                 ts.suppressLeadingAndTrailingTrivia(initializer);
135738                 var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
135739                 if (ts.isClassLike(scope)) {
135740                     ts.Debug.assert(!isJS, "Cannot extract to a JS class"); // See CannotExtractToJSClass
135741                     var modifiers = [];
135742                     modifiers.push(ts.createToken(117 /* PrivateKeyword */));
135743                     if (rangeFacts & RangeFacts.InStaticRegion) {
135744                         modifiers.push(ts.createToken(120 /* StaticKeyword */));
135745                     }
135746                     modifiers.push(ts.createToken(138 /* ReadonlyKeyword */));
135747                     var newVariable = ts.createProperty(
135748                     /*decorators*/ undefined, modifiers, localNameText, 
135749                     /*questionToken*/ undefined, variableType, initializer);
135750                     var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion
135751                         ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217
135752                         : ts.createThis(), ts.createIdentifier(localNameText));
135753                     // Declare
135754                     var maxInsertionPos = node.pos;
135755                     var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope);
135756                     changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true);
135757                     // Consume
135758                     changeTracker.replaceNode(context.file, node, localReference);
135759                 }
135760                 else {
135761                     var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer);
135762                     // If the node is part of an initializer in a list of variable declarations, insert a new
135763                     // variable declaration into the list (in case it depends on earlier ones).
135764                     // CONSIDER: If the declaration list isn't const, we might want to split it into multiple
135765                     // lists so that the newly extracted one can be const.
135766                     var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope);
135767                     if (oldVariableDeclaration) {
135768                         // Declare
135769                         // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`)
135770                         changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration);
135771                         // Consume
135772                         var localReference = ts.createIdentifier(localNameText);
135773                         changeTracker.replaceNode(context.file, node, localReference);
135774                     }
135775                     else if (node.parent.kind === 226 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) {
135776                         // If the parent is an expression statement and the target scope is the immediately enclosing one,
135777                         // replace the statement with the declaration.
135778                         var newVariableStatement = ts.createVariableStatement(
135779                         /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
135780                         changeTracker.replaceNode(context.file, node.parent, newVariableStatement);
135781                     }
135782                     else {
135783                         var newVariableStatement = ts.createVariableStatement(
135784                         /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */));
135785                         // Declare
135786                         var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope);
135787                         if (nodeToInsertBefore.pos === 0) {
135788                             changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false);
135789                         }
135790                         else {
135791                             changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false);
135792                         }
135793                         // Consume
135794                         if (node.parent.kind === 226 /* ExpressionStatement */) {
135795                             // If the parent is an expression statement, delete it.
135796                             changeTracker.delete(context.file, node.parent);
135797                         }
135798                         else {
135799                             var localReference = ts.createIdentifier(localNameText);
135800                             changeTracker.replaceNode(context.file, node, localReference);
135801                         }
135802                     }
135803                 }
135804                 var edits = changeTracker.getChanges();
135805                 var renameFilename = node.getSourceFile().fileName;
135806                 var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true);
135807                 return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
135808                 function transformFunctionInitializerAndType(variableType, initializer) {
135809                     // If no contextual type exists there is nothing to transfer to the function signature
135810                     if (variableType === undefined)
135811                         return { variableType: variableType, initializer: initializer };
135812                     // Only do this for function expressions and arrow functions that are not generic
135813                     if (!ts.isFunctionExpression(initializer) && !ts.isArrowFunction(initializer) || !!initializer.typeParameters)
135814                         return { variableType: variableType, initializer: initializer };
135815                     var functionType = checker.getTypeAtLocation(node);
135816                     var functionSignature = ts.singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */));
135817                     // If no function signature, maybe there was an error, do nothing
135818                     if (!functionSignature)
135819                         return { variableType: variableType, initializer: initializer };
135820                     // If the function signature has generic type parameters we don't attempt to move the parameters
135821                     if (!!functionSignature.getTypeParameters())
135822                         return { variableType: variableType, initializer: initializer };
135823                     // We add parameter types if needed
135824                     var parameters = [];
135825                     var hasAny = false;
135826                     for (var _i = 0, _a = initializer.parameters; _i < _a.length; _i++) {
135827                         var p = _a[_i];
135828                         if (p.type) {
135829                             parameters.push(p);
135830                         }
135831                         else {
135832                             var paramType = checker.getTypeAtLocation(p);
135833                             if (paramType === checker.getAnyType())
135834                                 hasAny = true;
135835                             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));
135836                         }
135837                     }
135838                     // If a parameter was inferred as any we skip adding function parameters at all.
135839                     // Turning an implicit any (which under common settings is a error) to an explicit
135840                     // is probably actually a worse refactor outcome.
135841                     if (hasAny)
135842                         return { variableType: variableType, initializer: initializer };
135843                     variableType = undefined;
135844                     if (ts.isArrowFunction(initializer)) {
135845                         initializer = ts.updateArrowFunction(initializer, node.modifiers, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer.equalsGreaterThanToken, initializer.body);
135846                     }
135847                     else {
135848                         if (functionSignature && !!functionSignature.thisParameter) {
135849                             var firstParameter = ts.firstOrUndefined(parameters);
135850                             // If the function signature has a this parameter and if the first defined parameter is not the this parameter, we must add it
135851                             // Note: If this parameter was already there, it would have been previously updated with the type if not type was present
135852                             if ((!firstParameter || (ts.isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) {
135853                                 var thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node);
135854                                 parameters.splice(0, 0, ts.createParameter(
135855                                 /* decorators */ undefined, 
135856                                 /* modifiers */ undefined, 
135857                                 /* dotDotDotToken */ undefined, "this", 
135858                                 /* questionToken */ undefined, checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */)));
135859                             }
135860                         }
135861                         initializer = ts.updateFunctionExpression(initializer, node.modifiers, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer.body);
135862                     }
135863                     return { variableType: variableType, initializer: initializer };
135864                 }
135865             }
135866             function getContainingVariableDeclarationIfInList(node, scope) {
135867                 var prevNode;
135868                 while (node !== undefined && node !== scope) {
135869                     if (ts.isVariableDeclaration(node) &&
135870                         node.initializer === prevNode &&
135871                         ts.isVariableDeclarationList(node.parent) &&
135872                         node.parent.declarations.length > 1) {
135873                         return node;
135874                     }
135875                     prevNode = node;
135876                     node = node.parent;
135877                 }
135878             }
135879             function getFirstDeclaration(type) {
135880                 var firstDeclaration;
135881                 var symbol = type.symbol;
135882                 if (symbol && symbol.declarations) {
135883                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
135884                         var declaration = _a[_i];
135885                         if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) {
135886                             firstDeclaration = declaration;
135887                         }
135888                     }
135889                 }
135890                 return firstDeclaration;
135891             }
135892             function compareTypesByDeclarationOrder(_a, _b) {
135893                 var type1 = _a.type, declaration1 = _a.declaration;
135894                 var type2 = _b.type, declaration2 = _b.declaration;
135895                 return ts.compareProperties(declaration1, declaration2, "pos", ts.compareValues)
135896                     || ts.compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "")
135897                     || ts.compareValues(type1.id, type2.id);
135898             }
135899             function getCalledExpression(scope, range, functionNameText) {
135900                 var functionReference = ts.createIdentifier(functionNameText);
135901                 if (ts.isClassLike(scope)) {
135902                     var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217
135903                     return ts.createPropertyAccess(lhs, functionReference);
135904                 }
135905                 else {
135906                     return functionReference;
135907                 }
135908             }
135909             function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn) {
135910                 var hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0;
135911                 if (ts.isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
135912                     // already block, no declarations or writes to propagate back, no substitutions - can use node as is
135913                     return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined };
135914                 }
135915                 var returnValueProperty;
135916                 var ignoreReturns = false;
135917                 var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]);
135918                 // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions
135919                 if (hasWritesOrVariableDeclarations || substitutions.size) {
135920                     var rewrittenStatements = ts.visitNodes(statements, visitor).slice();
135921                     if (hasWritesOrVariableDeclarations && !hasReturn && ts.isStatement(body)) {
135922                         // add return at the end to propagate writes back in case if control flow falls out of the function body
135923                         // it is ok to know that range has at least one return since it we only allow unconditional returns
135924                         var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
135925                         if (assignments.length === 1) {
135926                             rewrittenStatements.push(ts.createReturn(assignments[0].name));
135927                         }
135928                         else {
135929                             rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments)));
135930                         }
135931                     }
135932                     return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty };
135933                 }
135934                 else {
135935                     return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined };
135936                 }
135937                 function visitor(node) {
135938                     if (!ignoreReturns && node.kind === 235 /* ReturnStatement */ && hasWritesOrVariableDeclarations) {
135939                         var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
135940                         if (node.expression) {
135941                             if (!returnValueProperty) {
135942                                 returnValueProperty = "__return";
135943                             }
135944                             assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor)));
135945                         }
135946                         if (assignments.length === 1) {
135947                             return ts.createReturn(assignments[0].name);
135948                         }
135949                         else {
135950                             return ts.createReturn(ts.createObjectLiteral(assignments));
135951                         }
135952                     }
135953                     else {
135954                         var oldIgnoreReturns = ignoreReturns;
135955                         ignoreReturns = ignoreReturns || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node);
135956                         var substitution = substitutions.get(ts.getNodeId(node).toString());
135957                         var result = substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
135958                         ignoreReturns = oldIgnoreReturns;
135959                         return result;
135960                     }
135961                 }
135962             }
135963             function transformConstantInitializer(initializer, substitutions) {
135964                 return substitutions.size
135965                     ? visitor(initializer)
135966                     : initializer;
135967                 function visitor(node) {
135968                     var substitution = substitutions.get(ts.getNodeId(node).toString());
135969                     return substitution ? ts.getSynthesizedDeepClone(substitution) : ts.visitEachChild(node, visitor, ts.nullTransformationContext);
135970                 }
135971             }
135972             function getStatementsOrClassElements(scope) {
135973                 if (ts.isFunctionLikeDeclaration(scope)) {
135974                     var body = scope.body; // TODO: GH#18217
135975                     if (ts.isBlock(body)) {
135976                         return body.statements;
135977                     }
135978                 }
135979                 else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) {
135980                     return scope.statements;
135981                 }
135982                 else if (ts.isClassLike(scope)) {
135983                     return scope.members;
135984                 }
135985                 else {
135986                     ts.assertType(scope);
135987                 }
135988                 return ts.emptyArray;
135989             }
135990             /**
135991              * If `scope` contains a function after `minPos`, then return the first such function.
135992              * Otherwise, return `undefined`.
135993              */
135994             function getNodeToInsertFunctionBefore(minPos, scope) {
135995                 return ts.find(getStatementsOrClassElements(scope), function (child) {
135996                     return child.pos >= minPos && ts.isFunctionLikeDeclaration(child) && !ts.isConstructorDeclaration(child);
135997                 });
135998             }
135999             function getNodeToInsertPropertyBefore(maxPos, scope) {
136000                 var members = scope.members;
136001                 ts.Debug.assert(members.length > 0, "Found no members"); // There must be at least one child, since we extracted from one.
136002                 var prevMember;
136003                 var allProperties = true;
136004                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
136005                     var member = members_1[_i];
136006                     if (member.pos > maxPos) {
136007                         return prevMember || members[0];
136008                     }
136009                     if (allProperties && !ts.isPropertyDeclaration(member)) {
136010                         // If it is non-vacuously true that all preceding members are properties,
136011                         // insert before the current member (i.e. at the end of the list of properties).
136012                         if (prevMember !== undefined) {
136013                             return member;
136014                         }
136015                         allProperties = false;
136016                     }
136017                     prevMember = member;
136018                 }
136019                 if (prevMember === undefined)
136020                     return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember.
136021                 return prevMember;
136022             }
136023             function getNodeToInsertConstantBefore(node, scope) {
136024                 ts.Debug.assert(!ts.isClassLike(scope));
136025                 var prevScope;
136026                 for (var curr = node; curr !== scope; curr = curr.parent) {
136027                     if (isScope(curr)) {
136028                         prevScope = curr;
136029                     }
136030                 }
136031                 for (var curr = (prevScope || node).parent;; curr = curr.parent) {
136032                     if (isBlockLike(curr)) {
136033                         var prevStatement = void 0;
136034                         for (var _i = 0, _a = curr.statements; _i < _a.length; _i++) {
136035                             var statement = _a[_i];
136036                             if (statement.pos > node.pos) {
136037                                 break;
136038                             }
136039                             prevStatement = statement;
136040                         }
136041                         if (!prevStatement && ts.isCaseClause(curr)) {
136042                             // We must have been in the expression of the case clause.
136043                             ts.Debug.assert(ts.isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement");
136044                             return curr.parent.parent;
136045                         }
136046                         // There must be at least one statement since we started in one.
136047                         return ts.Debug.checkDefined(prevStatement, "prevStatement failed to get set");
136048                     }
136049                     ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
136050                 }
136051             }
136052             function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
136053                 var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); });
136054                 var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); });
136055                 // TODO: GH#18217 `variableAssignments` not possibly undefined!
136056                 return variableAssignments === undefined
136057                     ? writeAssignments
136058                     : writeAssignments === undefined
136059                         ? variableAssignments
136060                         : variableAssignments.concat(writeAssignments);
136061             }
136062             function isReadonlyArray(v) {
136063                 return ts.isArray(v);
136064             }
136065             /**
136066              * Produces a range that spans the entirety of nodes, given a selection
136067              * that might start/end in the middle of nodes.
136068              *
136069              * For example, when the user makes a selection like this
136070              *                     v---v
136071              *   var someThing = foo + bar;
136072              *  this returns     ^-------^
136073              */
136074             function getEnclosingTextRange(targetRange, sourceFile) {
136075                 return isReadonlyArray(targetRange.range)
136076                     ? { pos: ts.first(targetRange.range).getStart(sourceFile), end: ts.last(targetRange.range).getEnd() }
136077                     : targetRange.range;
136078             }
136079             var Usage;
136080             (function (Usage) {
136081                 // value should be passed to extracted method
136082                 Usage[Usage["Read"] = 1] = "Read";
136083                 // value should be passed to extracted method and propagated back
136084                 Usage[Usage["Write"] = 2] = "Write";
136085             })(Usage || (Usage = {}));
136086             function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) {
136087                 var allTypeParameterUsages = ts.createMap(); // Key is type ID
136088                 var usagesPerScope = [];
136089                 var substitutionsPerScope = [];
136090                 var functionErrorsPerScope = [];
136091                 var constantErrorsPerScope = [];
136092                 var visibleDeclarationsInExtractedRange = [];
136093                 var exposedVariableSymbolSet = ts.createMap(); // Key is symbol ID
136094                 var exposedVariableDeclarations = [];
136095                 var firstExposedNonVariableDeclaration;
136096                 var expression = !isReadonlyArray(targetRange.range)
136097                     ? targetRange.range
136098                     : targetRange.range.length === 1 && ts.isExpressionStatement(targetRange.range[0])
136099                         ? targetRange.range[0].expression
136100                         : undefined;
136101                 var expressionDiagnostic;
136102                 if (expression === undefined) {
136103                     var statements = targetRange.range;
136104                     var start = ts.first(statements).getStart();
136105                     var end = ts.last(statements).end;
136106                     expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected);
136107                 }
136108                 else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) {
136109                     expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType);
136110                 }
136111                 // initialize results
136112                 for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) {
136113                     var scope = scopes_1[_i];
136114                     usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() });
136115                     substitutionsPerScope.push(ts.createMap());
136116                     functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 244 /* FunctionDeclaration */
136117                         ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)]
136118                         : []);
136119                     var constantErrors = [];
136120                     if (expressionDiagnostic) {
136121                         constantErrors.push(expressionDiagnostic);
136122                     }
136123                     if (ts.isClassLike(scope) && ts.isInJSFile(scope)) {
136124                         constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
136125                     }
136126                     if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) {
136127                         // TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this
136128                         constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
136129                     }
136130                     constantErrorsPerScope.push(constantErrors);
136131                 }
136132                 var seenUsages = ts.createMap();
136133                 var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range;
136134                 var unmodifiedNode = isReadonlyArray(targetRange.range) ? ts.first(targetRange.range) : targetRange.range;
136135                 var inGenericContext = isInGenericContext(unmodifiedNode);
136136                 collectUsages(target);
136137                 // Unfortunately, this code takes advantage of the knowledge that the generated method
136138                 // will use the contextual type of an expression as the return type of the extracted
136139                 // method (and will therefore "use" all the types involved).
136140                 if (inGenericContext && !isReadonlyArray(targetRange.range)) {
136141                     var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217
136142                     recordTypeParameterUsages(contextualType);
136143                 }
136144                 if (allTypeParameterUsages.size > 0) {
136145                     var seenTypeParameterUsages = ts.createMap(); // Key is type ID
136146                     var i_1 = 0;
136147                     for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) {
136148                         if (curr === scopes[i_1]) {
136149                             // Copy current contents of seenTypeParameterUsages into scope.
136150                             seenTypeParameterUsages.forEach(function (typeParameter, id) {
136151                                 usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter);
136152                             });
136153                             i_1++;
136154                         }
136155                         // Note that we add the current node's type parameters *after* updating the corresponding scope.
136156                         if (ts.isDeclarationWithTypeParameters(curr)) {
136157                             for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
136158                                 var typeParameterDecl = _b[_a];
136159                                 var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
136160                                 if (allTypeParameterUsages.has(typeParameter.id.toString())) {
136161                                     seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter);
136162                                 }
136163                             }
136164                         }
136165                     }
136166                     // If we didn't get through all the scopes, then there were some that weren't in our
136167                     // parent chain (impossible at time of writing).  A conservative solution would be to
136168                     // copy allTypeParameterUsages into all remaining scopes.
136169                     ts.Debug.assert(i_1 === scopes.length, "Should have iterated all scopes");
136170                 }
136171                 // If there are any declarations in the extracted block that are used in the same enclosing
136172                 // lexical scope, we can't move the extraction "up" as those declarations will become unreachable
136173                 if (visibleDeclarationsInExtractedRange.length) {
136174                     var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent)
136175                         ? scopes[0]
136176                         : ts.getEnclosingBlockScopeContainer(scopes[0]);
136177                     ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
136178                 }
136179                 var _loop_16 = function (i) {
136180                     var scopeUsages = usagesPerScope[i];
136181                     // Special case: in the innermost scope, all usages are available.
136182                     // (The computed value reflects the value at the top-level of the scope, but the
136183                     // local will actually be declared at the same level as the extracted expression).
136184                     if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
136185                         var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
136186                         constantErrorsPerScope[i].push(ts.createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
136187                     }
136188                     var hasWrite = false;
136189                     var readonlyClassPropertyWrite;
136190                     usagesPerScope[i].usages.forEach(function (value) {
136191                         if (value.usage === 2 /* Write */) {
136192                             hasWrite = true;
136193                             if (value.symbol.flags & 106500 /* ClassMember */ &&
136194                                 value.symbol.valueDeclaration &&
136195                                 ts.hasModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) {
136196                                 readonlyClassPropertyWrite = value.symbol.valueDeclaration;
136197                             }
136198                         }
136199                     });
136200                     // If an expression was extracted, then there shouldn't have been any variable declarations.
136201                     ts.Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted");
136202                     if (hasWrite && !isReadonlyArray(targetRange.range)) {
136203                         var diag = ts.createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
136204                         functionErrorsPerScope[i].push(diag);
136205                         constantErrorsPerScope[i].push(diag);
136206                     }
136207                     else if (readonlyClassPropertyWrite && i > 0) {
136208                         var diag = ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
136209                         functionErrorsPerScope[i].push(diag);
136210                         constantErrorsPerScope[i].push(diag);
136211                     }
136212                     else if (firstExposedNonVariableDeclaration) {
136213                         var diag = ts.createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
136214                         functionErrorsPerScope[i].push(diag);
136215                         constantErrorsPerScope[i].push(diag);
136216                     }
136217                 };
136218                 for (var i = 0; i < scopes.length; i++) {
136219                     _loop_16(i);
136220                 }
136221                 return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
136222                 function isInGenericContext(node) {
136223                     return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
136224                 }
136225                 function recordTypeParameterUsages(type) {
136226                     // PERF: This is potentially very expensive.  `type` could be a library type with
136227                     // a lot of properties, each of which the walker will visit.  Unfortunately, the
136228                     // solution isn't as trivial as filtering to user types because of (e.g.) Array.
136229                     var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); });
136230                     var visitedTypes = symbolWalker.walkType(type).visitedTypes;
136231                     for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) {
136232                         var visitedType = visitedTypes_1[_i];
136233                         if (visitedType.isTypeParameter()) {
136234                             allTypeParameterUsages.set(visitedType.id.toString(), visitedType);
136235                         }
136236                     }
136237                 }
136238                 function collectUsages(node, valueUsage) {
136239                     if (valueUsage === void 0) { valueUsage = 1 /* Read */; }
136240                     if (inGenericContext) {
136241                         var type = checker.getTypeAtLocation(node);
136242                         recordTypeParameterUsages(type);
136243                     }
136244                     if (ts.isDeclaration(node) && node.symbol) {
136245                         visibleDeclarationsInExtractedRange.push(node);
136246                     }
136247                     if (ts.isAssignmentExpression(node)) {
136248                         // use 'write' as default usage for values
136249                         collectUsages(node.left, 2 /* Write */);
136250                         collectUsages(node.right);
136251                     }
136252                     else if (ts.isUnaryExpressionWithWrite(node)) {
136253                         collectUsages(node.operand, 2 /* Write */);
136254                     }
136255                     else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
136256                         // use 'write' as default usage for values
136257                         ts.forEachChild(node, collectUsages);
136258                     }
136259                     else if (ts.isIdentifier(node)) {
136260                         if (!node.parent) {
136261                             return;
136262                         }
136263                         if (ts.isQualifiedName(node.parent) && node !== node.parent.left) {
136264                             return;
136265                         }
136266                         if (ts.isPropertyAccessExpression(node.parent) && node !== node.parent.expression) {
136267                             return;
136268                         }
136269                         recordUsage(node, valueUsage, /*isTypeNode*/ ts.isPartOfTypeNode(node));
136270                     }
136271                     else {
136272                         ts.forEachChild(node, collectUsages);
136273                     }
136274                 }
136275                 function recordUsage(n, usage, isTypeNode) {
136276                     var symbolId = recordUsagebySymbol(n, usage, isTypeNode);
136277                     if (symbolId) {
136278                         for (var i = 0; i < scopes.length; i++) {
136279                             // push substitution from map<symbolId, subst> to map<nodeId, subst> to simplify rewriting
136280                             var substitution = substitutionsPerScope[i].get(symbolId);
136281                             if (substitution) {
136282                                 usagesPerScope[i].substitutions.set(ts.getNodeId(n).toString(), substitution);
136283                             }
136284                         }
136285                     }
136286                 }
136287                 function recordUsagebySymbol(identifier, usage, isTypeName) {
136288                     var symbol = getSymbolReferencedByIdentifier(identifier);
136289                     if (!symbol) {
136290                         // cannot find symbol - do nothing
136291                         return undefined;
136292                     }
136293                     var symbolId = ts.getSymbolId(symbol).toString();
136294                     var lastUsage = seenUsages.get(symbolId);
136295                     // there are two kinds of value usages
136296                     // - reads - if range contains a read from the value located outside of the range then value should be passed as a parameter
136297                     // - writes - if range contains a write to a value located outside the range the value should be passed as a parameter and
136298                     //   returned as a return value
136299                     // 'write' case is a superset of 'read' so if we already have processed 'write' of some symbol there is not need to handle 'read'
136300                     // since all information is already recorded
136301                     if (lastUsage && lastUsage >= usage) {
136302                         return symbolId;
136303                     }
136304                     seenUsages.set(symbolId, usage);
136305                     if (lastUsage) {
136306                         // if we get here this means that we are trying to handle 'write' and 'read' was already processed
136307                         // walk scopes and update existing records.
136308                         for (var _i = 0, usagesPerScope_1 = usagesPerScope; _i < usagesPerScope_1.length; _i++) {
136309                             var perScope = usagesPerScope_1[_i];
136310                             var prevEntry = perScope.usages.get(identifier.text);
136311                             if (prevEntry) {
136312                                 perScope.usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
136313                             }
136314                         }
136315                         return symbolId;
136316                     }
136317                     // find first declaration in this file
136318                     var decls = symbol.getDeclarations();
136319                     var declInFile = decls && ts.find(decls, function (d) { return d.getSourceFile() === sourceFile; });
136320                     if (!declInFile) {
136321                         return undefined;
136322                     }
136323                     if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) {
136324                         // declaration is located in range to be extracted - do nothing
136325                         return undefined;
136326                     }
136327                     if (targetRange.facts & RangeFacts.IsGenerator && usage === 2 /* Write */) {
136328                         // this is write to a reference located outside of the target scope and range is extracted into generator
136329                         // currently this is unsupported scenario
136330                         var diag = ts.createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
136331                         for (var _a = 0, functionErrorsPerScope_1 = functionErrorsPerScope; _a < functionErrorsPerScope_1.length; _a++) {
136332                             var errors = functionErrorsPerScope_1[_a];
136333                             errors.push(diag);
136334                         }
136335                         for (var _b = 0, constantErrorsPerScope_1 = constantErrorsPerScope; _b < constantErrorsPerScope_1.length; _b++) {
136336                             var errors = constantErrorsPerScope_1[_b];
136337                             errors.push(diag);
136338                         }
136339                     }
136340                     for (var i = 0; i < scopes.length; i++) {
136341                         var scope = scopes[i];
136342                         var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false);
136343                         if (resolvedSymbol === symbol) {
136344                             continue;
136345                         }
136346                         if (!substitutionsPerScope[i].has(symbolId)) {
136347                             var substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName);
136348                             if (substitution) {
136349                                 substitutionsPerScope[i].set(symbolId, substitution);
136350                             }
136351                             else if (isTypeName) {
136352                                 // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument
136353                                 // so there's no problem.
136354                                 if (!(symbol.flags & 262144 /* TypeParameter */)) {
136355                                     var diag = ts.createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
136356                                     functionErrorsPerScope[i].push(diag);
136357                                     constantErrorsPerScope[i].push(diag);
136358                                 }
136359                             }
136360                             else {
136361                                 usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier });
136362                             }
136363                         }
136364                     }
136365                     return symbolId;
136366                 }
136367                 function checkForUsedDeclarations(node) {
136368                     // If this node is entirely within the original extraction range, we don't need to do anything.
136369                     if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0)) {
136370                         return;
136371                     }
136372                     // Otherwise check and recurse.
136373                     var sym = ts.isIdentifier(node)
136374                         ? getSymbolReferencedByIdentifier(node)
136375                         : checker.getSymbolAtLocation(node);
136376                     if (sym) {
136377                         var decl = ts.find(visibleDeclarationsInExtractedRange, function (d) { return d.symbol === sym; });
136378                         if (decl) {
136379                             if (ts.isVariableDeclaration(decl)) {
136380                                 var idString = decl.symbol.id.toString();
136381                                 if (!exposedVariableSymbolSet.has(idString)) {
136382                                     exposedVariableDeclarations.push(decl);
136383                                     exposedVariableSymbolSet.set(idString, true);
136384                                 }
136385                             }
136386                             else {
136387                                 // CONSIDER: this includes binding elements, which we could
136388                                 // expose in the same way as variables.
136389                                 firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl;
136390                             }
136391                         }
136392                     }
136393                     ts.forEachChild(node, checkForUsedDeclarations);
136394                 }
136395                 /**
136396                  * Return the symbol referenced by an identifier (even if it declares a different symbol).
136397                  */
136398                 function getSymbolReferencedByIdentifier(identifier) {
136399                     // If the identifier is both a property name and its value, we're only interested in its value
136400                     // (since the name is a declaration and will be included in the extracted range).
136401                     return identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier
136402                         ? checker.getShorthandAssignmentValueSymbol(identifier.parent)
136403                         : checker.getSymbolAtLocation(identifier);
136404                 }
136405                 function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode) {
136406                     if (!symbol) {
136407                         return undefined;
136408                     }
136409                     var decls = symbol.getDeclarations();
136410                     if (decls && decls.some(function (d) { return d.parent === scopeDecl; })) {
136411                         return ts.createIdentifier(symbol.name);
136412                     }
136413                     var prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode);
136414                     if (prefix === undefined) {
136415                         return undefined;
136416                     }
136417                     return isTypeNode
136418                         ? ts.createQualifiedName(prefix, ts.createIdentifier(symbol.name))
136419                         : ts.createPropertyAccess(prefix, symbol.name);
136420                 }
136421             }
136422             /**
136423              * Computes whether or not a node represents an expression in a position where it could
136424              * be extracted.
136425              * The isExpression() in utilities.ts returns some false positives we need to handle,
136426              * such as `import x from 'y'` -- the 'y' is a StringLiteral but is *not* an expression
136427              * in the sense of something that you could extract on
136428              */
136429             function isExtractableExpression(node) {
136430                 var parent = node.parent;
136431                 switch (parent.kind) {
136432                     case 284 /* EnumMember */:
136433                         return false;
136434                 }
136435                 switch (node.kind) {
136436                     case 10 /* StringLiteral */:
136437                         return parent.kind !== 254 /* ImportDeclaration */ &&
136438                             parent.kind !== 258 /* ImportSpecifier */;
136439                     case 213 /* SpreadElement */:
136440                     case 189 /* ObjectBindingPattern */:
136441                     case 191 /* BindingElement */:
136442                         return false;
136443                     case 75 /* Identifier */:
136444                         return parent.kind !== 191 /* BindingElement */ &&
136445                             parent.kind !== 258 /* ImportSpecifier */ &&
136446                             parent.kind !== 263 /* ExportSpecifier */;
136447                 }
136448                 return true;
136449             }
136450             function isBlockLike(node) {
136451                 switch (node.kind) {
136452                     case 223 /* Block */:
136453                     case 290 /* SourceFile */:
136454                     case 250 /* ModuleBlock */:
136455                     case 277 /* CaseClause */:
136456                         return true;
136457                     default:
136458                         return false;
136459                 }
136460             }
136461         })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {}));
136462     })(refactor = ts.refactor || (ts.refactor = {}));
136463 })(ts || (ts = {}));
136464 /* @internal */
136465 var ts;
136466 (function (ts) {
136467     var refactor;
136468     (function (refactor) {
136469         var refactorName = "Extract type";
136470         var extractToTypeAlias = "Extract to type alias";
136471         var extractToInterface = "Extract to interface";
136472         var extractToTypeDef = "Extract to typedef";
136473         refactor.registerRefactor(refactorName, {
136474             getAvailableActions: function (context) {
136475                 var info = getRangeToExtract(context);
136476                 if (!info)
136477                     return ts.emptyArray;
136478                 return [{
136479                         name: refactorName,
136480                         description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_type),
136481                         actions: info.isJS ? [{
136482                                 name: extractToTypeDef, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_typedef)
136483                             }] : ts.append([{
136484                                 name: extractToTypeAlias, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_type_alias)
136485                             }], info.typeElements && {
136486                             name: extractToInterface, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_to_interface)
136487                         })
136488                     }];
136489             },
136490             getEditsForAction: function (context, actionName) {
136491                 var file = context.file;
136492                 var info = ts.Debug.checkDefined(getRangeToExtract(context), "Expected to find a range to extract");
136493                 var name = ts.getUniqueName("NewType", file);
136494                 var edits = ts.textChanges.ChangeTracker.with(context, function (changes) {
136495                     switch (actionName) {
136496                         case extractToTypeAlias:
136497                             ts.Debug.assert(!info.isJS, "Invalid actionName/JS combo");
136498                             return doTypeAliasChange(changes, file, name, info);
136499                         case extractToTypeDef:
136500                             ts.Debug.assert(info.isJS, "Invalid actionName/JS combo");
136501                             return doTypedefChange(changes, file, name, info);
136502                         case extractToInterface:
136503                             ts.Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo");
136504                             return doInterfaceChange(changes, file, name, info);
136505                         default:
136506                             ts.Debug.fail("Unexpected action name");
136507                     }
136508                 });
136509                 var renameFilename = file.fileName;
136510                 var renameLocation = ts.getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ false);
136511                 return { edits: edits, renameFilename: renameFilename, renameLocation: renameLocation };
136512             }
136513         });
136514         function getRangeToExtract(context) {
136515             var file = context.file, startPosition = context.startPosition;
136516             var isJS = ts.isSourceFileJS(file);
136517             var current = ts.getTokenAtPosition(file, startPosition);
136518             var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
136519             var selection = ts.findAncestor(current, (function (node) { return node.parent && rangeContainsSkipTrivia(range, node, file) && !rangeContainsSkipTrivia(range, node.parent, file); }));
136520             if (!selection || !ts.isTypeNode(selection))
136521                 return undefined;
136522             var checker = context.program.getTypeChecker();
136523             var firstStatement = ts.Debug.checkDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement");
136524             var typeParameters = collectTypeParameters(checker, selection, firstStatement, file);
136525             if (!typeParameters)
136526                 return undefined;
136527             var typeElements = flattenTypeLiteralNodeReference(checker, selection);
136528             return { isJS: isJS, selection: selection, firstStatement: firstStatement, typeParameters: typeParameters, typeElements: typeElements };
136529         }
136530         function flattenTypeLiteralNodeReference(checker, node) {
136531             if (!node)
136532                 return undefined;
136533             if (ts.isIntersectionTypeNode(node)) {
136534                 var result = [];
136535                 var seen_1 = ts.createMap();
136536                 for (var _i = 0, _a = node.types; _i < _a.length; _i++) {
136537                     var type = _a[_i];
136538                     var flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type);
136539                     if (!flattenedTypeMembers || !flattenedTypeMembers.every(function (type) { return type.name && ts.addToSeen(seen_1, ts.getNameFromPropertyName(type.name)); })) {
136540                         return undefined;
136541                     }
136542                     ts.addRange(result, flattenedTypeMembers);
136543                 }
136544                 return result;
136545             }
136546             else if (ts.isParenthesizedTypeNode(node)) {
136547                 return flattenTypeLiteralNodeReference(checker, node.type);
136548             }
136549             else if (ts.isTypeLiteralNode(node)) {
136550                 return node.members;
136551             }
136552             return undefined;
136553         }
136554         function rangeContainsSkipTrivia(r1, node, file) {
136555             return ts.rangeContainsStartEnd(r1, ts.skipTrivia(file.text, node.pos), node.end);
136556         }
136557         function collectTypeParameters(checker, selection, statement, file) {
136558             var result = [];
136559             return visitor(selection) ? undefined : result;
136560             function visitor(node) {
136561                 if (ts.isTypeReferenceNode(node)) {
136562                     if (ts.isIdentifier(node.typeName)) {
136563                         var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true);
136564                         if (symbol) {
136565                             var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration);
136566                             if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) {
136567                                 result.push(declaration);
136568                             }
136569                         }
136570                     }
136571                 }
136572                 else if (ts.isInferTypeNode(node)) {
136573                     var conditionalTypeNode = ts.findAncestor(node, function (n) { return ts.isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file); });
136574                     if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) {
136575                         return true;
136576                     }
136577                 }
136578                 else if ((ts.isTypePredicateNode(node) || ts.isThisTypeNode(node))) {
136579                     var functionLikeNode = ts.findAncestor(node.parent, ts.isFunctionLike);
136580                     if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) {
136581                         return true;
136582                     }
136583                 }
136584                 else if (ts.isTypeQueryNode(node)) {
136585                     if (ts.isIdentifier(node.exprName)) {
136586                         var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false);
136587                         if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) {
136588                             return true;
136589                         }
136590                     }
136591                     else {
136592                         if (ts.isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) {
136593                             return true;
136594                         }
136595                     }
136596                 }
136597                 return ts.forEachChild(node, visitor);
136598             }
136599         }
136600         function doTypeAliasChange(changes, file, name, info) {
136601             var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters;
136602             var newTypeNode = ts.createTypeAliasDeclaration(
136603             /* decorators */ undefined, 
136604             /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.updateTypeParameterDeclaration(id, id.name, id.constraint, /* defaultType */ undefined); }), selection);
136605             changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true);
136606             changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
136607         }
136608         function doInterfaceChange(changes, file, name, info) {
136609             var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters, typeElements = info.typeElements;
136610             var newTypeNode = ts.createInterfaceDeclaration(
136611             /* decorators */ undefined, 
136612             /* modifiers */ undefined, name, typeParameters, 
136613             /* heritageClauses */ undefined, typeElements);
136614             changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true);
136615             changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
136616         }
136617         function doTypedefChange(changes, file, name, info) {
136618             var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters;
136619             var node = ts.createNode(322 /* JSDocTypedefTag */);
136620             node.tagName = ts.createIdentifier("typedef"); // TODO: jsdoc factory https://github.com/Microsoft/TypeScript/pull/29539
136621             node.fullName = ts.createIdentifier(name);
136622             node.name = node.fullName;
136623             node.typeExpression = ts.createJSDocTypeExpression(selection);
136624             var templates = [];
136625             ts.forEach(typeParameters, function (typeParameter) {
136626                 var constraint = ts.getEffectiveConstraintOfTypeParameter(typeParameter);
136627                 var template = ts.createNode(321 /* JSDocTemplateTag */);
136628                 template.tagName = ts.createIdentifier("template");
136629                 template.constraint = constraint && ts.cast(constraint, ts.isJSDocTypeExpression);
136630                 var parameter = ts.createNode(155 /* TypeParameter */);
136631                 parameter.name = typeParameter.name;
136632                 template.typeParameters = ts.createNodeArray([parameter]);
136633                 templates.push(template);
136634             });
136635             changes.insertNodeBefore(file, firstStatement, ts.createJSDocComment(/* comment */ undefined, ts.createNodeArray(ts.concatenate(templates, [node]))), /* blankLineBetween */ true);
136636             changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); })));
136637         }
136638     })(refactor = ts.refactor || (ts.refactor = {}));
136639 })(ts || (ts = {}));
136640 /* @internal */
136641 var ts;
136642 (function (ts) {
136643     var refactor;
136644     (function (refactor) {
136645         var generateGetAccessorAndSetAccessor;
136646         (function (generateGetAccessorAndSetAccessor) {
136647             var actionName = "Generate 'get' and 'set' accessors";
136648             var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message;
136649             refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
136650             function getAvailableActions(context) {
136651                 if (!getConvertibleFieldAtPosition(context))
136652                     return ts.emptyArray;
136653                 return [{
136654                         name: actionName,
136655                         description: actionDescription,
136656                         actions: [
136657                             {
136658                                 name: actionName,
136659                                 description: actionDescription
136660                             }
136661                         ]
136662                     }];
136663             }
136664             function getEditsForAction(context, _actionName) {
136665                 var file = context.file;
136666                 var fieldInfo = getConvertibleFieldAtPosition(context);
136667                 if (!fieldInfo)
136668                     return undefined;
136669                 var isJS = ts.isSourceFileJS(file);
136670                 var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
136671                 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;
136672                 ts.suppressLeadingAndTrailingTrivia(fieldName);
136673                 ts.suppressLeadingAndTrailingTrivia(accessorName);
136674                 ts.suppressLeadingAndTrailingTrivia(declaration);
136675                 ts.suppressLeadingAndTrailingTrivia(container);
136676                 var isInClassLike = ts.isClassLike(container);
136677                 // avoid Readonly modifier because it will convert to get accessor
136678                 var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
136679                 var accessorModifiers = isInClassLike
136680                     ? !modifierFlags || modifierFlags & 8 /* Private */
136681                         ? getModifiers(isJS, isStatic, 119 /* PublicKeyword */)
136682                         : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
136683                     : undefined;
136684                 var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 117 /* PrivateKeyword */) : undefined;
136685                 updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
136686                 var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
136687                 ts.suppressLeadingAndTrailingTrivia(getAccessor);
136688                 insertAccessor(changeTracker, file, getAccessor, declaration, container);
136689                 if (isReadonly) {
136690                     // readonly modifier only existed in classLikeDeclaration
136691                     var constructor = ts.getFirstConstructorWithBody(container);
136692                     if (constructor) {
136693                         updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
136694                     }
136695                 }
136696                 else {
136697                     var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
136698                     ts.suppressLeadingAndTrailingTrivia(setAccessor);
136699                     insertAccessor(changeTracker, file, setAccessor, declaration, container);
136700                 }
136701                 var edits = changeTracker.getChanges();
136702                 var renameFilename = file.fileName;
136703                 var nameNeedRename = renameAccessor ? accessorName : fieldName;
136704                 var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
136705                 var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
136706                 return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
136707             }
136708             function isConvertibleName(name) {
136709                 return ts.isIdentifier(name) || ts.isStringLiteral(name);
136710             }
136711             function isAcceptedDeclaration(node) {
136712                 return ts.isParameterPropertyDeclaration(node, node.parent) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node);
136713             }
136714             function createPropertyName(name, originalName) {
136715                 return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name);
136716             }
136717             function createAccessorAccessExpression(fieldName, isStatic, container) {
136718                 var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217
136719                 return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName));
136720             }
136721             function getModifiers(isJS, isStatic, accessModifier) {
136722                 var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(120 /* StaticKeyword */) : undefined);
136723                 return modifiers && ts.createNodeArray(modifiers);
136724             }
136725             function getConvertibleFieldAtPosition(context) {
136726                 var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition;
136727                 var node = ts.getTokenAtPosition(file, startPosition);
136728                 var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
136729                 // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
136730                 var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
136731                 if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217
136732                     || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
136733                     return undefined;
136734                 var name = declaration.name.text;
136735                 var startWithUnderscore = ts.startsWithUnderscore(name);
136736                 var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name);
136737                 var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name);
136738                 return {
136739                     isStatic: ts.hasStaticModifier(declaration),
136740                     isReadonly: ts.hasReadonlyModifier(declaration),
136741                     type: ts.getTypeAnnotationNode(declaration),
136742                     container: declaration.kind === 156 /* Parameter */ ? declaration.parent.parent : declaration.parent,
136743                     originalName: declaration.name.text,
136744                     declaration: declaration,
136745                     fieldName: fieldName,
136746                     accessorName: accessorName,
136747                     renameAccessor: startWithUnderscore
136748                 };
136749             }
136750             function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
136751                 return ts.createGetAccessor(
136752                 /*decorators*/ undefined, modifiers, accessorName, 
136753                 /*parameters*/ undefined, // TODO: GH#18217
136754                 type, ts.createBlock([
136755                     ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container))
136756                 ], /*multiLine*/ true));
136757             }
136758             function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
136759                 return ts.createSetAccessor(
136760                 /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter(
136761                     /*decorators*/ undefined, 
136762                     /*modifiers*/ undefined, 
136763                     /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), 
136764                     /*questionToken*/ undefined, type)], ts.createBlock([
136765                     ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value")))
136766                 ], /*multiLine*/ true));
136767             }
136768             function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
136769                 var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
136770                 changeTracker.replaceNode(file, declaration, property);
136771             }
136772             function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
136773                 var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
136774                 changeTracker.replacePropertyAssignment(file, declaration, assignment);
136775             }
136776             function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
136777                 if (ts.isPropertyDeclaration(declaration)) {
136778                     updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
136779                 }
136780                 else if (ts.isPropertyAssignment(declaration)) {
136781                     updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
136782                 }
136783                 else {
136784                     changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
136785                 }
136786             }
136787             function insertAccessor(changeTracker, file, accessor, declaration, container) {
136788                 ts.isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertNodeAtClassStart(file, container, accessor) :
136789                     ts.isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) :
136790                         changeTracker.insertNodeAfter(file, declaration, accessor);
136791             }
136792             function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) {
136793                 if (!constructor.body)
136794                     return;
136795                 constructor.body.forEachChild(function recur(node) {
136796                     if (ts.isElementAccessExpression(node) &&
136797                         node.expression.kind === 104 /* ThisKeyword */ &&
136798                         ts.isStringLiteral(node.argumentExpression) &&
136799                         node.argumentExpression.text === originalName &&
136800                         ts.isWriteAccess(node)) {
136801                         changeTracker.replaceNode(file, node.argumentExpression, ts.createStringLiteral(fieldName));
136802                     }
136803                     if (ts.isPropertyAccessExpression(node) && node.expression.kind === 104 /* ThisKeyword */ && node.name.text === originalName && ts.isWriteAccess(node)) {
136804                         changeTracker.replaceNode(file, node.name, ts.createIdentifier(fieldName));
136805                     }
136806                     if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) {
136807                         node.forEachChild(recur);
136808                     }
136809                 });
136810             }
136811         })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
136812     })(refactor = ts.refactor || (ts.refactor = {}));
136813 })(ts || (ts = {}));
136814 /* @internal */
136815 var ts;
136816 (function (ts) {
136817     var refactor;
136818     (function (refactor) {
136819         var refactorName = "Move to a new file";
136820         refactor.registerRefactor(refactorName, {
136821             getAvailableActions: function (context) {
136822                 if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
136823                     return ts.emptyArray;
136824                 var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
136825                 return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
136826             },
136827             getEditsForAction: function (context, actionName) {
136828                 ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked");
136829                 var statements = ts.Debug.checkDefined(getStatementsToMove(context));
136830                 var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); });
136831                 return { edits: edits, renameFilename: undefined, renameLocation: undefined };
136832             }
136833         });
136834         function getRangeToMove(context) {
136835             var file = context.file;
136836             var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
136837             var statements = file.statements;
136838             var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
136839             if (startNodeIndex === -1)
136840                 return undefined;
136841             var startStatement = statements[startNodeIndex];
136842             if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) {
136843                 return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] };
136844             }
136845             // Can't only partially include the start node or be partially into the next node
136846             if (range.pos > startStatement.getStart(file))
136847                 return undefined;
136848             var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
136849             // Can't be partially into the next node
136850             if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
136851                 return undefined;
136852             return {
136853                 toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex),
136854                 afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex],
136855             };
136856         }
136857         function doChange(oldFile, program, toMove, changes, host, preferences) {
136858             var checker = program.getTypeChecker();
136859             var usage = getUsageInfo(oldFile, toMove.all, checker);
136860             var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
136861             var extension = ts.extensionFromPath(oldFile.fileName);
136862             var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
136863             var newFileNameWithExtension = newModuleName + extension;
136864             // If previous file was global, this is easy.
136865             changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences));
136866             addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
136867         }
136868         // 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.
136869         function getStatementsToMove(context) {
136870             var rangeToMove = getRangeToMove(context);
136871             if (rangeToMove === undefined)
136872                 return undefined;
136873             var all = [];
136874             var ranges = [];
136875             var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast;
136876             ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) {
136877                 for (var i = start; i < afterEndIndex; i++)
136878                     all.push(toMove[i]);
136879                 ranges.push({ first: toMove[start], afterLast: afterLast });
136880             });
136881             return all.length === 0 ? undefined : { all: all, ranges: ranges };
136882         }
136883         function isPureImport(node) {
136884             switch (node.kind) {
136885                 case 254 /* ImportDeclaration */:
136886                     return true;
136887                 case 253 /* ImportEqualsDeclaration */:
136888                     return !ts.hasModifier(node, 1 /* Export */);
136889                 case 225 /* VariableStatement */:
136890                     return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
136891                 default:
136892                     return false;
136893             }
136894         }
136895         function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
136896             var cfg = program.getCompilerOptions().configFile;
136897             if (!cfg)
136898                 return;
136899             var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
136900             var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
136901             var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
136902             var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
136903                 return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
136904             });
136905             if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
136906                 changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
136907             }
136908         }
136909         function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) {
136910             var checker = program.getTypeChecker();
136911             if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
136912                 deleteMovedStatements(oldFile, toMove.ranges, changes);
136913                 return toMove.all;
136914             }
136915             var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
136916             var quotePreference = ts.getQuotePreference(oldFile, preferences);
136917             var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference);
136918             if (importsFromNewFile) {
136919                 ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true);
136920             }
136921             deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
136922             deleteMovedStatements(oldFile, toMove.ranges, changes);
136923             updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
136924             return __spreadArrays(getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference), addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
136925         }
136926         function deleteMovedStatements(sourceFile, moved, changes) {
136927             for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
136928                 var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast;
136929                 changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast);
136930             }
136931         }
136932         function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
136933             for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
136934                 var statement = _a[_i];
136935                 if (ts.contains(toMove, statement))
136936                     continue;
136937                 forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
136938             }
136939         }
136940         function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
136941             var checker = program.getTypeChecker();
136942             var _loop_17 = function (sourceFile) {
136943                 if (sourceFile === oldFile)
136944                     return "continue";
136945                 var _loop_18 = function (statement) {
136946                     forEachImportInStatement(statement, function (importNode) {
136947                         if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
136948                             return;
136949                         var shouldMove = function (name) {
136950                             var symbol = ts.isBindingElement(name.parent)
136951                                 ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
136952                                 : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217
136953                             return !!symbol && movedSymbols.has(symbol);
136954                         };
136955                         deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
136956                         var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
136957                         var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
136958                         if (newImportDeclaration)
136959                             changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
136960                         var ns = getNamespaceLikeImport(importNode);
136961                         if (ns)
136962                             updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode);
136963                     });
136964                 };
136965                 for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
136966                     var statement = _a[_i];
136967                     _loop_18(statement);
136968                 }
136969             };
136970             for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
136971                 var sourceFile = _a[_i];
136972                 _loop_17(sourceFile);
136973             }
136974         }
136975         function getNamespaceLikeImport(node) {
136976             switch (node.kind) {
136977                 case 254 /* ImportDeclaration */:
136978                     return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 256 /* NamespaceImport */ ?
136979                         node.importClause.namedBindings.name : undefined;
136980                 case 253 /* ImportEqualsDeclaration */:
136981                     return node.name;
136982                 case 242 /* VariableDeclaration */:
136983                     return ts.tryCast(node.name, ts.isIdentifier);
136984                 default:
136985                     return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind);
136986             }
136987         }
136988         function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
136989             var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 99 /* ESNext */);
136990             var needUniqueName = false;
136991             var toChange = [];
136992             ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
136993                 if (!ts.isPropertyAccessExpression(ref.parent))
136994                     return;
136995                 needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true);
136996                 if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) {
136997                     toChange.push(ref);
136998                 }
136999             });
137000             if (toChange.length) {
137001                 var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName;
137002                 for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) {
137003                     var ref = toChange_1[_i];
137004                     changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName));
137005                 }
137006                 changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier));
137007             }
137008         }
137009         function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) {
137010             var newNamespaceId = ts.createIdentifier(newNamespaceName);
137011             var newModuleString = ts.createLiteral(newModuleSpecifier);
137012             switch (node.kind) {
137013                 case 254 /* ImportDeclaration */:
137014                     return ts.createImportDeclaration(
137015                     /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString);
137016                 case 253 /* ImportEqualsDeclaration */:
137017                     return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString));
137018                 case 242 /* VariableDeclaration */:
137019                     return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString));
137020                 default:
137021                     return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind);
137022             }
137023         }
137024         function moduleSpecifierFromImport(i) {
137025             return (i.kind === 254 /* ImportDeclaration */ ? i.moduleSpecifier
137026                 : i.kind === 253 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
137027                     : i.initializer.arguments[0]);
137028         }
137029         function forEachImportInStatement(statement, cb) {
137030             if (ts.isImportDeclaration(statement)) {
137031                 if (ts.isStringLiteral(statement.moduleSpecifier))
137032                     cb(statement);
137033             }
137034             else if (ts.isImportEqualsDeclaration(statement)) {
137035                 if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
137036                     cb(statement);
137037                 }
137038             }
137039             else if (ts.isVariableStatement(statement)) {
137040                 for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
137041                     var decl = _a[_i];
137042                     if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
137043                         cb(decl);
137044                     }
137045                 }
137046             }
137047         }
137048         function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) {
137049             var defaultImport;
137050             var imports = [];
137051             newFileNeedExport.forEach(function (symbol) {
137052                 if (symbol.escapedName === "default" /* Default */) {
137053                     defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217
137054                 }
137055                 else {
137056                     imports.push(symbol.name);
137057                 }
137058             });
137059             return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference);
137060         }
137061         function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) {
137062             path = ts.ensurePathIsNonModuleName(path);
137063             if (useEs6Imports) {
137064                 var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
137065                 return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference);
137066             }
137067             else {
137068                 ts.Debug.assert(!defaultImport, "No default import should exist"); // If there's a default export, it should have been an es6 module.
137069                 var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
137070                 return bindingElements.length
137071                     ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
137072                     : undefined;
137073             }
137074         }
137075         function makeVariableStatement(name, type, initializer, flags) {
137076             if (flags === void 0) { flags = 2 /* Const */; }
137077             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
137078         }
137079         function createRequireCall(moduleSpecifier) {
137080             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
137081         }
137082         function addExports(sourceFile, toMove, needExport, useEs6Exports) {
137083             return ts.flatMap(toMove, function (statement) {
137084                 if (isTopLevelDeclarationStatement(statement) &&
137085                     !isExported(sourceFile, statement, useEs6Exports) &&
137086                     forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.checkDefined(d.symbol)); })) {
137087                     var exports = addExport(statement, useEs6Exports);
137088                     if (exports)
137089                         return exports;
137090                 }
137091                 return statement;
137092             });
137093         }
137094         function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
137095             switch (importDecl.kind) {
137096                 case 254 /* ImportDeclaration */:
137097                     deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
137098                     break;
137099                 case 253 /* ImportEqualsDeclaration */:
137100                     if (isUnused(importDecl.name)) {
137101                         changes.delete(sourceFile, importDecl);
137102                     }
137103                     break;
137104                 case 242 /* VariableDeclaration */:
137105                     deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
137106                     break;
137107                 default:
137108                     ts.Debug.assertNever(importDecl, "Unexpected import decl kind " + importDecl.kind);
137109             }
137110         }
137111         function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
137112             if (!importDecl.importClause)
137113                 return;
137114             var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
137115             var defaultUnused = !name || isUnused(name);
137116             var namedBindingsUnused = !namedBindings ||
137117                 (namedBindings.kind === 256 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); }));
137118             if (defaultUnused && namedBindingsUnused) {
137119                 changes.delete(sourceFile, importDecl);
137120             }
137121             else {
137122                 if (name && defaultUnused) {
137123                     changes.delete(sourceFile, name);
137124                 }
137125                 if (namedBindings) {
137126                     if (namedBindingsUnused) {
137127                         changes.replaceNode(sourceFile, importDecl.importClause, ts.updateImportClause(importDecl.importClause, name, /*namedBindings*/ undefined, importDecl.importClause.isTypeOnly));
137128                     }
137129                     else if (namedBindings.kind === 257 /* NamedImports */) {
137130                         for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
137131                             var element = _b[_i];
137132                             if (isUnused(element.name))
137133                                 changes.delete(sourceFile, element);
137134                         }
137135                     }
137136                 }
137137             }
137138         }
137139         function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
137140             var name = varDecl.name;
137141             switch (name.kind) {
137142                 case 75 /* Identifier */:
137143                     if (isUnused(name)) {
137144                         changes.delete(sourceFile, name);
137145                     }
137146                     break;
137147                 case 190 /* ArrayBindingPattern */:
137148                     break;
137149                 case 189 /* ObjectBindingPattern */:
137150                     if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
137151                         changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
137152                     }
137153                     else {
137154                         for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
137155                             var element = _a[_i];
137156                             if (ts.isIdentifier(element.name) && isUnused(element.name)) {
137157                                 changes.delete(sourceFile, element.name);
137158                             }
137159                         }
137160                     }
137161                     break;
137162             }
137163         }
137164         function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) {
137165             var copiedOldImports = [];
137166             for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
137167                 var oldStatement = _a[_i];
137168                 forEachImportInStatement(oldStatement, function (i) {
137169                     ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
137170                 });
137171             }
137172             // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
137173             var oldFileDefault;
137174             var oldFileNamedImports = [];
137175             var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
137176             newFileImportsFromOldFile.forEach(function (symbol) {
137177                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
137178                     var decl = _a[_i];
137179                     if (!isTopLevelDeclaration(decl))
137180                         continue;
137181                     var name = nameOfTopLevelDeclaration(decl);
137182                     if (!name)
137183                         continue;
137184                     var top = getTopLevelDeclarationStatement(decl);
137185                     if (markSeenTop(top)) {
137186                         addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
137187                     }
137188                     if (ts.hasModifier(decl, 512 /* Default */)) {
137189                         oldFileDefault = name;
137190                     }
137191                     else {
137192                         oldFileNamedImports.push(name.text);
137193                     }
137194                 }
137195             });
137196             ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference));
137197             return copiedOldImports;
137198         }
137199         function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
137200             var newModuleName = moduleName;
137201             for (var i = 1;; i++) {
137202                 var name = ts.combinePaths(inDirectory, newModuleName + extension);
137203                 if (!host.fileExists(name))
137204                     return newModuleName; // TODO: GH#18217
137205                 newModuleName = moduleName + "." + i;
137206             }
137207         }
137208         function getNewModuleName(movedSymbols) {
137209             return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
137210         }
137211         function getUsageInfo(oldFile, toMove, checker) {
137212             var movedSymbols = new SymbolSet();
137213             var oldImportsNeededByNewFile = new SymbolSet();
137214             var newFileImportsFromOldFile = new SymbolSet();
137215             var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
137216             var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
137217             if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
137218                 oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
137219             }
137220             for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
137221                 var statement = toMove_1[_i];
137222                 forEachTopLevelDeclaration(statement, function (decl) {
137223                     movedSymbols.add(ts.Debug.checkDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
137224                 });
137225             }
137226             for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
137227                 var statement = toMove_2[_a];
137228                 forEachReference(statement, checker, function (symbol) {
137229                     if (!symbol.declarations)
137230                         return;
137231                     for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
137232                         var decl = _a[_i];
137233                         if (isInImport(decl)) {
137234                             oldImportsNeededByNewFile.add(symbol);
137235                         }
137236                         else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) {
137237                             newFileImportsFromOldFile.add(symbol);
137238                         }
137239                     }
137240                 });
137241             }
137242             var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
137243             var oldFileImportsFromNewFile = new SymbolSet();
137244             for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
137245                 var statement = _c[_b];
137246                 if (ts.contains(toMove, statement))
137247                     continue;
137248                 // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
137249                 if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
137250                     unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
137251                 }
137252                 forEachReference(statement, checker, function (symbol) {
137253                     if (movedSymbols.has(symbol))
137254                         oldFileImportsFromNewFile.add(symbol);
137255                     unusedImportsFromOldFile.delete(symbol);
137256                 });
137257             }
137258             return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
137259             function getJsxNamespaceSymbol(containsJsx) {
137260                 if (containsJsx === undefined) {
137261                     return undefined;
137262                 }
137263                 var jsxNamespace = checker.getJsxNamespace(containsJsx);
137264                 // Strictly speaking, this could resolve to a symbol other than the JSX namespace.
137265                 // This will produce erroneous output (probably, an incorrectly copied import) but
137266                 // is expected to be very rare and easily reversible.
137267                 var jsxNamespaceSymbol = checker.resolveName(jsxNamespace, containsJsx, 1920 /* Namespace */, /*excludeGlobals*/ true);
137268                 return !!jsxNamespaceSymbol && ts.some(jsxNamespaceSymbol.declarations, isInImport)
137269                     ? jsxNamespaceSymbol
137270                     : undefined;
137271             }
137272         }
137273         // Below should all be utilities
137274         function isInImport(decl) {
137275             switch (decl.kind) {
137276                 case 253 /* ImportEqualsDeclaration */:
137277                 case 258 /* ImportSpecifier */:
137278                 case 255 /* ImportClause */:
137279                 case 256 /* NamespaceImport */:
137280                     return true;
137281                 case 242 /* VariableDeclaration */:
137282                     return isVariableDeclarationInImport(decl);
137283                 case 191 /* BindingElement */:
137284                     return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
137285                 default:
137286                     return false;
137287             }
137288         }
137289         function isVariableDeclarationInImport(decl) {
137290             return ts.isSourceFile(decl.parent.parent.parent) &&
137291                 !!decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
137292         }
137293         function filterImport(i, moduleSpecifier, keep) {
137294             switch (i.kind) {
137295                 case 254 /* ImportDeclaration */: {
137296                     var clause = i.importClause;
137297                     if (!clause)
137298                         return undefined;
137299                     var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
137300                     var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
137301                     return defaultImport || namedBindings
137302                         ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
137303                         : undefined;
137304                 }
137305                 case 253 /* ImportEqualsDeclaration */:
137306                     return keep(i.name) ? i : undefined;
137307                 case 242 /* VariableDeclaration */: {
137308                     var name = filterBindingName(i.name, keep);
137309                     return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
137310                 }
137311                 default:
137312                     return ts.Debug.assertNever(i, "Unexpected import kind " + i.kind);
137313             }
137314         }
137315         function filterNamedBindings(namedBindings, keep) {
137316             if (namedBindings.kind === 256 /* NamespaceImport */) {
137317                 return keep(namedBindings.name) ? namedBindings : undefined;
137318             }
137319             else {
137320                 var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
137321                 return newElements.length ? ts.createNamedImports(newElements) : undefined;
137322             }
137323         }
137324         function filterBindingName(name, keep) {
137325             switch (name.kind) {
137326                 case 75 /* Identifier */:
137327                     return keep(name) ? name : undefined;
137328                 case 190 /* ArrayBindingPattern */:
137329                     return name;
137330                 case 189 /* ObjectBindingPattern */: {
137331                     // We can't handle nested destructurings or property names well here, so just copy them all.
137332                     var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
137333                     return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
137334                 }
137335             }
137336         }
137337         function forEachReference(node, checker, onReference) {
137338             node.forEachChild(function cb(node) {
137339                 if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
137340                     var sym = checker.getSymbolAtLocation(node);
137341                     if (sym)
137342                         onReference(sym);
137343                 }
137344                 else {
137345                     node.forEachChild(cb);
137346                 }
137347             });
137348         }
137349         var SymbolSet = /** @class */ (function () {
137350             function SymbolSet() {
137351                 this.map = ts.createMap();
137352             }
137353             SymbolSet.prototype.add = function (symbol) {
137354                 this.map.set(String(ts.getSymbolId(symbol)), symbol);
137355             };
137356             SymbolSet.prototype.has = function (symbol) {
137357                 return this.map.has(String(ts.getSymbolId(symbol)));
137358             };
137359             SymbolSet.prototype.delete = function (symbol) {
137360                 this.map.delete(String(ts.getSymbolId(symbol)));
137361             };
137362             SymbolSet.prototype.forEach = function (cb) {
137363                 this.map.forEach(cb);
137364             };
137365             SymbolSet.prototype.forEachEntry = function (cb) {
137366                 return ts.forEachEntry(this.map, cb);
137367             };
137368             SymbolSet.prototype.clone = function () {
137369                 var clone = new SymbolSet();
137370                 ts.copyEntries(this.map, clone.map);
137371                 return clone;
137372             };
137373             return SymbolSet;
137374         }());
137375         function isTopLevelDeclaration(node) {
137376             return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
137377         }
137378         function sourceFileOfTopLevelDeclaration(node) {
137379             return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent;
137380         }
137381         function isTopLevelDeclarationStatement(node) {
137382             ts.Debug.assert(ts.isSourceFile(node.parent), "Node parent should be a SourceFile");
137383             return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
137384         }
137385         function isNonVariableTopLevelDeclaration(node) {
137386             switch (node.kind) {
137387                 case 244 /* FunctionDeclaration */:
137388                 case 245 /* ClassDeclaration */:
137389                 case 249 /* ModuleDeclaration */:
137390                 case 248 /* EnumDeclaration */:
137391                 case 247 /* TypeAliasDeclaration */:
137392                 case 246 /* InterfaceDeclaration */:
137393                 case 253 /* ImportEqualsDeclaration */:
137394                     return true;
137395                 default:
137396                     return false;
137397             }
137398         }
137399         function forEachTopLevelDeclaration(statement, cb) {
137400             switch (statement.kind) {
137401                 case 244 /* FunctionDeclaration */:
137402                 case 245 /* ClassDeclaration */:
137403                 case 249 /* ModuleDeclaration */:
137404                 case 248 /* EnumDeclaration */:
137405                 case 247 /* TypeAliasDeclaration */:
137406                 case 246 /* InterfaceDeclaration */:
137407                 case 253 /* ImportEqualsDeclaration */:
137408                     return cb(statement);
137409                 case 225 /* VariableStatement */:
137410                     return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); });
137411                 case 226 /* ExpressionStatement */: {
137412                     var expression = statement.expression;
137413                     return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */
137414                         ? cb(statement)
137415                         : undefined;
137416                 }
137417             }
137418         }
137419         function forEachTopLevelDeclarationInBindingName(name, cb) {
137420             switch (name.kind) {
137421                 case 75 /* Identifier */:
137422                     return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); }));
137423                 case 190 /* ArrayBindingPattern */:
137424                 case 189 /* ObjectBindingPattern */:
137425                     return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); });
137426                 default:
137427                     return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind);
137428             }
137429         }
137430         function nameOfTopLevelDeclaration(d) {
137431             return ts.isExpressionStatement(d) ? ts.tryCast(d.expression.left.name, ts.isIdentifier) : ts.tryCast(d.name, ts.isIdentifier);
137432         }
137433         function getTopLevelDeclarationStatement(d) {
137434             switch (d.kind) {
137435                 case 242 /* VariableDeclaration */:
137436                     return d.parent.parent;
137437                 case 191 /* BindingElement */:
137438                     return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); }));
137439                 default:
137440                     return d;
137441             }
137442         }
137443         function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
137444             if (isExported(sourceFile, decl, useEs6Exports))
137445                 return;
137446             if (useEs6Exports) {
137447                 if (!ts.isExpressionStatement(decl))
137448                     changes.insertExportModifier(sourceFile, decl);
137449             }
137450             else {
137451                 var names = getNamesToExportInCommonJS(decl);
137452                 if (names.length !== 0)
137453                     changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
137454             }
137455         }
137456         function isExported(sourceFile, decl, useEs6Exports) {
137457             if (useEs6Exports) {
137458                 return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
137459             }
137460             else {
137461                 return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
137462             }
137463         }
137464         function addExport(decl, useEs6Exports) {
137465             return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
137466         }
137467         function addEs6Export(d) {
137468             var modifiers = ts.concatenate([ts.createModifier(89 /* ExportKeyword */)], d.modifiers);
137469             switch (d.kind) {
137470                 case 244 /* FunctionDeclaration */:
137471                     return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
137472                 case 245 /* ClassDeclaration */:
137473                     return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
137474                 case 225 /* VariableStatement */:
137475                     return ts.updateVariableStatement(d, modifiers, d.declarationList);
137476                 case 249 /* ModuleDeclaration */:
137477                     return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
137478                 case 248 /* EnumDeclaration */:
137479                     return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
137480                 case 247 /* TypeAliasDeclaration */:
137481                     return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
137482                 case 246 /* InterfaceDeclaration */:
137483                     return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
137484                 case 253 /* ImportEqualsDeclaration */:
137485                     return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
137486                 case 226 /* ExpressionStatement */:
137487                     return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
137488                 default:
137489                     return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind);
137490             }
137491         }
137492         function addCommonjsExport(decl) {
137493             return __spreadArrays([decl], getNamesToExportInCommonJS(decl).map(createExportAssignment));
137494         }
137495         function getNamesToExportInCommonJS(decl) {
137496             switch (decl.kind) {
137497                 case 244 /* FunctionDeclaration */:
137498                 case 245 /* ClassDeclaration */:
137499                     return [decl.name.text]; // TODO: GH#18217
137500                 case 225 /* VariableStatement */:
137501                     return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
137502                 case 249 /* ModuleDeclaration */:
137503                 case 248 /* EnumDeclaration */:
137504                 case 247 /* TypeAliasDeclaration */:
137505                 case 246 /* InterfaceDeclaration */:
137506                 case 253 /* ImportEqualsDeclaration */:
137507                     return ts.emptyArray;
137508                 case 226 /* ExpressionStatement */:
137509                     return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...`
137510                 default:
137511                     return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind);
137512             }
137513         }
137514         /** Creates `exports.x = x;` */
137515         function createExportAssignment(name) {
137516             return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 62 /* EqualsToken */, ts.createIdentifier(name)));
137517         }
137518     })(refactor = ts.refactor || (ts.refactor = {}));
137519 })(ts || (ts = {}));
137520 /* @internal */
137521 var ts;
137522 (function (ts) {
137523     var refactor;
137524     (function (refactor) {
137525         var addOrRemoveBracesToArrowFunction;
137526         (function (addOrRemoveBracesToArrowFunction) {
137527             var refactorName = "Add or remove braces in an arrow function";
137528             var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message;
137529             var addBracesActionName = "Add braces to arrow function";
137530             var removeBracesActionName = "Remove braces from arrow function";
137531             var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message;
137532             var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message;
137533             refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
137534             function getAvailableActions(context) {
137535                 var file = context.file, startPosition = context.startPosition;
137536                 var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
137537                 if (!info)
137538                     return ts.emptyArray;
137539                 return [{
137540                         name: refactorName,
137541                         description: refactorDescription,
137542                         actions: [
137543                             info.addBraces ?
137544                                 {
137545                                     name: addBracesActionName,
137546                                     description: addBracesActionDescription
137547                                 } : {
137548                                 name: removeBracesActionName,
137549                                 description: removeBracesActionDescription
137550                             }
137551                         ]
137552                     }];
137553             }
137554             function getEditsForAction(context, actionName) {
137555                 var file = context.file, startPosition = context.startPosition;
137556                 var info = getConvertibleArrowFunctionAtPosition(file, startPosition);
137557                 if (!info)
137558                     return undefined;
137559                 var expression = info.expression, returnStatement = info.returnStatement, func = info.func;
137560                 var body;
137561                 if (actionName === addBracesActionName) {
137562                     var returnStatement_1 = ts.createReturn(expression);
137563                     body = ts.createBlock([returnStatement_1], /* multiLine */ true);
137564                     ts.suppressLeadingAndTrailingTrivia(body);
137565                     ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
137566                 }
137567                 else if (actionName === removeBracesActionName && returnStatement) {
137568                     var actualExpression = expression || ts.createVoidZero();
137569                     body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
137570                     ts.suppressLeadingAndTrailingTrivia(body);
137571                     ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137572                     ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137573                     ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
137574                 }
137575                 else {
137576                     ts.Debug.fail("invalid action");
137577                 }
137578                 var edits = ts.textChanges.ChangeTracker.with(context, function (t) {
137579                     t.replaceNode(file, func.body, body);
137580                 });
137581                 return { renameFilename: undefined, renameLocation: undefined, edits: edits };
137582             }
137583             function getConvertibleArrowFunctionAtPosition(file, startPosition) {
137584                 var node = ts.getTokenAtPosition(file, startPosition);
137585                 var func = ts.getContainingFunction(node);
137586                 if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node)))
137587                     return undefined;
137588                 if (ts.isExpression(func.body)) {
137589                     return {
137590                         func: func,
137591                         addBraces: true,
137592                         expression: func.body
137593                     };
137594                 }
137595                 else if (func.body.statements.length === 1) {
137596                     var firstStatement = ts.first(func.body.statements);
137597                     if (ts.isReturnStatement(firstStatement)) {
137598                         return {
137599                             func: func,
137600                             addBraces: false,
137601                             expression: firstStatement.expression,
137602                             returnStatement: firstStatement
137603                         };
137604                     }
137605                 }
137606                 return undefined;
137607             }
137608         })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
137609     })(refactor = ts.refactor || (ts.refactor = {}));
137610 })(ts || (ts = {}));
137611 /* @internal */
137612 var ts;
137613 (function (ts) {
137614     var refactor;
137615     (function (refactor) {
137616         var convertParamsToDestructuredObject;
137617         (function (convertParamsToDestructuredObject) {
137618             var refactorName = "Convert parameters to destructured object";
137619             var minimumParameterLength = 2;
137620             refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
137621             function getAvailableActions(context) {
137622                 var file = context.file, startPosition = context.startPosition;
137623                 var isJSFile = ts.isSourceFileJS(file);
137624                 if (isJSFile)
137625                     return ts.emptyArray; // TODO: GH#30113
137626                 var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
137627                 if (!functionDeclaration)
137628                     return ts.emptyArray;
137629                 var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
137630                 return [{
137631                         name: refactorName,
137632                         description: description,
137633                         actions: [{
137634                                 name: refactorName,
137635                                 description: description
137636                             }]
137637                     }];
137638             }
137639             function getEditsForAction(context, actionName) {
137640                 ts.Debug.assert(actionName === refactorName, "Unexpected action name");
137641                 var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
137642                 var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
137643                 if (!functionDeclaration || !cancellationToken)
137644                     return undefined;
137645                 var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
137646                 if (groupedReferences.valid) {
137647                     var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
137648                     return { renameFilename: undefined, renameLocation: undefined, edits: edits };
137649                 }
137650                 return { edits: [] }; // TODO: GH#30113
137651             }
137652             function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
137653                 var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
137654                 changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
137655                     // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
137656                     indentation: 0,
137657                     leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
137658                     trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
137659                 });
137660                 var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
137661                 for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
137662                     var call = functionCalls_1[_i];
137663                     if (call.arguments && call.arguments.length) {
137664                         var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
137665                         changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
137666                     }
137667                 }
137668             }
137669             function getGroupedReferences(functionDeclaration, program, cancellationToken) {
137670                 var functionNames = getFunctionNames(functionDeclaration);
137671                 var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
137672                 var names = ts.deduplicate(__spreadArrays(functionNames, classNames), ts.equateValues);
137673                 var checker = program.getTypeChecker();
137674                 var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
137675                 var groupedReferences = groupReferences(references);
137676                 if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
137677                     groupedReferences.valid = false;
137678                 }
137679                 return groupedReferences;
137680                 function groupReferences(referenceEntries) {
137681                     var classReferences = { accessExpressions: [], typeUsages: [] };
137682                     var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
137683                     var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation);
137684                     var classSymbols = ts.map(classNames, getSymbolTargetAtLocation);
137685                     var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
137686                     for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
137687                         var entry = referenceEntries_1[_i];
137688                         if (entry.kind !== 1 /* Node */) {
137689                             groupedReferences.valid = false;
137690                             continue;
137691                         }
137692                         /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
137693                         Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
137694                             class A { foo(a: number, b: number) { return a + b; } }
137695                             class B { foo(c: number, d: number) { return c + d; } }
137696                             declare const ab: A | B;
137697                             ab.foo(1, 2);
137698                         Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
137699                         When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
137700                         So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
137701                         the symbols are going to be different.
137702                         */
137703                         if (ts.contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || ts.isNewExpressionTarget(entry.node)) {
137704                             var importOrExportReference = entryToImportOrExport(entry);
137705                             if (importOrExportReference) {
137706                                 continue;
137707                             }
137708                             var decl = entryToDeclaration(entry);
137709                             if (decl) {
137710                                 groupedReferences.declarations.push(decl);
137711                                 continue;
137712                             }
137713                             var call = entryToFunctionCall(entry);
137714                             if (call) {
137715                                 groupedReferences.functionCalls.push(call);
137716                                 continue;
137717                             }
137718                         }
137719                         // if the refactored function is a constructor, we must also check if the references to its class are valid
137720                         if (isConstructor && ts.contains(classSymbols, getSymbolTargetAtLocation(entry.node))) {
137721                             var importOrExportReference = entryToImportOrExport(entry);
137722                             if (importOrExportReference) {
137723                                 continue;
137724                             }
137725                             var decl = entryToDeclaration(entry);
137726                             if (decl) {
137727                                 groupedReferences.declarations.push(decl);
137728                                 continue;
137729                             }
137730                             var accessExpression = entryToAccessExpression(entry);
137731                             if (accessExpression) {
137732                                 classReferences.accessExpressions.push(accessExpression);
137733                                 continue;
137734                             }
137735                             // Only class declarations are allowed to be used as a type (in a heritage clause),
137736                             // otherwise `findAllReferences` might not be able to track constructor calls.
137737                             if (ts.isClassDeclaration(functionDeclaration.parent)) {
137738                                 var type = entryToType(entry);
137739                                 if (type) {
137740                                     classReferences.typeUsages.push(type);
137741                                     continue;
137742                                 }
137743                             }
137744                         }
137745                         groupedReferences.valid = false;
137746                     }
137747                     return groupedReferences;
137748                 }
137749                 function getSymbolTargetAtLocation(node) {
137750                     var symbol = checker.getSymbolAtLocation(node);
137751                     return symbol && ts.getSymbolTarget(symbol, checker);
137752                 }
137753             }
137754             function entryToImportOrExport(entry) {
137755                 var node = entry.node;
137756                 if (ts.isImportSpecifier(node.parent)
137757                     || ts.isImportClause(node.parent)
137758                     || ts.isImportEqualsDeclaration(node.parent)
137759                     || ts.isNamespaceImport(node.parent)) {
137760                     return node;
137761                 }
137762                 if (ts.isExportSpecifier(node.parent) || ts.isExportAssignment(node.parent)) {
137763                     return node;
137764                 }
137765                 return undefined;
137766             }
137767             function entryToDeclaration(entry) {
137768                 if (ts.isDeclaration(entry.node.parent)) {
137769                     return entry.node;
137770                 }
137771                 return undefined;
137772             }
137773             function entryToFunctionCall(entry) {
137774                 if (entry.node.parent) {
137775                     var functionReference = entry.node;
137776                     var parent = functionReference.parent;
137777                     switch (parent.kind) {
137778                         // foo(...) or super(...) or new Foo(...)
137779                         case 196 /* CallExpression */:
137780                         case 197 /* NewExpression */:
137781                             var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression);
137782                             if (callOrNewExpression && callOrNewExpression.expression === functionReference) {
137783                                 return callOrNewExpression;
137784                             }
137785                             break;
137786                         // x.foo(...)
137787                         case 194 /* PropertyAccessExpression */:
137788                             var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
137789                             if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
137790                                 var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression);
137791                                 if (callOrNewExpression_1 && callOrNewExpression_1.expression === propertyAccessExpression) {
137792                                     return callOrNewExpression_1;
137793                                 }
137794                             }
137795                             break;
137796                         // x["foo"](...)
137797                         case 195 /* ElementAccessExpression */:
137798                             var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
137799                             if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
137800                                 var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression);
137801                                 if (callOrNewExpression_2 && callOrNewExpression_2.expression === elementAccessExpression) {
137802                                     return callOrNewExpression_2;
137803                                 }
137804                             }
137805                             break;
137806                     }
137807                 }
137808                 return undefined;
137809             }
137810             function entryToAccessExpression(entry) {
137811                 if (entry.node.parent) {
137812                     var reference = entry.node;
137813                     var parent = reference.parent;
137814                     switch (parent.kind) {
137815                         // `C.foo`
137816                         case 194 /* PropertyAccessExpression */:
137817                             var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
137818                             if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
137819                                 return propertyAccessExpression;
137820                             }
137821                             break;
137822                         // `C["foo"]`
137823                         case 195 /* ElementAccessExpression */:
137824                             var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
137825                             if (elementAccessExpression && elementAccessExpression.expression === reference) {
137826                                 return elementAccessExpression;
137827                             }
137828                             break;
137829                     }
137830                 }
137831                 return undefined;
137832             }
137833             function entryToType(entry) {
137834                 var reference = entry.node;
137835                 if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
137836                     return reference;
137837                 }
137838                 return undefined;
137839             }
137840             function getFunctionDeclarationAtPosition(file, startPosition, checker) {
137841                 var node = ts.getTouchingToken(file, startPosition);
137842                 var functionDeclaration = ts.getContainingFunctionDeclaration(node);
137843                 // don't offer refactor on top-level JSDoc
137844                 if (isTopLevelJSDoc(node))
137845                     return undefined;
137846                 if (functionDeclaration
137847                     && isValidFunctionDeclaration(functionDeclaration, checker)
137848                     && ts.rangeContainsRange(functionDeclaration, node)
137849                     && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
137850                     return functionDeclaration;
137851                 return undefined;
137852             }
137853             function isTopLevelJSDoc(node) {
137854                 var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
137855                 if (containingJSDoc) {
137856                     var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
137857                     return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
137858                 }
137859                 return false;
137860             }
137861             function isValidFunctionDeclaration(functionDeclaration, checker) {
137862                 if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
137863                     return false;
137864                 switch (functionDeclaration.kind) {
137865                     case 244 /* FunctionDeclaration */:
137866                         return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker);
137867                     case 161 /* MethodDeclaration */:
137868                         return isSingleImplementation(functionDeclaration, checker);
137869                     case 162 /* Constructor */:
137870                         if (ts.isClassDeclaration(functionDeclaration.parent)) {
137871                             return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker);
137872                         }
137873                         else {
137874                             return isValidVariableDeclaration(functionDeclaration.parent.parent)
137875                                 && isSingleImplementation(functionDeclaration, checker);
137876                         }
137877                     case 201 /* FunctionExpression */:
137878                     case 202 /* ArrowFunction */:
137879                         return isValidVariableDeclaration(functionDeclaration.parent);
137880                 }
137881                 return false;
137882             }
137883             function isSingleImplementation(functionDeclaration, checker) {
137884                 return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
137885             }
137886             function hasNameOrDefault(functionOrClassDeclaration) {
137887                 if (!functionOrClassDeclaration.name) {
137888                     var defaultKeyword = ts.findModifier(functionOrClassDeclaration, 84 /* DefaultKeyword */);
137889                     return !!defaultKeyword;
137890                 }
137891                 return true;
137892             }
137893             function isValidParameterNodeArray(parameters, checker) {
137894                 return getRefactorableParametersLength(parameters) >= minimumParameterLength
137895                     && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
137896             }
137897             function isValidParameterDeclaration(parameterDeclaration, checker) {
137898                 if (ts.isRestParameter(parameterDeclaration)) {
137899                     var type = checker.getTypeAtLocation(parameterDeclaration);
137900                     if (!checker.isArrayType(type) && !checker.isTupleType(type))
137901                         return false;
137902                 }
137903                 return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
137904             }
137905             function isValidVariableDeclaration(node) {
137906                 return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
137907             }
137908             function hasThisParameter(parameters) {
137909                 return parameters.length > 0 && ts.isThis(parameters[0].name);
137910             }
137911             function getRefactorableParametersLength(parameters) {
137912                 if (hasThisParameter(parameters)) {
137913                     return parameters.length - 1;
137914                 }
137915                 return parameters.length;
137916             }
137917             function getRefactorableParameters(parameters) {
137918                 if (hasThisParameter(parameters)) {
137919                     parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
137920                 }
137921                 return parameters;
137922             }
137923             function createPropertyOrShorthandAssignment(name, initializer) {
137924                 if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
137925                     return ts.createShorthandPropertyAssignment(name);
137926                 }
137927                 return ts.createPropertyAssignment(name, initializer);
137928             }
137929             function createNewArgument(functionDeclaration, functionArguments) {
137930                 var parameters = getRefactorableParameters(functionDeclaration.parameters);
137931                 var hasRestParameter = ts.isRestParameter(ts.last(parameters));
137932                 var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
137933                 var properties = ts.map(nonRestArguments, function (arg, i) {
137934                     var parameterName = getParameterName(parameters[i]);
137935                     var property = createPropertyOrShorthandAssignment(parameterName, arg);
137936                     ts.suppressLeadingAndTrailingTrivia(property.name);
137937                     if (ts.isPropertyAssignment(property))
137938                         ts.suppressLeadingAndTrailingTrivia(property.initializer);
137939                     ts.copyComments(arg, property);
137940                     return property;
137941                 });
137942                 if (hasRestParameter && functionArguments.length >= parameters.length) {
137943                     var restArguments = functionArguments.slice(parameters.length - 1);
137944                     var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
137945                     properties.push(restProperty);
137946                 }
137947                 var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
137948                 return objectLiteral;
137949             }
137950             function createNewParameters(functionDeclaration, program, host) {
137951                 var checker = program.getTypeChecker();
137952                 var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
137953                 var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
137954                 var objectParameterName = ts.createObjectBindingPattern(bindingElements);
137955                 var objectParameterType = createParameterTypeNode(refactorableParameters);
137956                 var objectInitializer;
137957                 // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
137958                 if (ts.every(refactorableParameters, isOptionalParameter)) {
137959                     objectInitializer = ts.createObjectLiteral();
137960                 }
137961                 var objectParameter = ts.createParameter(
137962                 /*decorators*/ undefined, 
137963                 /*modifiers*/ undefined, 
137964                 /*dotDotDotToken*/ undefined, objectParameterName, 
137965                 /*questionToken*/ undefined, objectParameterType, objectInitializer);
137966                 if (hasThisParameter(functionDeclaration.parameters)) {
137967                     var thisParameter = functionDeclaration.parameters[0];
137968                     var newThisParameter = ts.createParameter(
137969                     /*decorators*/ undefined, 
137970                     /*modifiers*/ undefined, 
137971                     /*dotDotDotToken*/ undefined, thisParameter.name, 
137972                     /*questionToken*/ undefined, thisParameter.type);
137973                     ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
137974                     ts.copyComments(thisParameter.name, newThisParameter.name);
137975                     if (thisParameter.type) {
137976                         ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
137977                         ts.copyComments(thisParameter.type, newThisParameter.type);
137978                     }
137979                     return ts.createNodeArray([newThisParameter, objectParameter]);
137980                 }
137981                 return ts.createNodeArray([objectParameter]);
137982                 function createBindingElementFromParameterDeclaration(parameterDeclaration) {
137983                     var element = ts.createBindingElement(
137984                     /*dotDotDotToken*/ undefined, 
137985                     /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
137986                     ts.suppressLeadingAndTrailingTrivia(element);
137987                     if (parameterDeclaration.initializer && element.initializer) {
137988                         ts.copyComments(parameterDeclaration.initializer, element.initializer);
137989                     }
137990                     return element;
137991                 }
137992                 function createParameterTypeNode(parameters) {
137993                     var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
137994                     var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
137995                     return typeNode;
137996                 }
137997                 function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
137998                     var parameterType = parameterDeclaration.type;
137999                     if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
138000                         parameterType = getTypeNode(parameterDeclaration);
138001                     }
138002                     var propertySignature = ts.createPropertySignature(
138003                     /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, 
138004                     /*initializer*/ undefined);
138005                     ts.suppressLeadingAndTrailingTrivia(propertySignature);
138006                     ts.copyComments(parameterDeclaration.name, propertySignature.name);
138007                     if (parameterDeclaration.type && propertySignature.type) {
138008                         ts.copyComments(parameterDeclaration.type, propertySignature.type);
138009                     }
138010                     return propertySignature;
138011                 }
138012                 function getTypeNode(node) {
138013                     var type = checker.getTypeAtLocation(node);
138014                     return ts.getTypeNodeIfAccessible(type, node, program, host);
138015                 }
138016                 function isOptionalParameter(parameterDeclaration) {
138017                     if (ts.isRestParameter(parameterDeclaration)) {
138018                         var type = checker.getTypeAtLocation(parameterDeclaration);
138019                         return !checker.isTupleType(type);
138020                     }
138021                     return checker.isOptionalParameter(parameterDeclaration);
138022                 }
138023             }
138024             function getParameterName(paramDeclaration) {
138025                 return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
138026             }
138027             function getClassNames(constructorDeclaration) {
138028                 switch (constructorDeclaration.parent.kind) {
138029                     case 245 /* ClassDeclaration */:
138030                         var classDeclaration = constructorDeclaration.parent;
138031                         if (classDeclaration.name)
138032                             return [classDeclaration.name];
138033                         // If the class declaration doesn't have a name, it should have a default modifier.
138034                         // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
138035                         var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 84 /* DefaultKeyword */), "Nameless class declaration should be a default export");
138036                         return [defaultModifier];
138037                     case 214 /* ClassExpression */:
138038                         var classExpression = constructorDeclaration.parent;
138039                         var variableDeclaration = constructorDeclaration.parent.parent;
138040                         var className = classExpression.name;
138041                         if (className)
138042                             return [className, variableDeclaration.name];
138043                         return [variableDeclaration.name];
138044                 }
138045             }
138046             function getFunctionNames(functionDeclaration) {
138047                 switch (functionDeclaration.kind) {
138048                     case 244 /* FunctionDeclaration */:
138049                         if (functionDeclaration.name)
138050                             return [functionDeclaration.name];
138051                         // If the function declaration doesn't have a name, it should have a default modifier.
138052                         // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
138053                         var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 84 /* DefaultKeyword */), "Nameless function declaration should be a default export");
138054                         return [defaultModifier];
138055                     case 161 /* MethodDeclaration */:
138056                         return [functionDeclaration.name];
138057                     case 162 /* Constructor */:
138058                         var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 129 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword");
138059                         if (functionDeclaration.parent.kind === 214 /* ClassExpression */) {
138060                             var variableDeclaration = functionDeclaration.parent.parent;
138061                             return [variableDeclaration.name, ctrKeyword];
138062                         }
138063                         return [ctrKeyword];
138064                     case 202 /* ArrowFunction */:
138065                         return [functionDeclaration.parent.name];
138066                     case 201 /* FunctionExpression */:
138067                         if (functionDeclaration.name)
138068                             return [functionDeclaration.name, functionDeclaration.parent.name];
138069                         return [functionDeclaration.parent.name];
138070                     default:
138071                         return ts.Debug.assertNever(functionDeclaration, "Unexpected function declaration kind " + functionDeclaration.kind);
138072                 }
138073             }
138074         })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
138075     })(refactor = ts.refactor || (ts.refactor = {}));
138076 })(ts || (ts = {}));
138077 /* @internal */
138078 var ts;
138079 (function (ts) {
138080     var refactor;
138081     (function (refactor) {
138082         var convertStringOrTemplateLiteral;
138083         (function (convertStringOrTemplateLiteral) {
138084             var refactorName = "Convert to template string";
138085             var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_template_string);
138086             refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
138087             function getAvailableActions(context) {
138088                 var file = context.file, startPosition = context.startPosition;
138089                 var node = getNodeOrParentOfParentheses(file, startPosition);
138090                 var maybeBinary = getParentBinaryExpression(node);
138091                 var refactorInfo = { name: refactorName, description: refactorDescription, actions: [] };
138092                 if (ts.isBinaryExpression(maybeBinary) && isStringConcatenationValid(maybeBinary)) {
138093                     refactorInfo.actions.push({ name: refactorName, description: refactorDescription });
138094                     return [refactorInfo];
138095                 }
138096                 return ts.emptyArray;
138097             }
138098             function getNodeOrParentOfParentheses(file, startPosition) {
138099                 var node = ts.getTokenAtPosition(file, startPosition);
138100                 var nestedBinary = getParentBinaryExpression(node);
138101                 var isNonStringBinary = !isStringConcatenationValid(nestedBinary);
138102                 if (isNonStringBinary &&
138103                     ts.isParenthesizedExpression(nestedBinary.parent) &&
138104                     ts.isBinaryExpression(nestedBinary.parent.parent)) {
138105                     return nestedBinary.parent.parent;
138106                 }
138107                 return node;
138108             }
138109             function getEditsForAction(context, actionName) {
138110                 var file = context.file, startPosition = context.startPosition;
138111                 var node = getNodeOrParentOfParentheses(file, startPosition);
138112                 switch (actionName) {
138113                     case refactorDescription:
138114                         return { edits: getEditsForToTemplateLiteral(context, node) };
138115                     default:
138116                         return ts.Debug.fail("invalid action");
138117                 }
138118             }
138119             function getEditsForToTemplateLiteral(context, node) {
138120                 var maybeBinary = getParentBinaryExpression(node);
138121                 var file = context.file;
138122                 var templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file);
138123                 var trailingCommentRanges = ts.getTrailingCommentRanges(file.text, maybeBinary.end);
138124                 if (trailingCommentRanges) {
138125                     var lastComment = trailingCommentRanges[trailingCommentRanges.length - 1];
138126                     var trailingRange_1 = { pos: trailingCommentRanges[0].pos, end: lastComment.end };
138127                     // since suppressTrailingTrivia(maybeBinary) does not work, the trailing comment is removed manually
138128                     // otherwise it would have the trailing comment twice
138129                     return ts.textChanges.ChangeTracker.with(context, function (t) {
138130                         t.deleteRange(file, trailingRange_1);
138131                         t.replaceNode(file, maybeBinary, templateLiteral);
138132                     });
138133                 }
138134                 else {
138135                     return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, maybeBinary, templateLiteral); });
138136                 }
138137             }
138138             function isNotEqualsOperator(node) {
138139                 return node.operatorToken.kind !== 62 /* EqualsToken */;
138140             }
138141             function getParentBinaryExpression(expr) {
138142                 while (ts.isBinaryExpression(expr.parent) && isNotEqualsOperator(expr.parent)) {
138143                     expr = expr.parent;
138144                 }
138145                 return expr;
138146             }
138147             function isStringConcatenationValid(node) {
138148                 var _a = treeToArray(node), containsString = _a.containsString, areOperatorsValid = _a.areOperatorsValid;
138149                 return containsString && areOperatorsValid;
138150             }
138151             function treeToArray(current) {
138152                 if (ts.isBinaryExpression(current)) {
138153                     var _a = treeToArray(current.left), nodes = _a.nodes, operators = _a.operators, leftHasString = _a.containsString, leftOperatorValid = _a.areOperatorsValid;
138154                     if (!leftHasString && !ts.isStringLiteral(current.right)) {
138155                         return { nodes: [current], operators: [], containsString: false, areOperatorsValid: true };
138156                     }
138157                     var currentOperatorValid = current.operatorToken.kind === 39 /* PlusToken */;
138158                     var areOperatorsValid = leftOperatorValid && currentOperatorValid;
138159                     nodes.push(current.right);
138160                     operators.push(current.operatorToken);
138161                     return { nodes: nodes, operators: operators, containsString: true, areOperatorsValid: areOperatorsValid };
138162                 }
138163                 return { nodes: [current], operators: [], containsString: ts.isStringLiteral(current), areOperatorsValid: true };
138164             }
138165             // to copy comments following the operator
138166             // "foo" + /* comment */ "bar"
138167             var copyTrailingOperatorComments = function (operators, file) { return function (index, targetNode) {
138168                 if (index < operators.length) {
138169                     ts.copyTrailingComments(operators[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
138170                 }
138171             }; };
138172             // to copy comments following the string
138173             // "foo" /* comment */ + "bar" /* comment */ + "bar2"
138174             var copyCommentFromMultiNode = function (nodes, file, copyOperatorComments) {
138175                 return function (indexes, targetNode) {
138176                     while (indexes.length > 0) {
138177                         var index = indexes.shift();
138178                         ts.copyTrailingComments(nodes[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
138179                         copyOperatorComments(index, targetNode);
138180                     }
138181                 };
138182             };
138183             function concatConsecutiveString(index, nodes) {
138184                 var text = "";
138185                 var indexes = [];
138186                 while (index < nodes.length && ts.isStringLiteral(nodes[index])) {
138187                     var stringNode = nodes[index];
138188                     text = text + stringNode.text;
138189                     indexes.push(index);
138190                     index++;
138191                 }
138192                 return [index, text, indexes];
138193             }
138194             function nodesToTemplate(_a, file) {
138195                 var nodes = _a.nodes, operators = _a.operators;
138196                 var copyOperatorComments = copyTrailingOperatorComments(operators, file);
138197                 var copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments);
138198                 var _b = concatConsecutiveString(0, nodes), begin = _b[0], headText = _b[1], headIndexes = _b[2];
138199                 if (begin === nodes.length) {
138200                     var noSubstitutionTemplateLiteral = ts.createNoSubstitutionTemplateLiteral(headText);
138201                     copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral);
138202                     return noSubstitutionTemplateLiteral;
138203                 }
138204                 var templateSpans = [];
138205                 var templateHead = ts.createTemplateHead(headText);
138206                 copyCommentFromStringLiterals(headIndexes, templateHead);
138207                 for (var i = begin; i < nodes.length; i++) {
138208                     var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]);
138209                     copyOperatorComments(i, currentNode);
138210                     var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2];
138211                     i = newIndex - 1;
138212                     var templatePart = i === nodes.length - 1 ? ts.createTemplateTail(subsequentText) : ts.createTemplateMiddle(subsequentText);
138213                     copyCommentFromStringLiterals(stringIndexes, templatePart);
138214                     templateSpans.push(ts.createTemplateSpan(currentNode, templatePart));
138215                 }
138216                 return ts.createTemplateExpression(templateHead, templateSpans);
138217             }
138218             // to copy comments following the opening & closing parentheses
138219             // "foo" + ( /* comment */ 5 + 5 ) /* comment */ + "bar"
138220             function copyCommentsWhenParenthesized(node) {
138221                 var file = node.getSourceFile();
138222                 ts.copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
138223                 ts.copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
138224             }
138225             function getExpressionFromParenthesesOrExpression(node) {
138226                 if (ts.isParenthesizedExpression(node)) {
138227                     copyCommentsWhenParenthesized(node);
138228                     node = node.expression;
138229                 }
138230                 return node;
138231             }
138232         })(convertStringOrTemplateLiteral = refactor.convertStringOrTemplateLiteral || (refactor.convertStringOrTemplateLiteral = {}));
138233     })(refactor = ts.refactor || (ts.refactor = {}));
138234 })(ts || (ts = {}));
138235 var ts;
138236 (function (ts) {
138237     /** The version of the language service API */
138238     ts.servicesVersion = "0.8";
138239     function createNode(kind, pos, end, parent) {
138240         var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) :
138241             kind === 75 /* Identifier */ ? new IdentifierObject(75 /* Identifier */, pos, end) :
138242                 kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierObject(76 /* PrivateIdentifier */, pos, end) :
138243                     new TokenObject(kind, pos, end);
138244         node.parent = parent;
138245         node.flags = parent.flags & 25358336 /* ContextFlags */;
138246         return node;
138247     }
138248     var NodeObject = /** @class */ (function () {
138249         function NodeObject(kind, pos, end) {
138250             this.pos = pos;
138251             this.end = end;
138252             this.flags = 0 /* None */;
138253             this.modifierFlagsCache = 0 /* None */;
138254             this.transformFlags = 0 /* None */;
138255             this.parent = undefined;
138256             this.kind = kind;
138257         }
138258         NodeObject.prototype.assertHasRealPosition = function (message) {
138259             // eslint-disable-next-line debug-assert
138260             ts.Debug.assert(!ts.positionIsSynthesized(this.pos) && !ts.positionIsSynthesized(this.end), message || "Node must have a real position for this operation");
138261         };
138262         NodeObject.prototype.getSourceFile = function () {
138263             return ts.getSourceFileOfNode(this);
138264         };
138265         NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
138266             this.assertHasRealPosition();
138267             return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
138268         };
138269         NodeObject.prototype.getFullStart = function () {
138270             this.assertHasRealPosition();
138271             return this.pos;
138272         };
138273         NodeObject.prototype.getEnd = function () {
138274             this.assertHasRealPosition();
138275             return this.end;
138276         };
138277         NodeObject.prototype.getWidth = function (sourceFile) {
138278             this.assertHasRealPosition();
138279             return this.getEnd() - this.getStart(sourceFile);
138280         };
138281         NodeObject.prototype.getFullWidth = function () {
138282             this.assertHasRealPosition();
138283             return this.end - this.pos;
138284         };
138285         NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
138286             this.assertHasRealPosition();
138287             return this.getStart(sourceFile) - this.pos;
138288         };
138289         NodeObject.prototype.getFullText = function (sourceFile) {
138290             this.assertHasRealPosition();
138291             return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
138292         };
138293         NodeObject.prototype.getText = function (sourceFile) {
138294             this.assertHasRealPosition();
138295             if (!sourceFile) {
138296                 sourceFile = this.getSourceFile();
138297             }
138298             return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
138299         };
138300         NodeObject.prototype.getChildCount = function (sourceFile) {
138301             return this.getChildren(sourceFile).length;
138302         };
138303         NodeObject.prototype.getChildAt = function (index, sourceFile) {
138304             return this.getChildren(sourceFile)[index];
138305         };
138306         NodeObject.prototype.getChildren = function (sourceFile) {
138307             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");
138308             return this._children || (this._children = createChildren(this, sourceFile));
138309         };
138310         NodeObject.prototype.getFirstToken = function (sourceFile) {
138311             this.assertHasRealPosition();
138312             var children = this.getChildren(sourceFile);
138313             if (!children.length) {
138314                 return undefined;
138315             }
138316             var child = ts.find(children, function (kid) { return kid.kind < 294 /* FirstJSDocNode */ || kid.kind > 323 /* LastJSDocNode */; });
138317             return child.kind < 153 /* FirstNode */ ?
138318                 child :
138319                 child.getFirstToken(sourceFile);
138320         };
138321         NodeObject.prototype.getLastToken = function (sourceFile) {
138322             this.assertHasRealPosition();
138323             var children = this.getChildren(sourceFile);
138324             var child = ts.lastOrUndefined(children);
138325             if (!child) {
138326                 return undefined;
138327             }
138328             return child.kind < 153 /* FirstNode */ ? child : child.getLastToken(sourceFile);
138329         };
138330         NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) {
138331             return ts.forEachChild(this, cbNode, cbNodeArray);
138332         };
138333         return NodeObject;
138334     }());
138335     function createChildren(node, sourceFile) {
138336         if (!ts.isNodeKind(node.kind)) {
138337             return ts.emptyArray;
138338         }
138339         var children = [];
138340         if (ts.isJSDocCommentContainingNode(node)) {
138341             /** Don't add trivia for "tokens" since this is in a comment. */
138342             node.forEachChild(function (child) { children.push(child); });
138343             return children;
138344         }
138345         ts.scanner.setText((sourceFile || node.getSourceFile()).text);
138346         var pos = node.pos;
138347         var processNode = function (child) {
138348             addSyntheticNodes(children, pos, child.pos, node);
138349             children.push(child);
138350             pos = child.end;
138351         };
138352         var processNodes = function (nodes) {
138353             addSyntheticNodes(children, pos, nodes.pos, node);
138354             children.push(createSyntaxList(nodes, node));
138355             pos = nodes.end;
138356         };
138357         // jsDocComments need to be the first children
138358         ts.forEach(node.jsDoc, processNode);
138359         // For syntactic classifications, all trivia are classified together, including jsdoc comments.
138360         // For that to work, the jsdoc comments should still be the leading trivia of the first child.
138361         // Restoring the scanner position ensures that.
138362         pos = node.pos;
138363         node.forEachChild(processNode, processNodes);
138364         addSyntheticNodes(children, pos, node.end, node);
138365         ts.scanner.setText(undefined);
138366         return children;
138367     }
138368     function addSyntheticNodes(nodes, pos, end, parent) {
138369         ts.scanner.setTextPos(pos);
138370         while (pos < end) {
138371             var token = ts.scanner.scan();
138372             var textPos = ts.scanner.getTextPos();
138373             if (textPos <= end) {
138374                 if (token === 75 /* Identifier */) {
138375                     ts.Debug.fail("Did not expect " + ts.Debug.formatSyntaxKind(parent.kind) + " to have an Identifier in its trivia");
138376                 }
138377                 nodes.push(createNode(token, pos, textPos, parent));
138378             }
138379             pos = textPos;
138380             if (token === 1 /* EndOfFileToken */) {
138381                 break;
138382             }
138383         }
138384     }
138385     function createSyntaxList(nodes, parent) {
138386         var list = createNode(324 /* SyntaxList */, nodes.pos, nodes.end, parent);
138387         list._children = [];
138388         var pos = nodes.pos;
138389         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
138390             var node = nodes_1[_i];
138391             addSyntheticNodes(list._children, pos, node.pos, parent);
138392             list._children.push(node);
138393             pos = node.end;
138394         }
138395         addSyntheticNodes(list._children, pos, nodes.end, parent);
138396         return list;
138397     }
138398     var TokenOrIdentifierObject = /** @class */ (function () {
138399         function TokenOrIdentifierObject(pos, end) {
138400             // Set properties in same order as NodeObject
138401             this.pos = pos;
138402             this.end = end;
138403             this.flags = 0 /* None */;
138404             this.modifierFlagsCache = 0 /* None */;
138405             this.transformFlags = 0 /* None */;
138406             this.parent = undefined;
138407         }
138408         TokenOrIdentifierObject.prototype.getSourceFile = function () {
138409             return ts.getSourceFileOfNode(this);
138410         };
138411         TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
138412             return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
138413         };
138414         TokenOrIdentifierObject.prototype.getFullStart = function () {
138415             return this.pos;
138416         };
138417         TokenOrIdentifierObject.prototype.getEnd = function () {
138418             return this.end;
138419         };
138420         TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
138421             return this.getEnd() - this.getStart(sourceFile);
138422         };
138423         TokenOrIdentifierObject.prototype.getFullWidth = function () {
138424             return this.end - this.pos;
138425         };
138426         TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
138427             return this.getStart(sourceFile) - this.pos;
138428         };
138429         TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
138430             return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
138431         };
138432         TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
138433             if (!sourceFile) {
138434                 sourceFile = this.getSourceFile();
138435             }
138436             return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd());
138437         };
138438         TokenOrIdentifierObject.prototype.getChildCount = function () {
138439             return 0;
138440         };
138441         TokenOrIdentifierObject.prototype.getChildAt = function () {
138442             return undefined; // TODO: GH#18217
138443         };
138444         TokenOrIdentifierObject.prototype.getChildren = function () {
138445             return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray;
138446         };
138447         TokenOrIdentifierObject.prototype.getFirstToken = function () {
138448             return undefined;
138449         };
138450         TokenOrIdentifierObject.prototype.getLastToken = function () {
138451             return undefined;
138452         };
138453         TokenOrIdentifierObject.prototype.forEachChild = function () {
138454             return undefined;
138455         };
138456         return TokenOrIdentifierObject;
138457     }());
138458     var SymbolObject = /** @class */ (function () {
138459         function SymbolObject(flags, name) {
138460             this.flags = flags;
138461             this.escapedName = name;
138462         }
138463         SymbolObject.prototype.getFlags = function () {
138464             return this.flags;
138465         };
138466         Object.defineProperty(SymbolObject.prototype, "name", {
138467             get: function () {
138468                 return ts.symbolName(this);
138469             },
138470             enumerable: false,
138471             configurable: true
138472         });
138473         SymbolObject.prototype.getEscapedName = function () {
138474             return this.escapedName;
138475         };
138476         SymbolObject.prototype.getName = function () {
138477             return this.name;
138478         };
138479         SymbolObject.prototype.getDeclarations = function () {
138480             return this.declarations;
138481         };
138482         SymbolObject.prototype.getDocumentationComment = function (checker) {
138483             if (!this.documentationComment) {
138484                 this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs
138485                 this.documentationComment = getDocumentationComment(this.declarations, checker);
138486             }
138487             return this.documentationComment;
138488         };
138489         SymbolObject.prototype.getJsDocTags = function () {
138490             if (this.tags === undefined) {
138491                 this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations);
138492             }
138493             return this.tags;
138494         };
138495         return SymbolObject;
138496     }());
138497     var TokenObject = /** @class */ (function (_super) {
138498         __extends(TokenObject, _super);
138499         function TokenObject(kind, pos, end) {
138500             var _this = _super.call(this, pos, end) || this;
138501             _this.kind = kind;
138502             return _this;
138503         }
138504         return TokenObject;
138505     }(TokenOrIdentifierObject));
138506     var IdentifierObject = /** @class */ (function (_super) {
138507         __extends(IdentifierObject, _super);
138508         function IdentifierObject(_kind, pos, end) {
138509             var _this = _super.call(this, pos, end) || this;
138510             _this.kind = 75 /* Identifier */;
138511             return _this;
138512         }
138513         Object.defineProperty(IdentifierObject.prototype, "text", {
138514             get: function () {
138515                 return ts.idText(this);
138516             },
138517             enumerable: false,
138518             configurable: true
138519         });
138520         return IdentifierObject;
138521     }(TokenOrIdentifierObject));
138522     IdentifierObject.prototype.kind = 75 /* Identifier */;
138523     var PrivateIdentifierObject = /** @class */ (function (_super) {
138524         __extends(PrivateIdentifierObject, _super);
138525         function PrivateIdentifierObject(_kind, pos, end) {
138526             return _super.call(this, pos, end) || this;
138527         }
138528         Object.defineProperty(PrivateIdentifierObject.prototype, "text", {
138529             get: function () {
138530                 return ts.idText(this);
138531             },
138532             enumerable: false,
138533             configurable: true
138534         });
138535         return PrivateIdentifierObject;
138536     }(TokenOrIdentifierObject));
138537     PrivateIdentifierObject.prototype.kind = 76 /* PrivateIdentifier */;
138538     var TypeObject = /** @class */ (function () {
138539         function TypeObject(checker, flags) {
138540             this.checker = checker;
138541             this.flags = flags;
138542         }
138543         TypeObject.prototype.getFlags = function () {
138544             return this.flags;
138545         };
138546         TypeObject.prototype.getSymbol = function () {
138547             return this.symbol;
138548         };
138549         TypeObject.prototype.getProperties = function () {
138550             return this.checker.getPropertiesOfType(this);
138551         };
138552         TypeObject.prototype.getProperty = function (propertyName) {
138553             return this.checker.getPropertyOfType(this, propertyName);
138554         };
138555         TypeObject.prototype.getApparentProperties = function () {
138556             return this.checker.getAugmentedPropertiesOfType(this);
138557         };
138558         TypeObject.prototype.getCallSignatures = function () {
138559             return this.checker.getSignaturesOfType(this, 0 /* Call */);
138560         };
138561         TypeObject.prototype.getConstructSignatures = function () {
138562             return this.checker.getSignaturesOfType(this, 1 /* Construct */);
138563         };
138564         TypeObject.prototype.getStringIndexType = function () {
138565             return this.checker.getIndexTypeOfType(this, 0 /* String */);
138566         };
138567         TypeObject.prototype.getNumberIndexType = function () {
138568             return this.checker.getIndexTypeOfType(this, 1 /* Number */);
138569         };
138570         TypeObject.prototype.getBaseTypes = function () {
138571             return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined;
138572         };
138573         TypeObject.prototype.isNullableType = function () {
138574             return this.checker.isNullableType(this);
138575         };
138576         TypeObject.prototype.getNonNullableType = function () {
138577             return this.checker.getNonNullableType(this);
138578         };
138579         TypeObject.prototype.getNonOptionalType = function () {
138580             return this.checker.getNonOptionalType(this);
138581         };
138582         TypeObject.prototype.getConstraint = function () {
138583             return this.checker.getBaseConstraintOfType(this);
138584         };
138585         TypeObject.prototype.getDefault = function () {
138586             return this.checker.getDefaultFromTypeParameter(this);
138587         };
138588         TypeObject.prototype.isUnion = function () {
138589             return !!(this.flags & 1048576 /* Union */);
138590         };
138591         TypeObject.prototype.isIntersection = function () {
138592             return !!(this.flags & 2097152 /* Intersection */);
138593         };
138594         TypeObject.prototype.isUnionOrIntersection = function () {
138595             return !!(this.flags & 3145728 /* UnionOrIntersection */);
138596         };
138597         TypeObject.prototype.isLiteral = function () {
138598             return !!(this.flags & 384 /* StringOrNumberLiteral */);
138599         };
138600         TypeObject.prototype.isStringLiteral = function () {
138601             return !!(this.flags & 128 /* StringLiteral */);
138602         };
138603         TypeObject.prototype.isNumberLiteral = function () {
138604             return !!(this.flags & 256 /* NumberLiteral */);
138605         };
138606         TypeObject.prototype.isTypeParameter = function () {
138607             return !!(this.flags & 262144 /* TypeParameter */);
138608         };
138609         TypeObject.prototype.isClassOrInterface = function () {
138610             return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */);
138611         };
138612         TypeObject.prototype.isClass = function () {
138613             return !!(ts.getObjectFlags(this) & 1 /* Class */);
138614         };
138615         Object.defineProperty(TypeObject.prototype, "typeArguments", {
138616             /**
138617              * This polyfills `referenceType.typeArguments` for API consumers
138618              */
138619             get: function () {
138620                 if (ts.getObjectFlags(this) & 4 /* Reference */) {
138621                     return this.checker.getTypeArguments(this);
138622                 }
138623                 return undefined;
138624             },
138625             enumerable: false,
138626             configurable: true
138627         });
138628         return TypeObject;
138629     }());
138630     var SignatureObject = /** @class */ (function () {
138631         function SignatureObject(checker, flags) {
138632             this.checker = checker;
138633             this.flags = flags;
138634         }
138635         SignatureObject.prototype.getDeclaration = function () {
138636             return this.declaration;
138637         };
138638         SignatureObject.prototype.getTypeParameters = function () {
138639             return this.typeParameters;
138640         };
138641         SignatureObject.prototype.getParameters = function () {
138642             return this.parameters;
138643         };
138644         SignatureObject.prototype.getReturnType = function () {
138645             return this.checker.getReturnTypeOfSignature(this);
138646         };
138647         SignatureObject.prototype.getDocumentationComment = function () {
138648             return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker));
138649         };
138650         SignatureObject.prototype.getJsDocTags = function () {
138651             if (this.jsDocTags === undefined) {
138652                 this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : [];
138653             }
138654             return this.jsDocTags;
138655         };
138656         return SignatureObject;
138657     }());
138658     /**
138659      * Returns whether or not the given node has a JSDoc "inheritDoc" tag on it.
138660      * @param node the Node in question.
138661      * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`.
138662      */
138663     function hasJSDocInheritDocTag(node) {
138664         return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; });
138665     }
138666     function getDocumentationComment(declarations, checker) {
138667         if (!declarations)
138668             return ts.emptyArray;
138669         var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
138670         if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
138671             ts.forEachUnique(declarations, function (declaration) {
138672                 var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
138673                 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
138674                 if (inheritedDocs)
138675                     doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc);
138676             });
138677         }
138678         return doc;
138679     }
138680     /**
138681      * Attempts to find JSDoc comments for possibly-inherited properties.  Checks superclasses then traverses
138682      * implemented interfaces until a symbol is found with the same name and with documentation.
138683      * @param declaration The possibly-inherited declaration to find comments for.
138684      * @param propertyName The name of the possibly-inherited property.
138685      * @param typeChecker A TypeChecker, used to find inherited properties.
138686      * @returns A filled array of documentation comments if any were found, otherwise an empty array.
138687      */
138688     function findInheritedJSDocComments(declaration, propertyName, typeChecker) {
138689         return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) {
138690             var superType = typeChecker.getTypeAtLocation(superTypeNode);
138691             var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName);
138692             var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker);
138693             return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined;
138694         });
138695     }
138696     var SourceFileObject = /** @class */ (function (_super) {
138697         __extends(SourceFileObject, _super);
138698         function SourceFileObject(kind, pos, end) {
138699             var _this = _super.call(this, kind, pos, end) || this;
138700             _this.kind = 290 /* SourceFile */;
138701             return _this;
138702         }
138703         SourceFileObject.prototype.update = function (newText, textChangeRange) {
138704             return ts.updateSourceFile(this, newText, textChangeRange);
138705         };
138706         SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) {
138707             return ts.getLineAndCharacterOfPosition(this, position);
138708         };
138709         SourceFileObject.prototype.getLineStarts = function () {
138710             return ts.getLineStarts(this);
138711         };
138712         SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) {
138713             return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits);
138714         };
138715         SourceFileObject.prototype.getLineEndOfPosition = function (pos) {
138716             var line = this.getLineAndCharacterOfPosition(pos).line;
138717             var lineStarts = this.getLineStarts();
138718             var lastCharPos;
138719             if (line + 1 >= lineStarts.length) {
138720                 lastCharPos = this.getEnd();
138721             }
138722             if (!lastCharPos) {
138723                 lastCharPos = lineStarts[line + 1] - 1;
138724             }
138725             var fullText = this.getFullText();
138726             // if the new line is "\r\n", we should return the last non-new-line-character position
138727             return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos;
138728         };
138729         SourceFileObject.prototype.getNamedDeclarations = function () {
138730             if (!this.namedDeclarations) {
138731                 this.namedDeclarations = this.computeNamedDeclarations();
138732             }
138733             return this.namedDeclarations;
138734         };
138735         SourceFileObject.prototype.computeNamedDeclarations = function () {
138736             var result = ts.createMultiMap();
138737             this.forEachChild(visit);
138738             return result;
138739             function addDeclaration(declaration) {
138740                 var name = getDeclarationName(declaration);
138741                 if (name) {
138742                     result.add(name, declaration);
138743                 }
138744             }
138745             function getDeclarations(name) {
138746                 var declarations = result.get(name);
138747                 if (!declarations) {
138748                     result.set(name, declarations = []);
138749                 }
138750                 return declarations;
138751             }
138752             function getDeclarationName(declaration) {
138753                 var name = ts.getNonAssignedNameOfDeclaration(declaration);
138754                 return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text
138755                     : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined);
138756             }
138757             function visit(node) {
138758                 switch (node.kind) {
138759                     case 244 /* FunctionDeclaration */:
138760                     case 201 /* FunctionExpression */:
138761                     case 161 /* MethodDeclaration */:
138762                     case 160 /* MethodSignature */:
138763                         var functionDeclaration = node;
138764                         var declarationName = getDeclarationName(functionDeclaration);
138765                         if (declarationName) {
138766                             var declarations = getDeclarations(declarationName);
138767                             var lastDeclaration = ts.lastOrUndefined(declarations);
138768                             // Check whether this declaration belongs to an "overload group".
138769                             if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
138770                                 // Overwrite the last declaration if it was an overload
138771                                 // and this one is an implementation.
138772                                 if (functionDeclaration.body && !lastDeclaration.body) {
138773                                     declarations[declarations.length - 1] = functionDeclaration;
138774                                 }
138775                             }
138776                             else {
138777                                 declarations.push(functionDeclaration);
138778                             }
138779                         }
138780                         ts.forEachChild(node, visit);
138781                         break;
138782                     case 245 /* ClassDeclaration */:
138783                     case 214 /* ClassExpression */:
138784                     case 246 /* InterfaceDeclaration */:
138785                     case 247 /* TypeAliasDeclaration */:
138786                     case 248 /* EnumDeclaration */:
138787                     case 249 /* ModuleDeclaration */:
138788                     case 253 /* ImportEqualsDeclaration */:
138789                     case 263 /* ExportSpecifier */:
138790                     case 258 /* ImportSpecifier */:
138791                     case 255 /* ImportClause */:
138792                     case 256 /* NamespaceImport */:
138793                     case 163 /* GetAccessor */:
138794                     case 164 /* SetAccessor */:
138795                     case 173 /* TypeLiteral */:
138796                         addDeclaration(node);
138797                         ts.forEachChild(node, visit);
138798                         break;
138799                     case 156 /* Parameter */:
138800                         // Only consider parameter properties
138801                         if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
138802                             break;
138803                         }
138804                     // falls through
138805                     case 242 /* VariableDeclaration */:
138806                     case 191 /* BindingElement */: {
138807                         var decl = node;
138808                         if (ts.isBindingPattern(decl.name)) {
138809                             ts.forEachChild(decl.name, visit);
138810                             break;
138811                         }
138812                         if (decl.initializer) {
138813                             visit(decl.initializer);
138814                         }
138815                     }
138816                     // falls through
138817                     case 284 /* EnumMember */:
138818                     case 159 /* PropertyDeclaration */:
138819                     case 158 /* PropertySignature */:
138820                         addDeclaration(node);
138821                         break;
138822                     case 260 /* ExportDeclaration */:
138823                         // Handle named exports case e.g.:
138824                         //    export {a, b as B} from "mod";
138825                         var exportDeclaration = node;
138826                         if (exportDeclaration.exportClause) {
138827                             if (ts.isNamedExports(exportDeclaration.exportClause)) {
138828                                 ts.forEach(exportDeclaration.exportClause.elements, visit);
138829                             }
138830                             else {
138831                                 visit(exportDeclaration.exportClause.name);
138832                             }
138833                         }
138834                         break;
138835                     case 254 /* ImportDeclaration */:
138836                         var importClause = node.importClause;
138837                         if (importClause) {
138838                             // Handle default import case e.g.:
138839                             //    import d from "mod";
138840                             if (importClause.name) {
138841                                 addDeclaration(importClause.name);
138842                             }
138843                             // Handle named bindings in imports e.g.:
138844                             //    import * as NS from "mod";
138845                             //    import {a, b as B} from "mod";
138846                             if (importClause.namedBindings) {
138847                                 if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
138848                                     addDeclaration(importClause.namedBindings);
138849                                 }
138850                                 else {
138851                                     ts.forEach(importClause.namedBindings.elements, visit);
138852                                 }
138853                             }
138854                         }
138855                         break;
138856                     case 209 /* BinaryExpression */:
138857                         if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) {
138858                             addDeclaration(node);
138859                         }
138860                     // falls through
138861                     default:
138862                         ts.forEachChild(node, visit);
138863                 }
138864             }
138865         };
138866         return SourceFileObject;
138867     }(NodeObject));
138868     var SourceMapSourceObject = /** @class */ (function () {
138869         function SourceMapSourceObject(fileName, text, skipTrivia) {
138870             this.fileName = fileName;
138871             this.text = text;
138872             this.skipTrivia = skipTrivia;
138873         }
138874         SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) {
138875             return ts.getLineAndCharacterOfPosition(this, pos);
138876         };
138877         return SourceMapSourceObject;
138878     }());
138879     function getServicesObjectAllocator() {
138880         return {
138881             getNodeConstructor: function () { return NodeObject; },
138882             getTokenConstructor: function () { return TokenObject; },
138883             getIdentifierConstructor: function () { return IdentifierObject; },
138884             getPrivateIdentifierConstructor: function () { return PrivateIdentifierObject; },
138885             getSourceFileConstructor: function () { return SourceFileObject; },
138886             getSymbolConstructor: function () { return SymbolObject; },
138887             getTypeConstructor: function () { return TypeObject; },
138888             getSignatureConstructor: function () { return SignatureObject; },
138889             getSourceMapSourceConstructor: function () { return SourceMapSourceObject; },
138890         };
138891     }
138892     function toEditorSettings(optionsAsMap) {
138893         var allPropertiesAreCamelCased = true;
138894         for (var key in optionsAsMap) {
138895             if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) {
138896                 allPropertiesAreCamelCased = false;
138897                 break;
138898             }
138899         }
138900         if (allPropertiesAreCamelCased) {
138901             return optionsAsMap;
138902         }
138903         var settings = {};
138904         for (var key in optionsAsMap) {
138905             if (ts.hasProperty(optionsAsMap, key)) {
138906                 var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1);
138907                 settings[newKey] = optionsAsMap[key];
138908             }
138909         }
138910         return settings;
138911     }
138912     ts.toEditorSettings = toEditorSettings;
138913     function isCamelCase(s) {
138914         return !s.length || s.charAt(0) === s.charAt(0).toLowerCase();
138915     }
138916     function displayPartsToString(displayParts) {
138917         if (displayParts) {
138918             return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join("");
138919         }
138920         return "";
138921     }
138922     ts.displayPartsToString = displayPartsToString;
138923     function getDefaultCompilerOptions() {
138924         // Always default to "ScriptTarget.ES5" for the language service
138925         return {
138926             target: 1 /* ES5 */,
138927             jsx: 1 /* Preserve */
138928         };
138929     }
138930     ts.getDefaultCompilerOptions = getDefaultCompilerOptions;
138931     function getSupportedCodeFixes() {
138932         return ts.codefix.getSupportedErrorCodes();
138933     }
138934     ts.getSupportedCodeFixes = getSupportedCodeFixes;
138935     // Cache host information about script Should be refreshed
138936     // at each language service public entry point, since we don't know when
138937     // the set of scripts handled by the host changes.
138938     var HostCache = /** @class */ (function () {
138939         function HostCache(host, getCanonicalFileName) {
138940             this.host = host;
138941             // script id => script index
138942             this.currentDirectory = host.getCurrentDirectory();
138943             this.fileNameToEntry = ts.createMap();
138944             // Initialize the list with the root file names
138945             var rootFileNames = host.getScriptFileNames();
138946             for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
138947                 var fileName = rootFileNames_1[_i];
138948                 this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName));
138949             }
138950             // store the compilation settings
138951             this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions();
138952         }
138953         HostCache.prototype.compilationSettings = function () {
138954             return this._compilationSettings;
138955         };
138956         HostCache.prototype.getProjectReferences = function () {
138957             return this.host.getProjectReferences && this.host.getProjectReferences();
138958         };
138959         HostCache.prototype.createEntry = function (fileName, path) {
138960             var entry;
138961             var scriptSnapshot = this.host.getScriptSnapshot(fileName);
138962             if (scriptSnapshot) {
138963                 entry = {
138964                     hostFileName: fileName,
138965                     version: this.host.getScriptVersion(fileName),
138966                     scriptSnapshot: scriptSnapshot,
138967                     scriptKind: ts.getScriptKind(fileName, this.host)
138968                 };
138969             }
138970             else {
138971                 entry = fileName;
138972             }
138973             this.fileNameToEntry.set(path, entry);
138974             return entry;
138975         };
138976         HostCache.prototype.getEntryByPath = function (path) {
138977             return this.fileNameToEntry.get(path);
138978         };
138979         HostCache.prototype.getHostFileInformation = function (path) {
138980             var entry = this.fileNameToEntry.get(path);
138981             return !ts.isString(entry) ? entry : undefined;
138982         };
138983         HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) {
138984             var info = this.getEntryByPath(path) || this.createEntry(fileName, path);
138985             return ts.isString(info) ? undefined : info; // TODO: GH#18217
138986         };
138987         HostCache.prototype.getRootFileNames = function () {
138988             var names = [];
138989             this.fileNameToEntry.forEach(function (entry) {
138990                 if (ts.isString(entry)) {
138991                     names.push(entry);
138992                 }
138993                 else {
138994                     names.push(entry.hostFileName);
138995                 }
138996             });
138997             return names;
138998         };
138999         HostCache.prototype.getScriptSnapshot = function (path) {
139000             var file = this.getHostFileInformation(path);
139001             return (file && file.scriptSnapshot); // TODO: GH#18217
139002         };
139003         return HostCache;
139004     }());
139005     var SyntaxTreeCache = /** @class */ (function () {
139006         function SyntaxTreeCache(host) {
139007             this.host = host;
139008         }
139009         SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) {
139010             var scriptSnapshot = this.host.getScriptSnapshot(fileName);
139011             if (!scriptSnapshot) {
139012                 // The host does not know about this file.
139013                 throw new Error("Could not find file: '" + fileName + "'.");
139014             }
139015             var scriptKind = ts.getScriptKind(fileName, this.host);
139016             var version = this.host.getScriptVersion(fileName);
139017             var sourceFile;
139018             if (this.currentFileName !== fileName) {
139019                 // This is a new file, just parse it
139020                 sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 99 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
139021             }
139022             else if (this.currentFileVersion !== version) {
139023                 // This is the same file, just a newer version. Incrementally parse the file.
139024                 var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot);
139025                 sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange);
139026             }
139027             if (sourceFile) {
139028                 // All done, ensure state is up to date
139029                 this.currentFileVersion = version;
139030                 this.currentFileName = fileName;
139031                 this.currentFileScriptSnapshot = scriptSnapshot;
139032                 this.currentSourceFile = sourceFile;
139033             }
139034             return this.currentSourceFile;
139035         };
139036         return SyntaxTreeCache;
139037     }());
139038     function setSourceFileFields(sourceFile, scriptSnapshot, version) {
139039         sourceFile.version = version;
139040         sourceFile.scriptSnapshot = scriptSnapshot;
139041     }
139042     function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) {
139043         var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind);
139044         setSourceFileFields(sourceFile, scriptSnapshot, version);
139045         return sourceFile;
139046     }
139047     ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile;
139048     function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) {
139049         // If we were given a text change range, and our version or open-ness changed, then
139050         // incrementally parse this file.
139051         if (textChangeRange) {
139052             if (version !== sourceFile.version) {
139053                 var newText = void 0;
139054                 // grab the fragment from the beginning of the original text to the beginning of the span
139055                 var prefix = textChangeRange.span.start !== 0
139056                     ? sourceFile.text.substr(0, textChangeRange.span.start)
139057                     : "";
139058                 // grab the fragment from the end of the span till the end of the original text
139059                 var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length
139060                     ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span))
139061                     : "";
139062                 if (textChangeRange.newLength === 0) {
139063                     // edit was a deletion - just combine prefix and suffix
139064                     newText = prefix && suffix ? prefix + suffix : prefix || suffix;
139065                 }
139066                 else {
139067                     // it was actual edit, fetch the fragment of new text that correspond to new span
139068                     var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength);
139069                     // combine prefix, changed text and suffix
139070                     newText = prefix && suffix
139071                         ? prefix + changedText + suffix
139072                         : prefix
139073                             ? (prefix + changedText)
139074                             : (changedText + suffix);
139075                 }
139076                 var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
139077                 setSourceFileFields(newSourceFile, scriptSnapshot, version);
139078                 // after incremental parsing nameTable might not be up-to-date
139079                 // drop it so it can be lazily recreated later
139080                 newSourceFile.nameTable = undefined;
139081                 // dispose all resources held by old script snapshot
139082                 if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) {
139083                     if (sourceFile.scriptSnapshot.dispose) {
139084                         sourceFile.scriptSnapshot.dispose();
139085                     }
139086                     sourceFile.scriptSnapshot = undefined;
139087                 }
139088                 return newSourceFile;
139089             }
139090         }
139091         // Otherwise, just create a new source file.
139092         return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind);
139093     }
139094     ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile;
139095     var CancellationTokenObject = /** @class */ (function () {
139096         function CancellationTokenObject(cancellationToken) {
139097             this.cancellationToken = cancellationToken;
139098         }
139099         CancellationTokenObject.prototype.isCancellationRequested = function () {
139100             return !!this.cancellationToken && this.cancellationToken.isCancellationRequested();
139101         };
139102         CancellationTokenObject.prototype.throwIfCancellationRequested = function () {
139103             if (this.isCancellationRequested()) {
139104                 throw new ts.OperationCanceledException();
139105             }
139106         };
139107         return CancellationTokenObject;
139108     }());
139109     /* @internal */
139110     /** A cancellation that throttles calls to the host */
139111     var ThrottledCancellationToken = /** @class */ (function () {
139112         function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) {
139113             if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; }
139114             this.hostCancellationToken = hostCancellationToken;
139115             this.throttleWaitMilliseconds = throttleWaitMilliseconds;
139116             // Store when we last tried to cancel.  Checking cancellation can be expensive (as we have
139117             // to marshall over to the host layer).  So we only bother actually checking once enough
139118             // time has passed.
139119             this.lastCancellationCheckTime = 0;
139120         }
139121         ThrottledCancellationToken.prototype.isCancellationRequested = function () {
139122             var time = ts.timestamp();
139123             var duration = Math.abs(time - this.lastCancellationCheckTime);
139124             if (duration >= this.throttleWaitMilliseconds) {
139125                 // Check no more than once every throttle wait milliseconds
139126                 this.lastCancellationCheckTime = time;
139127                 return this.hostCancellationToken.isCancellationRequested();
139128             }
139129             return false;
139130         };
139131         ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () {
139132             if (this.isCancellationRequested()) {
139133                 throw new ts.OperationCanceledException();
139134             }
139135         };
139136         return ThrottledCancellationToken;
139137     }());
139138     ts.ThrottledCancellationToken = ThrottledCancellationToken;
139139     function createLanguageService(host, documentRegistry, syntaxOnly) {
139140         var _a;
139141         if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
139142         if (syntaxOnly === void 0) { syntaxOnly = false; }
139143         var syntaxTreeCache = new SyntaxTreeCache(host);
139144         var program;
139145         var lastProjectVersion;
139146         var lastTypesRootVersion = 0;
139147         var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken());
139148         var currentDirectory = host.getCurrentDirectory();
139149         // Check if the localized messages json is set, otherwise query the host for it
139150         if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) {
139151             ts.setLocalizedDiagnosticMessages(host.getLocalizedDiagnosticMessages());
139152         }
139153         function log(message) {
139154             if (host.log) {
139155                 host.log(message);
139156             }
139157         }
139158         var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host);
139159         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
139160         var sourceMapper = ts.getSourceMapper({
139161             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
139162             getCurrentDirectory: function () { return currentDirectory; },
139163             getProgram: getProgram,
139164             fileExists: ts.maybeBind(host, host.fileExists),
139165             readFile: ts.maybeBind(host, host.readFile),
139166             getDocumentPositionMapper: ts.maybeBind(host, host.getDocumentPositionMapper),
139167             getSourceFileLike: ts.maybeBind(host, host.getSourceFileLike),
139168             log: log
139169         });
139170         function getValidSourceFile(fileName) {
139171             var sourceFile = program.getSourceFile(fileName);
139172             if (!sourceFile) {
139173                 var error = new Error("Could not find source file: '" + fileName + "'.");
139174                 // We've been having trouble debugging this, so attach sidecar data for the tsserver log.
139175                 // See https://github.com/microsoft/TypeScript/issues/30180.
139176                 error.ProgramFiles = program.getSourceFiles().map(function (f) { return f.fileName; });
139177                 throw error;
139178             }
139179             return sourceFile;
139180         }
139181         function synchronizeHostData() {
139182             var _a;
139183             ts.Debug.assert(!syntaxOnly);
139184             // perform fast check if host supports it
139185             if (host.getProjectVersion) {
139186                 var hostProjectVersion = host.getProjectVersion();
139187                 if (hostProjectVersion) {
139188                     if (lastProjectVersion === hostProjectVersion && !host.hasChangedAutomaticTypeDirectiveNames) {
139189                         return;
139190                     }
139191                     lastProjectVersion = hostProjectVersion;
139192                 }
139193             }
139194             var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0;
139195             if (lastTypesRootVersion !== typeRootsVersion) {
139196                 log("TypeRoots version has changed; provide new program");
139197                 program = undefined; // TODO: GH#18217
139198                 lastTypesRootVersion = typeRootsVersion;
139199             }
139200             // Get a fresh cache of the host information
139201             var hostCache = new HostCache(host, getCanonicalFileName);
139202             var rootFileNames = hostCache.getRootFileNames();
139203             var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
139204             var projectReferences = hostCache.getProjectReferences();
139205             // If the program is already up-to-date, we can reuse it
139206             if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
139207                 return;
139208             }
139209             // IMPORTANT - It is critical from this moment onward that we do not check
139210             // cancellation tokens.  We are about to mutate source files from a previous program
139211             // instance.  If we cancel midway through, we may end up in an inconsistent state where
139212             // the program points to old source files that have been invalidated because of
139213             // incremental parsing.
139214             var newSettings = hostCache.compilationSettings();
139215             // Now create a new compiler
139216             var compilerHost = {
139217                 getSourceFile: getOrCreateSourceFile,
139218                 getSourceFileByPath: getOrCreateSourceFileByPath,
139219                 getCancellationToken: function () { return cancellationToken; },
139220                 getCanonicalFileName: getCanonicalFileName,
139221                 useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
139222                 getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); },
139223                 getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
139224                 writeFile: ts.noop,
139225                 getCurrentDirectory: function () { return currentDirectory; },
139226                 fileExists: fileExists,
139227                 readFile: readFile,
139228                 realpath: host.realpath && (function (path) { return host.realpath(path); }),
139229                 directoryExists: function (directoryName) {
139230                     return ts.directoryProbablyExists(directoryName, host);
139231                 },
139232                 getDirectories: function (path) {
139233                     return host.getDirectories ? host.getDirectories(path) : [];
139234                 },
139235                 readDirectory: function (path, extensions, exclude, include, depth) {
139236                     ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
139237                     return host.readDirectory(path, extensions, exclude, include, depth);
139238                 },
139239                 onReleaseOldSourceFile: onReleaseOldSourceFile,
139240                 hasInvalidatedResolution: hasInvalidatedResolution,
139241                 hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames
139242             };
139243             if (host.trace) {
139244                 compilerHost.trace = function (message) { return host.trace(message); };
139245             }
139246             if (host.resolveModuleNames) {
139247                 compilerHost.resolveModuleNames = function () {
139248                     var args = [];
139249                     for (var _i = 0; _i < arguments.length; _i++) {
139250                         args[_i] = arguments[_i];
139251                     }
139252                     return host.resolveModuleNames.apply(host, args);
139253                 };
139254             }
139255             if (host.resolveTypeReferenceDirectives) {
139256                 compilerHost.resolveTypeReferenceDirectives = function () {
139257                     var args = [];
139258                     for (var _i = 0; _i < arguments.length; _i++) {
139259                         args[_i] = arguments[_i];
139260                     }
139261                     return host.resolveTypeReferenceDirectives.apply(host, args);
139262                 };
139263             }
139264             if (host.useSourceOfProjectReferenceRedirect) {
139265                 compilerHost.useSourceOfProjectReferenceRedirect = function () { return host.useSourceOfProjectReferenceRedirect(); };
139266             }
139267             (_a = host.setCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host, compilerHost);
139268             var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
139269             var options = {
139270                 rootNames: rootFileNames,
139271                 options: newSettings,
139272                 host: compilerHost,
139273                 oldProgram: program,
139274                 projectReferences: projectReferences
139275             };
139276             program = ts.createProgram(options);
139277             // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
139278             // It needs to be cleared to allow all collected snapshots to be released
139279             hostCache = undefined;
139280             // 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,
139281             // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during
139282             // the course of whatever called `synchronizeHostData`
139283             sourceMapper.clearCache();
139284             // Make sure all the nodes in the program are both bound, and have their parent
139285             // pointers set property.
139286             program.getTypeChecker();
139287             return;
139288             function fileExists(fileName) {
139289                 var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
139290                 var entry = hostCache && hostCache.getEntryByPath(path);
139291                 return entry ?
139292                     !ts.isString(entry) :
139293                     (!!host.fileExists && host.fileExists(fileName));
139294             }
139295             function readFile(fileName) {
139296                 // stub missing host functionality
139297                 var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
139298                 var entry = hostCache && hostCache.getEntryByPath(path);
139299                 if (entry) {
139300                     return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot);
139301                 }
139302                 return host.readFile && host.readFile(fileName);
139303             }
139304             // Release any files we have acquired in the old program but are
139305             // not part of the new program.
139306             function onReleaseOldSourceFile(oldSourceFile, oldOptions) {
139307                 var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions);
139308                 documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey);
139309             }
139310             function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
139311                 return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile);
139312             }
139313             function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) {
139314                 ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
139315                 // The program is asking for this file, check first if the host can locate it.
139316                 // If the host can not locate the file, then it does not exist. return undefined
139317                 // to the program to allow reporting of errors for missing files.
139318                 var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path);
139319                 if (!hostFileInformation) {
139320                     return undefined;
139321                 }
139322                 // Check if the language version has changed since we last created a program; if they are the same,
139323                 // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile
139324                 // can not be reused. we have to dump all syntax trees and create new ones.
139325                 if (!shouldCreateNewSourceFile) {
139326                     // Check if the old program had this file already
139327                     var oldSourceFile = program && program.getSourceFileByPath(path);
139328                     if (oldSourceFile) {
139329                         // We already had a source file for this file name.  Go to the registry to
139330                         // ensure that we get the right up to date version of it.  We need this to
139331                         // address the following race-condition.  Specifically, say we have the following:
139332                         //
139333                         //      LS1
139334                         //          \
139335                         //           DocumentRegistry
139336                         //          /
139337                         //      LS2
139338                         //
139339                         // Each LS has a reference to file 'foo.ts' at version 1.  LS2 then updates
139340                         // it's version of 'foo.ts' to version 2.  This will cause LS2 and the
139341                         // DocumentRegistry to have version 2 of the document.  HOwever, LS1 will
139342                         // have version 1.  And *importantly* this source file will be *corrupt*.
139343                         // The act of creating version 2 of the file irrevocably damages the version
139344                         // 1 file.
139345                         //
139346                         // So, later when we call into LS1, we need to make sure that it doesn't use
139347                         // it's source file any more, and instead defers to DocumentRegistry to get
139348                         // either version 1, version 2 (or some other version) depending on what the
139349                         // host says should be used.
139350                         // We do not support the scenario where a host can modify a registered
139351                         // file's script kind, i.e. in one project some file is treated as ".ts"
139352                         // and in another as ".js"
139353                         ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.");
139354                         return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
139355                     }
139356                     // We didn't already have the file.  Fall through and acquire it from the registry.
139357                 }
139358                 // Could not find this file in the old program, create a new SourceFile for it.
139359                 return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
139360             }
139361         }
139362         // TODO: GH#18217 frequently asserted as defined
139363         function getProgram() {
139364             if (syntaxOnly) {
139365                 ts.Debug.assert(program === undefined);
139366                 return undefined;
139367             }
139368             synchronizeHostData();
139369             return program;
139370         }
139371         function cleanupSemanticCache() {
139372             program = undefined; // TODO: GH#18217
139373         }
139374         function dispose() {
139375             if (program) {
139376                 // Use paths to ensure we are using correct key and paths as document registry could bre created with different current directory than host
139377                 var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions());
139378                 ts.forEach(program.getSourceFiles(), function (f) {
139379                     return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1);
139380                 });
139381                 program = undefined; // TODO: GH#18217
139382             }
139383             host = undefined;
139384         }
139385         /// Diagnostics
139386         function getSyntacticDiagnostics(fileName) {
139387             synchronizeHostData();
139388             return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice();
139389         }
139390         /**
139391          * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors
139392          * If '-d' enabled, report both semantic and emitter errors
139393          */
139394         function getSemanticDiagnostics(fileName) {
139395             synchronizeHostData();
139396             var targetSourceFile = getValidSourceFile(fileName);
139397             // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.
139398             // Therefore only get diagnostics for given file.
139399             var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);
139400             if (!ts.getEmitDeclarations(program.getCompilerOptions())) {
139401                 return semanticDiagnostics.slice();
139402             }
139403             // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
139404             var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);
139405             return __spreadArrays(semanticDiagnostics, declarationDiagnostics);
139406         }
139407         function getSuggestionDiagnostics(fileName) {
139408             synchronizeHostData();
139409             return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken);
139410         }
139411         function getCompilerOptionsDiagnostics() {
139412             synchronizeHostData();
139413             return __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken));
139414         }
139415         function getCompletionsAtPosition(fileName, position, options) {
139416             if (options === void 0) { options = ts.emptyOptions; }
139417             // Convert from deprecated options names to new names
139418             var fullPreferences = __assign(__assign({}, ts.identity(options)), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions });
139419             synchronizeHostData();
139420             return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter);
139421         }
139422         function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) {
139423             if (preferences === void 0) { preferences = ts.emptyOptions; }
139424             synchronizeHostData();
139425             return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217
139426             preferences, cancellationToken);
139427         }
139428         function getCompletionEntrySymbol(fileName, position, name, source, preferences) {
139429             if (preferences === void 0) { preferences = ts.emptyOptions; }
139430             synchronizeHostData();
139431             return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, preferences);
139432         }
139433         function getQuickInfoAtPosition(fileName, position) {
139434             synchronizeHostData();
139435             var sourceFile = getValidSourceFile(fileName);
139436             var node = ts.getTouchingPropertyName(sourceFile, position);
139437             if (node === sourceFile) {
139438                 // Avoid giving quickInfo for the sourceFile as a whole.
139439                 return undefined;
139440             }
139441             var typeChecker = program.getTypeChecker();
139442             var nodeForQuickInfo = getNodeForQuickInfo(node);
139443             var symbol = getSymbolAtLocationForQuickInfo(nodeForQuickInfo, typeChecker);
139444             if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
139445                 var type_2 = shouldGetType(sourceFile, nodeForQuickInfo, position) ? typeChecker.getTypeAtLocation(nodeForQuickInfo) : undefined;
139446                 return type_2 && {
139447                     kind: "" /* unknown */,
139448                     kindModifiers: "" /* none */,
139449                     textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
139450                     displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }),
139451                     documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined,
139452                     tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined
139453                 };
139454             }
139455             var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
139456                 return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(nodeForQuickInfo), nodeForQuickInfo);
139457             }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags;
139458             return {
139459                 kind: symbolKind,
139460                 kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
139461                 textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile),
139462                 displayParts: displayParts,
139463                 documentation: documentation,
139464                 tags: tags,
139465             };
139466         }
139467         function getNodeForQuickInfo(node) {
139468             if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) {
139469                 return node.parent.expression;
139470             }
139471             return node;
139472         }
139473         function shouldGetType(sourceFile, node, position) {
139474             switch (node.kind) {
139475                 case 75 /* Identifier */:
139476                     return !ts.isLabelName(node) && !ts.isTagName(node);
139477                 case 194 /* PropertyAccessExpression */:
139478                 case 153 /* QualifiedName */:
139479                     // Don't return quickInfo if inside the comment in `a/**/.b`
139480                     return !ts.isInComment(sourceFile, position);
139481                 case 104 /* ThisKeyword */:
139482                 case 183 /* ThisType */:
139483                 case 102 /* SuperKeyword */:
139484                     return true;
139485                 default:
139486                     return false;
139487             }
139488         }
139489         /// Goto definition
139490         function getDefinitionAtPosition(fileName, position) {
139491             synchronizeHostData();
139492             return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position);
139493         }
139494         function getDefinitionAndBoundSpan(fileName, position) {
139495             synchronizeHostData();
139496             return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position);
139497         }
139498         function getTypeDefinitionAtPosition(fileName, position) {
139499             synchronizeHostData();
139500             return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
139501         }
139502         /// Goto implementation
139503         function getImplementationAtPosition(fileName, position) {
139504             synchronizeHostData();
139505             return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
139506         }
139507         /// References and Occurrences
139508         function getOccurrencesAtPosition(fileName, position) {
139509             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 })); }); });
139510         }
139511         function getDocumentHighlights(fileName, position, filesToSearch) {
139512             var normalizedFileName = ts.normalizePath(fileName);
139513             ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; }));
139514             synchronizeHostData();
139515             var sourceFilesToSearch = ts.mapDefined(filesToSearch, function (fileName) { return program.getSourceFile(fileName); });
139516             var sourceFile = getValidSourceFile(fileName);
139517             return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
139518         }
139519         function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) {
139520             synchronizeHostData();
139521             var sourceFile = getValidSourceFile(fileName);
139522             var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position));
139523             if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) {
139524                 var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
139525                 return [openingElement, closingElement].map(function (node) {
139526                     var textSpan = ts.createTextSpanFromNode(node.tagName, sourceFile);
139527                     return __assign({ fileName: sourceFile.fileName, textSpan: textSpan }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, node.parent));
139528                 });
139529             }
139530             else {
139531                 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); });
139532             }
139533         }
139534         function getReferencesAtPosition(fileName, position) {
139535             synchronizeHostData();
139536             return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: 1 /* References */ }, ts.FindAllReferences.toReferenceEntry);
139537         }
139538         function getReferencesWorker(node, position, options, cb) {
139539             synchronizeHostData();
139540             // Exclude default library when renaming as commonly user don't want to change that file.
139541             var sourceFiles = options && options.use === 2 /* Rename */
139542                 ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); })
139543                 : program.getSourceFiles();
139544             return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb);
139545         }
139546         function findReferences(fileName, position) {
139547             synchronizeHostData();
139548             return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
139549         }
139550         function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
139551             if (excludeDtsFiles === void 0) { excludeDtsFiles = false; }
139552             synchronizeHostData();
139553             var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles();
139554             return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
139555         }
139556         function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) {
139557             synchronizeHostData();
139558             var sourceFile = getValidSourceFile(fileName);
139559             var customTransformers = host.getCustomTransformers && host.getCustomTransformers();
139560             return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit);
139561         }
139562         // Signature help
139563         /**
139564          * This is a semantic operation.
139565          */
139566         function getSignatureHelpItems(fileName, position, _a) {
139567             var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason;
139568             synchronizeHostData();
139569             var sourceFile = getValidSourceFile(fileName);
139570             return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
139571         }
139572         /// Syntactic features
139573         function getNonBoundSourceFile(fileName) {
139574             return syntaxTreeCache.getCurrentSourceFile(fileName);
139575         }
139576         function getNameOrDottedNameSpan(fileName, startPos, _endPos) {
139577             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139578             // Get node at the location
139579             var node = ts.getTouchingPropertyName(sourceFile, startPos);
139580             if (node === sourceFile) {
139581                 return undefined;
139582             }
139583             switch (node.kind) {
139584                 case 194 /* PropertyAccessExpression */:
139585                 case 153 /* QualifiedName */:
139586                 case 10 /* StringLiteral */:
139587                 case 91 /* FalseKeyword */:
139588                 case 106 /* TrueKeyword */:
139589                 case 100 /* NullKeyword */:
139590                 case 102 /* SuperKeyword */:
139591                 case 104 /* ThisKeyword */:
139592                 case 183 /* ThisType */:
139593                 case 75 /* Identifier */:
139594                     break;
139595                 // Cant create the text span
139596                 default:
139597                     return undefined;
139598             }
139599             var nodeForStartPos = node;
139600             while (true) {
139601                 if (ts.isRightSideOfPropertyAccess(nodeForStartPos) || ts.isRightSideOfQualifiedName(nodeForStartPos)) {
139602                     // 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
139603                     nodeForStartPos = nodeForStartPos.parent;
139604                 }
139605                 else if (ts.isNameOfModuleDeclaration(nodeForStartPos)) {
139606                     // If this is name of a module declarations, check if this is right side of dotted module name
139607                     // 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
139608                     // Then this name is name from dotted module
139609                     if (nodeForStartPos.parent.parent.kind === 249 /* ModuleDeclaration */ &&
139610                         nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
139611                         // Use parent module declarations name for start pos
139612                         nodeForStartPos = nodeForStartPos.parent.parent.name;
139613                     }
139614                     else {
139615                         // We have to use this name for start pos
139616                         break;
139617                     }
139618                 }
139619                 else {
139620                     // Is not a member expression so we have found the node for start pos
139621                     break;
139622                 }
139623             }
139624             return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd());
139625         }
139626         function getBreakpointStatementAtPosition(fileName, position) {
139627             // doesn't use compiler - no need to synchronize with host
139628             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139629             return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position);
139630         }
139631         function getNavigationBarItems(fileName) {
139632             return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
139633         }
139634         function getNavigationTree(fileName) {
139635             return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
139636         }
139637         function isTsOrTsxFile(fileName) {
139638             var kind = ts.getScriptKind(fileName, host);
139639             return kind === 3 /* TS */ || kind === 4 /* TSX */;
139640         }
139641         function getSemanticClassifications(fileName, span) {
139642             if (!isTsOrTsxFile(fileName)) {
139643                 // do not run semantic classification on non-ts-or-tsx files
139644                 return [];
139645             }
139646             synchronizeHostData();
139647             return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
139648         }
139649         function getEncodedSemanticClassifications(fileName, span) {
139650             if (!isTsOrTsxFile(fileName)) {
139651                 // do not run semantic classification on non-ts-or-tsx files
139652                 return { spans: [], endOfLineState: 0 /* None */ };
139653             }
139654             synchronizeHostData();
139655             return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span);
139656         }
139657         function getSyntacticClassifications(fileName, span) {
139658             // doesn't use compiler - no need to synchronize with host
139659             return ts.getSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
139660         }
139661         function getEncodedSyntacticClassifications(fileName, span) {
139662             // doesn't use compiler - no need to synchronize with host
139663             return ts.getEncodedSyntacticClassifications(cancellationToken, syntaxTreeCache.getCurrentSourceFile(fileName), span);
139664         }
139665         function getOutliningSpans(fileName) {
139666             // doesn't use compiler - no need to synchronize with host
139667             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139668             return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken);
139669         }
139670         var braceMatching = ts.createMapFromTemplate((_a = {},
139671             _a[18 /* OpenBraceToken */] = 19 /* CloseBraceToken */,
139672             _a[20 /* OpenParenToken */] = 21 /* CloseParenToken */,
139673             _a[22 /* OpenBracketToken */] = 23 /* CloseBracketToken */,
139674             _a[31 /* GreaterThanToken */] = 29 /* LessThanToken */,
139675             _a));
139676         braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); });
139677         function getBraceMatchingAtPosition(fileName, position) {
139678             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139679             var token = ts.getTouchingToken(sourceFile, position);
139680             var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined;
139681             var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile);
139682             // We want to order the braces when we return the result.
139683             return match ? [ts.createTextSpanFromNode(token, sourceFile), ts.createTextSpanFromNode(match, sourceFile)].sort(function (a, b) { return a.start - b.start; }) : ts.emptyArray;
139684         }
139685         function getIndentationAtPosition(fileName, position, editorOptions) {
139686             var start = ts.timestamp();
139687             var settings = toEditorSettings(editorOptions);
139688             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139689             log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start));
139690             start = ts.timestamp();
139691             var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings);
139692             log("getIndentationAtPosition: computeIndentation  : " + (ts.timestamp() - start));
139693             return result;
139694         }
139695         function getFormattingEditsForRange(fileName, start, end, options) {
139696             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139697             return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options), host));
139698         }
139699         function getFormattingEditsForDocument(fileName, options) {
139700             return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options), host));
139701         }
139702         function getFormattingEditsAfterKeystroke(fileName, position, key, options) {
139703             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139704             var formatContext = ts.formatting.getFormatContext(toEditorSettings(options), host);
139705             if (!ts.isInComment(sourceFile, position)) {
139706                 switch (key) {
139707                     case "{":
139708                         return ts.formatting.formatOnOpeningCurly(position, sourceFile, formatContext);
139709                     case "}":
139710                         return ts.formatting.formatOnClosingCurly(position, sourceFile, formatContext);
139711                     case ";":
139712                         return ts.formatting.formatOnSemicolon(position, sourceFile, formatContext);
139713                     case "\n":
139714                         return ts.formatting.formatOnEnter(position, sourceFile, formatContext);
139715                 }
139716             }
139717             return [];
139718         }
139719         function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) {
139720             if (preferences === void 0) { preferences = ts.emptyOptions; }
139721             synchronizeHostData();
139722             var sourceFile = getValidSourceFile(fileName);
139723             var span = ts.createTextSpanFromBounds(start, end);
139724             var formatContext = ts.formatting.getFormatContext(formatOptions, host);
139725             return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) {
139726                 cancellationToken.throwIfCancellationRequested();
139727                 return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
139728             });
139729         }
139730         function getCombinedCodeFix(scope, fixId, formatOptions, preferences) {
139731             if (preferences === void 0) { preferences = ts.emptyOptions; }
139732             synchronizeHostData();
139733             ts.Debug.assert(scope.type === "file");
139734             var sourceFile = getValidSourceFile(scope.fileName);
139735             var formatContext = ts.formatting.getFormatContext(formatOptions, host);
139736             return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
139737         }
139738         function organizeImports(scope, formatOptions, preferences) {
139739             if (preferences === void 0) { preferences = ts.emptyOptions; }
139740             synchronizeHostData();
139741             ts.Debug.assert(scope.type === "file");
139742             var sourceFile = getValidSourceFile(scope.fileName);
139743             var formatContext = ts.formatting.getFormatContext(formatOptions, host);
139744             return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences);
139745         }
139746         function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) {
139747             if (preferences === void 0) { preferences = ts.emptyOptions; }
139748             return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions, host), preferences, sourceMapper);
139749         }
139750         function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) {
139751             var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName;
139752             return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a); })) : applySingleCodeActionCommand(action);
139753         }
139754         function applySingleCodeActionCommand(action) {
139755             var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); };
139756             ts.Debug.assertEqual(action.type, "install package");
139757             return host.installPackage
139758                 ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName })
139759                 : Promise.reject("Host does not implement `installPackage`");
139760         }
139761         function getDocCommentTemplateAtPosition(fileName, position) {
139762             return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position);
139763         }
139764         function isValidBraceCompletionAtPosition(fileName, position, openingBrace) {
139765             // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too
139766             // expensive to do during typing scenarios
139767             // i.e. whether we're dealing with:
139768             //      var x = new foo<| ( with class foo<T>{} )
139769             // or
139770             //      var y = 3 <|
139771             if (openingBrace === 60 /* lessThan */) {
139772                 return false;
139773             }
139774             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139775             // Check if in a context where we don't want to perform any insertion
139776             if (ts.isInString(sourceFile, position)) {
139777                 return false;
139778             }
139779             if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) {
139780                 return openingBrace === 123 /* openBrace */;
139781             }
139782             if (ts.isInTemplateString(sourceFile, position)) {
139783                 return false;
139784             }
139785             switch (openingBrace) {
139786                 case 39 /* singleQuote */:
139787                 case 34 /* doubleQuote */:
139788                 case 96 /* backtick */:
139789                     return !ts.isInComment(sourceFile, position);
139790             }
139791             return true;
139792         }
139793         function getJsxClosingTagAtPosition(fileName, position) {
139794             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139795             var token = ts.findPrecedingToken(position, sourceFile);
139796             if (!token)
139797                 return undefined;
139798             var element = token.kind === 31 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent
139799                 : ts.isJsxText(token) ? token.parent : undefined;
139800             if (element && isUnclosedTag(element)) {
139801                 return { newText: "</" + element.openingElement.tagName.getText(sourceFile) + ">" };
139802             }
139803         }
139804         function isUnclosedTag(_a) {
139805             var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent;
139806             return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) ||
139807                 ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent);
139808         }
139809         function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
139810             var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
139811             var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position);
139812             return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined;
139813         }
139814         function getTodoComments(fileName, descriptors) {
139815             // Note: while getting todo comments seems like a syntactic operation, we actually
139816             // treat it as a semantic operation here.  This is because we expect our host to call
139817             // this on every single file.  If we treat this syntactically, then that will cause
139818             // us to populate and throw away the tree in our syntax tree cache for each file.  By
139819             // treating this as a semantic operation, we can access any tree without throwing
139820             // anything away.
139821             synchronizeHostData();
139822             var sourceFile = getValidSourceFile(fileName);
139823             cancellationToken.throwIfCancellationRequested();
139824             var fileContents = sourceFile.text;
139825             var result = [];
139826             // Exclude node_modules files as we don't want to show the todos of external libraries.
139827             if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) {
139828                 var regExp = getTodoCommentsRegExp();
139829                 var matchArray = void 0;
139830                 while (matchArray = regExp.exec(fileContents)) {
139831                     cancellationToken.throwIfCancellationRequested();
139832                     // If we got a match, here is what the match array will look like.  Say the source text is:
139833                     //
139834                     //      "    // hack   1"
139835                     //
139836                     // The result array with the regexp:    will be:
139837                     //
139838                     //      ["// hack   1", "// ", "hack   1", undefined, "hack"]
139839                     //
139840                     // Here are the relevant capture groups:
139841                     //  0) The full match for the entire regexp.
139842                     //  1) The preamble to the message portion.
139843                     //  2) The message portion.
139844                     //  3...N) The descriptor that was matched - by index.  'undefined' for each
139845                     //         descriptor that didn't match.  an actual value if it did match.
139846                     //
139847                     //  i.e. 'undefined' in position 3 above means TODO(jason) didn't match.
139848                     //       "hack"      in position 4 means HACK did match.
139849                     var firstDescriptorCaptureIndex = 3;
139850                     ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
139851                     var preamble = matchArray[1];
139852                     var matchPosition = matchArray.index + preamble.length;
139853                     // OK, we have found a match in the file.  This is only an acceptable match if
139854                     // it is contained within a comment.
139855                     if (!ts.isInComment(sourceFile, matchPosition)) {
139856                         continue;
139857                     }
139858                     var descriptor = void 0;
139859                     for (var i = 0; i < descriptors.length; i++) {
139860                         if (matchArray[i + firstDescriptorCaptureIndex]) {
139861                             descriptor = descriptors[i];
139862                         }
139863                     }
139864                     if (descriptor === undefined)
139865                         return ts.Debug.fail();
139866                     // We don't want to match something like 'TODOBY', so we make sure a non
139867                     // letter/digit follows the match.
139868                     if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
139869                         continue;
139870                     }
139871                     var message = matchArray[2];
139872                     result.push({ descriptor: descriptor, message: message, position: matchPosition });
139873                 }
139874             }
139875             return result;
139876             function escapeRegExp(str) {
139877                 return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
139878             }
139879             function getTodoCommentsRegExp() {
139880                 // NOTE: `?:` means 'non-capture group'.  It allows us to have groups without having to
139881                 // filter them out later in the final result array.
139882                 // TODO comments can appear in one of the following forms:
139883                 //
139884                 //  1)      // TODO     or  /////////// TODO
139885                 //
139886                 //  2)      /* TODO     or  /********** TODO
139887                 //
139888                 //  3)      /*
139889                 //           *   TODO
139890                 //           */
139891                 //
139892                 // The following three regexps are used to match the start of the text up to the TODO
139893                 // comment portion.
139894                 var singleLineCommentStart = /(?:\/\/+\s*)/.source;
139895                 var multiLineCommentStart = /(?:\/\*+\s*)/.source;
139896                 var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
139897                 // Match any of the above three TODO comment start regexps.
139898                 // Note that the outermost group *is* a capture group.  We want to capture the preamble
139899                 // so that we can determine the starting position of the TODO comment match.
139900                 var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
139901                 // Takes the descriptors and forms a regexp that matches them as if they were literals.
139902                 // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be:
139903                 //
139904                 //      (?:(TODO\(jason\))|(HACK))
139905                 //
139906                 // Note that the outermost group is *not* a capture group, but the innermost groups
139907                 // *are* capture groups.  By capturing the inner literals we can determine after
139908                 // matching which descriptor we are dealing with.
139909                 var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")";
139910                 // After matching a descriptor literal, the following regexp matches the rest of the
139911                 // text up to the end of the line (or */).
139912                 var endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
139913                 var messageRemainder = /(?:.*?)/.source;
139914                 // This is the portion of the match we'll return as part of the TODO comment result. We
139915                 // match the literal portion up to the end of the line or end of comment.
139916                 var messagePortion = "(" + literals + messageRemainder + ")";
139917                 var regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
139918                 // The final regexp will look like this:
139919                 // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim
139920                 // The flags of the regexp are important here.
139921                 //  'g' is so that we are doing a global search and can find matches several times
139922                 //  in the input.
139923                 //
139924                 //  'i' is for case insensitivity (We do this to match C# TODO comment code).
139925                 //
139926                 //  'm' is so we can find matches in a multi-line input.
139927                 return new RegExp(regExpString, "gim");
139928             }
139929             function isLetterOrDigit(char) {
139930                 return (char >= 97 /* a */ && char <= 122 /* z */) ||
139931                     (char >= 65 /* A */ && char <= 90 /* Z */) ||
139932                     (char >= 48 /* _0 */ && char <= 57 /* _9 */);
139933             }
139934             function isNodeModulesFile(path) {
139935                 return ts.stringContains(path, "/node_modules/");
139936             }
139937         }
139938         function getRenameInfo(fileName, position, options) {
139939             synchronizeHostData();
139940             return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options);
139941         }
139942         function getRefactorContext(file, positionOrRange, preferences, formatOptions) {
139943             var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1];
139944             return {
139945                 file: file,
139946                 startPosition: startPosition,
139947                 endPosition: endPosition,
139948                 program: getProgram(),
139949                 host: host,
139950                 formatContext: ts.formatting.getFormatContext(formatOptions, host),
139951                 cancellationToken: cancellationToken,
139952                 preferences: preferences,
139953             };
139954         }
139955         function getSmartSelectionRange(fileName, position) {
139956             return ts.SmartSelectionRange.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName));
139957         }
139958         function getApplicableRefactors(fileName, positionOrRange, preferences) {
139959             if (preferences === void 0) { preferences = ts.emptyOptions; }
139960             synchronizeHostData();
139961             var file = getValidSourceFile(fileName);
139962             return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences));
139963         }
139964         function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) {
139965             if (preferences === void 0) { preferences = ts.emptyOptions; }
139966             synchronizeHostData();
139967             var file = getValidSourceFile(fileName);
139968             return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName);
139969         }
139970         function prepareCallHierarchy(fileName, position) {
139971             synchronizeHostData();
139972             var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position));
139973             return declarations && ts.mapOneOrMany(declarations, function (declaration) { return ts.CallHierarchy.createCallHierarchyItem(program, declaration); });
139974         }
139975         function provideCallHierarchyIncomingCalls(fileName, position) {
139976             synchronizeHostData();
139977             var sourceFile = getValidSourceFile(fileName);
139978             var declaration = ts.firstOrOnly(ts.CallHierarchy.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : ts.getTouchingPropertyName(sourceFile, position)));
139979             return declaration ? ts.CallHierarchy.getIncomingCalls(program, declaration, cancellationToken) : [];
139980         }
139981         function provideCallHierarchyOutgoingCalls(fileName, position) {
139982             synchronizeHostData();
139983             var sourceFile = getValidSourceFile(fileName);
139984             var declaration = ts.firstOrOnly(ts.CallHierarchy.resolveCallHierarchyDeclaration(program, position === 0 ? sourceFile : ts.getTouchingPropertyName(sourceFile, position)));
139985             return declaration ? ts.CallHierarchy.getOutgoingCalls(program, declaration) : [];
139986         }
139987         return {
139988             dispose: dispose,
139989             cleanupSemanticCache: cleanupSemanticCache,
139990             getSyntacticDiagnostics: getSyntacticDiagnostics,
139991             getSemanticDiagnostics: getSemanticDiagnostics,
139992             getSuggestionDiagnostics: getSuggestionDiagnostics,
139993             getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics,
139994             getSyntacticClassifications: getSyntacticClassifications,
139995             getSemanticClassifications: getSemanticClassifications,
139996             getEncodedSyntacticClassifications: getEncodedSyntacticClassifications,
139997             getEncodedSemanticClassifications: getEncodedSemanticClassifications,
139998             getCompletionsAtPosition: getCompletionsAtPosition,
139999             getCompletionEntryDetails: getCompletionEntryDetails,
140000             getCompletionEntrySymbol: getCompletionEntrySymbol,
140001             getSignatureHelpItems: getSignatureHelpItems,
140002             getQuickInfoAtPosition: getQuickInfoAtPosition,
140003             getDefinitionAtPosition: getDefinitionAtPosition,
140004             getDefinitionAndBoundSpan: getDefinitionAndBoundSpan,
140005             getImplementationAtPosition: getImplementationAtPosition,
140006             getTypeDefinitionAtPosition: getTypeDefinitionAtPosition,
140007             getReferencesAtPosition: getReferencesAtPosition,
140008             findReferences: findReferences,
140009             getOccurrencesAtPosition: getOccurrencesAtPosition,
140010             getDocumentHighlights: getDocumentHighlights,
140011             getNameOrDottedNameSpan: getNameOrDottedNameSpan,
140012             getBreakpointStatementAtPosition: getBreakpointStatementAtPosition,
140013             getNavigateToItems: getNavigateToItems,
140014             getRenameInfo: getRenameInfo,
140015             getSmartSelectionRange: getSmartSelectionRange,
140016             findRenameLocations: findRenameLocations,
140017             getNavigationBarItems: getNavigationBarItems,
140018             getNavigationTree: getNavigationTree,
140019             getOutliningSpans: getOutliningSpans,
140020             getTodoComments: getTodoComments,
140021             getBraceMatchingAtPosition: getBraceMatchingAtPosition,
140022             getIndentationAtPosition: getIndentationAtPosition,
140023             getFormattingEditsForRange: getFormattingEditsForRange,
140024             getFormattingEditsForDocument: getFormattingEditsForDocument,
140025             getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke,
140026             getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition,
140027             isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition,
140028             getJsxClosingTagAtPosition: getJsxClosingTagAtPosition,
140029             getSpanOfEnclosingComment: getSpanOfEnclosingComment,
140030             getCodeFixesAtPosition: getCodeFixesAtPosition,
140031             getCombinedCodeFix: getCombinedCodeFix,
140032             applyCodeActionCommand: applyCodeActionCommand,
140033             organizeImports: organizeImports,
140034             getEditsForFileRename: getEditsForFileRename,
140035             getEmitOutput: getEmitOutput,
140036             getNonBoundSourceFile: getNonBoundSourceFile,
140037             getProgram: getProgram,
140038             getApplicableRefactors: getApplicableRefactors,
140039             getEditsForRefactor: getEditsForRefactor,
140040             toLineColumnOffset: sourceMapper.toLineColumnOffset,
140041             getSourceMapper: function () { return sourceMapper; },
140042             clearSourceMapperCache: function () { return sourceMapper.clearCache(); },
140043             prepareCallHierarchy: prepareCallHierarchy,
140044             provideCallHierarchyIncomingCalls: provideCallHierarchyIncomingCalls,
140045             provideCallHierarchyOutgoingCalls: provideCallHierarchyOutgoingCalls
140046         };
140047     }
140048     ts.createLanguageService = createLanguageService;
140049     /* @internal */
140050     /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */
140051     function getNameTable(sourceFile) {
140052         if (!sourceFile.nameTable) {
140053             initializeNameTable(sourceFile);
140054         }
140055         return sourceFile.nameTable; // TODO: GH#18217
140056     }
140057     ts.getNameTable = getNameTable;
140058     function initializeNameTable(sourceFile) {
140059         var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap();
140060         sourceFile.forEachChild(function walk(node) {
140061             if (ts.isIdentifier(node) && !ts.isTagName(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) {
140062                 var text = ts.getEscapedTextOfIdentifierOrLiteral(node);
140063                 nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
140064             }
140065             else if (ts.isPrivateIdentifier(node)) {
140066                 var text = node.escapedText;
140067                 nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
140068             }
140069             ts.forEachChild(node, walk);
140070             if (ts.hasJSDocNodes(node)) {
140071                 for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
140072                     var jsDoc = _a[_i];
140073                     ts.forEachChild(jsDoc, walk);
140074                 }
140075             }
140076         });
140077     }
140078     /**
140079      * We want to store any numbers/strings if they were a name that could be
140080      * related to a declaration.  So, if we have 'import x = require("something")'
140081      * then we want 'something' to be in the name table.  Similarly, if we have
140082      * "a['propname']" then we want to store "propname" in the name table.
140083      */
140084     function literalIsName(node) {
140085         return ts.isDeclarationName(node) ||
140086             node.parent.kind === 265 /* ExternalModuleReference */ ||
140087             isArgumentOfElementAccessExpression(node) ||
140088             ts.isLiteralComputedPropertyDeclarationName(node);
140089     }
140090     /**
140091      * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
140092      */
140093     /* @internal */
140094     function getContainingObjectLiteralElement(node) {
140095         var element = getContainingObjectLiteralElementWorker(node);
140096         return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined;
140097     }
140098     ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement;
140099     function getContainingObjectLiteralElementWorker(node) {
140100         switch (node.kind) {
140101             case 10 /* StringLiteral */:
140102             case 14 /* NoSubstitutionTemplateLiteral */:
140103             case 8 /* NumericLiteral */:
140104                 if (node.parent.kind === 154 /* ComputedPropertyName */) {
140105                     return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined;
140106                 }
140107             // falls through
140108             case 75 /* Identifier */:
140109                 return ts.isObjectLiteralElement(node.parent) &&
140110                     (node.parent.parent.kind === 193 /* ObjectLiteralExpression */ || node.parent.parent.kind === 274 /* JsxAttributes */) &&
140111                     node.parent.name === node ? node.parent : undefined;
140112         }
140113         return undefined;
140114     }
140115     function getSymbolAtLocationForQuickInfo(node, checker) {
140116         var object = getContainingObjectLiteralElement(node);
140117         if (object) {
140118             var contextualType = checker.getContextualType(object.parent);
140119             var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false);
140120             if (properties && properties.length === 1) {
140121                 return ts.first(properties);
140122             }
140123         }
140124         return checker.getSymbolAtLocation(node);
140125     }
140126     /** Gets all symbols for one property. Does not get symbols for every property. */
140127     /* @internal */
140128     function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) {
140129         var name = ts.getNameFromPropertyName(node.name);
140130         if (!name)
140131             return ts.emptyArray;
140132         if (!contextualType.isUnion()) {
140133             var symbol = contextualType.getProperty(name);
140134             return symbol ? [symbol] : ts.emptyArray;
140135         }
140136         var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); });
140137         if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) {
140138             var symbol = contextualType.getProperty(name);
140139             if (symbol)
140140                 return [symbol];
140141         }
140142         if (discriminatedPropertySymbols.length === 0) {
140143             // Bad discriminant -- do again without discriminating
140144             return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); });
140145         }
140146         return discriminatedPropertySymbols;
140147     }
140148     ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType;
140149     function isArgumentOfElementAccessExpression(node) {
140150         return node &&
140151             node.parent &&
140152             node.parent.kind === 195 /* ElementAccessExpression */ &&
140153             node.parent.argumentExpression === node;
140154     }
140155     /**
140156      * Get the path of the default library files (lib.d.ts) as distributed with the typescript
140157      * node package.
140158      * The functionality is not supported if the ts module is consumed outside of a node module.
140159      */
140160     function getDefaultLibFilePath(options) {
140161         // Check __dirname is defined and that we are on a node.js system.
140162         if (typeof __dirname !== "undefined") {
140163             return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options);
140164         }
140165         throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
140166     }
140167     ts.getDefaultLibFilePath = getDefaultLibFilePath;
140168     ts.setObjectAllocator(getServicesObjectAllocator());
140169 })(ts || (ts = {}));
140170 /* @internal */
140171 var ts;
140172 (function (ts) {
140173     var BreakpointResolver;
140174     (function (BreakpointResolver) {
140175         /**
140176          * Get the breakpoint span in given sourceFile
140177          */
140178         function spanInSourceFileAtLocation(sourceFile, position) {
140179             // Cannot set breakpoint in dts file
140180             if (sourceFile.isDeclarationFile) {
140181                 return undefined;
140182             }
140183             var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
140184             var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
140185             if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
140186                 // Get previous token if the token is returned starts on new line
140187                 // eg: let x =10; |--- cursor is here
140188                 //     let y = 10;
140189                 // token at position will return let keyword on second line as the token but we would like to use
140190                 // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
140191                 var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile);
140192                 // It's a blank line
140193                 if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) {
140194                     return undefined;
140195                 }
140196                 tokenAtLocation = preceding;
140197             }
140198             // Cannot set breakpoint in ambient declarations
140199             if (tokenAtLocation.flags & 8388608 /* Ambient */) {
140200                 return undefined;
140201             }
140202             // Get the span in the node based on its syntax
140203             return spanInNode(tokenAtLocation);
140204             function textSpan(startNode, endNode) {
140205                 var start = startNode.decorators ?
140206                     ts.skipTrivia(sourceFile.text, startNode.decorators.end) :
140207                     startNode.getStart(sourceFile);
140208                 return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
140209             }
140210             function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
140211                 return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
140212             }
140213             function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
140214                 if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
140215                     return spanInNode(node);
140216                 }
140217                 return spanInNode(otherwiseOnNode);
140218             }
140219             function spanInNodeArray(nodeArray) {
140220                 return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
140221             }
140222             function spanInPreviousNode(node) {
140223                 return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
140224             }
140225             function spanInNextNode(node) {
140226                 return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
140227             }
140228             function spanInNode(node) {
140229                 if (node) {
140230                     var parent = node.parent;
140231                     switch (node.kind) {
140232                         case 225 /* VariableStatement */:
140233                             // Span on first variable declaration
140234                             return spanInVariableDeclaration(node.declarationList.declarations[0]);
140235                         case 242 /* VariableDeclaration */:
140236                         case 159 /* PropertyDeclaration */:
140237                         case 158 /* PropertySignature */:
140238                             return spanInVariableDeclaration(node);
140239                         case 156 /* Parameter */:
140240                             return spanInParameterDeclaration(node);
140241                         case 244 /* FunctionDeclaration */:
140242                         case 161 /* MethodDeclaration */:
140243                         case 160 /* MethodSignature */:
140244                         case 163 /* GetAccessor */:
140245                         case 164 /* SetAccessor */:
140246                         case 162 /* Constructor */:
140247                         case 201 /* FunctionExpression */:
140248                         case 202 /* ArrowFunction */:
140249                             return spanInFunctionDeclaration(node);
140250                         case 223 /* Block */:
140251                             if (ts.isFunctionBlock(node)) {
140252                                 return spanInFunctionBlock(node);
140253                             }
140254                         // falls through
140255                         case 250 /* ModuleBlock */:
140256                             return spanInBlock(node);
140257                         case 280 /* CatchClause */:
140258                             return spanInBlock(node.block);
140259                         case 226 /* ExpressionStatement */:
140260                             // span on the expression
140261                             return textSpan(node.expression);
140262                         case 235 /* ReturnStatement */:
140263                             // span on return keyword and expression if present
140264                             return textSpan(node.getChildAt(0), node.expression);
140265                         case 229 /* WhileStatement */:
140266                             // Span on while(...)
140267                             return textSpanEndingAtNextToken(node, node.expression);
140268                         case 228 /* DoStatement */:
140269                             // span in statement of the do statement
140270                             return spanInNode(node.statement);
140271                         case 241 /* DebuggerStatement */:
140272                             // span on debugger keyword
140273                             return textSpan(node.getChildAt(0));
140274                         case 227 /* IfStatement */:
140275                             // set on if(..) span
140276                             return textSpanEndingAtNextToken(node, node.expression);
140277                         case 238 /* LabeledStatement */:
140278                             // span in statement
140279                             return spanInNode(node.statement);
140280                         case 234 /* BreakStatement */:
140281                         case 233 /* ContinueStatement */:
140282                             // On break or continue keyword and label if present
140283                             return textSpan(node.getChildAt(0), node.label);
140284                         case 230 /* ForStatement */:
140285                             return spanInForStatement(node);
140286                         case 231 /* ForInStatement */:
140287                             // span of for (a in ...)
140288                             return textSpanEndingAtNextToken(node, node.expression);
140289                         case 232 /* ForOfStatement */:
140290                             // span in initializer
140291                             return spanInInitializerOfForLike(node);
140292                         case 237 /* SwitchStatement */:
140293                             // span on switch(...)
140294                             return textSpanEndingAtNextToken(node, node.expression);
140295                         case 277 /* CaseClause */:
140296                         case 278 /* DefaultClause */:
140297                             // span in first statement of the clause
140298                             return spanInNode(node.statements[0]);
140299                         case 240 /* TryStatement */:
140300                             // span in try block
140301                             return spanInBlock(node.tryBlock);
140302                         case 239 /* ThrowStatement */:
140303                             // span in throw ...
140304                             return textSpan(node, node.expression);
140305                         case 259 /* ExportAssignment */:
140306                             // span on export = id
140307                             return textSpan(node, node.expression);
140308                         case 253 /* ImportEqualsDeclaration */:
140309                             // import statement without including semicolon
140310                             return textSpan(node, node.moduleReference);
140311                         case 254 /* ImportDeclaration */:
140312                             // import statement without including semicolon
140313                             return textSpan(node, node.moduleSpecifier);
140314                         case 260 /* ExportDeclaration */:
140315                             // import statement without including semicolon
140316                             return textSpan(node, node.moduleSpecifier);
140317                         case 249 /* ModuleDeclaration */:
140318                             // span on complete module if it is instantiated
140319                             if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
140320                                 return undefined;
140321                             }
140322                         // falls through
140323                         case 245 /* ClassDeclaration */:
140324                         case 248 /* EnumDeclaration */:
140325                         case 284 /* EnumMember */:
140326                         case 191 /* BindingElement */:
140327                             // span on complete node
140328                             return textSpan(node);
140329                         case 236 /* WithStatement */:
140330                             // span in statement
140331                             return spanInNode(node.statement);
140332                         case 157 /* Decorator */:
140333                             return spanInNodeArray(parent.decorators);
140334                         case 189 /* ObjectBindingPattern */:
140335                         case 190 /* ArrayBindingPattern */:
140336                             return spanInBindingPattern(node);
140337                         // No breakpoint in interface, type alias
140338                         case 246 /* InterfaceDeclaration */:
140339                         case 247 /* TypeAliasDeclaration */:
140340                             return undefined;
140341                         // Tokens:
140342                         case 26 /* SemicolonToken */:
140343                         case 1 /* EndOfFileToken */:
140344                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile));
140345                         case 27 /* CommaToken */:
140346                             return spanInPreviousNode(node);
140347                         case 18 /* OpenBraceToken */:
140348                             return spanInOpenBraceToken(node);
140349                         case 19 /* CloseBraceToken */:
140350                             return spanInCloseBraceToken(node);
140351                         case 23 /* CloseBracketToken */:
140352                             return spanInCloseBracketToken(node);
140353                         case 20 /* OpenParenToken */:
140354                             return spanInOpenParenToken(node);
140355                         case 21 /* CloseParenToken */:
140356                             return spanInCloseParenToken(node);
140357                         case 58 /* ColonToken */:
140358                             return spanInColonToken(node);
140359                         case 31 /* GreaterThanToken */:
140360                         case 29 /* LessThanToken */:
140361                             return spanInGreaterThanOrLessThanToken(node);
140362                         // Keywords:
140363                         case 111 /* WhileKeyword */:
140364                             return spanInWhileKeyword(node);
140365                         case 87 /* ElseKeyword */:
140366                         case 79 /* CatchKeyword */:
140367                         case 92 /* FinallyKeyword */:
140368                             return spanInNextNode(node);
140369                         case 152 /* OfKeyword */:
140370                             return spanInOfKeyword(node);
140371                         default:
140372                             // Destructuring pattern in destructuring assignment
140373                             // [a, b, c] of
140374                             // [a, b, c] = expression
140375                             if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
140376                                 return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node);
140377                             }
140378                             // Set breakpoint on identifier element of destructuring pattern
140379                             // `a` or `...c` or `d: x` from
140380                             // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern
140381                             if ((node.kind === 75 /* Identifier */ ||
140382                                 node.kind === 213 /* SpreadElement */ ||
140383                                 node.kind === 281 /* PropertyAssignment */ ||
140384                                 node.kind === 282 /* ShorthandPropertyAssignment */) &&
140385                                 ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) {
140386                                 return textSpan(node);
140387                             }
140388                             if (node.kind === 209 /* BinaryExpression */) {
140389                                 var _a = node, left = _a.left, operatorToken = _a.operatorToken;
140390                                 // Set breakpoint in destructuring pattern if its destructuring assignment
140391                                 // [a, b, c] or {a, b, c} of
140392                                 // [a, b, c] = expression or
140393                                 // {a, b, c} = expression
140394                                 if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
140395                                     return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left);
140396                                 }
140397                                 if (operatorToken.kind === 62 /* EqualsToken */ && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
140398                                     // Set breakpoint on assignment expression element of destructuring pattern
140399                                     // a = expression of
140400                                     // [a = expression, b, c] = someExpression or
140401                                     // { a = expression, b, c } = someExpression
140402                                     return textSpan(node);
140403                                 }
140404                                 if (operatorToken.kind === 27 /* CommaToken */) {
140405                                     return spanInNode(left);
140406                                 }
140407                             }
140408                             if (ts.isExpressionNode(node)) {
140409                                 switch (parent.kind) {
140410                                     case 228 /* DoStatement */:
140411                                         // Set span as if on while keyword
140412                                         return spanInPreviousNode(node);
140413                                     case 157 /* Decorator */:
140414                                         // Set breakpoint on the decorator emit
140415                                         return spanInNode(node.parent);
140416                                     case 230 /* ForStatement */:
140417                                     case 232 /* ForOfStatement */:
140418                                         return textSpan(node);
140419                                     case 209 /* BinaryExpression */:
140420                                         if (node.parent.operatorToken.kind === 27 /* CommaToken */) {
140421                                             // If this is a comma expression, the breakpoint is possible in this expression
140422                                             return textSpan(node);
140423                                         }
140424                                         break;
140425                                     case 202 /* ArrowFunction */:
140426                                         if (node.parent.body === node) {
140427                                             // If this is body of arrow function, it is allowed to have the breakpoint
140428                                             return textSpan(node);
140429                                         }
140430                                         break;
140431                                 }
140432                             }
140433                             switch (node.parent.kind) {
140434                                 case 281 /* PropertyAssignment */:
140435                                     // If this is name of property assignment, set breakpoint in the initializer
140436                                     if (node.parent.name === node &&
140437                                         !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
140438                                         return spanInNode(node.parent.initializer);
140439                                     }
140440                                     break;
140441                                 case 199 /* TypeAssertionExpression */:
140442                                     // Breakpoint in type assertion goes to its operand
140443                                     if (node.parent.type === node) {
140444                                         return spanInNextNode(node.parent.type);
140445                                     }
140446                                     break;
140447                                 case 242 /* VariableDeclaration */:
140448                                 case 156 /* Parameter */: {
140449                                     // initializer of variable/parameter declaration go to previous node
140450                                     var _b = node.parent, initializer = _b.initializer, type = _b.type;
140451                                     if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) {
140452                                         return spanInPreviousNode(node);
140453                                     }
140454                                     break;
140455                                 }
140456                                 case 209 /* BinaryExpression */: {
140457                                     var left = node.parent.left;
140458                                     if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
140459                                         // If initializer of destructuring assignment move to previous token
140460                                         return spanInPreviousNode(node);
140461                                     }
140462                                     break;
140463                                 }
140464                                 default:
140465                                     // return type of function go to previous token
140466                                     if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
140467                                         return spanInPreviousNode(node);
140468                                     }
140469                             }
140470                             // Default go to parent to set the breakpoint
140471                             return spanInNode(node.parent);
140472                     }
140473                 }
140474                 function textSpanFromVariableDeclaration(variableDeclaration) {
140475                     if (ts.isVariableDeclarationList(variableDeclaration.parent) && variableDeclaration.parent.declarations[0] === variableDeclaration) {
140476                         // First declaration - include let keyword
140477                         return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
140478                     }
140479                     else {
140480                         // Span only on this declaration
140481                         return textSpan(variableDeclaration);
140482                     }
140483                 }
140484                 function spanInVariableDeclaration(variableDeclaration) {
140485                     // If declaration of for in statement, just set the span in parent
140486                     if (variableDeclaration.parent.parent.kind === 231 /* ForInStatement */) {
140487                         return spanInNode(variableDeclaration.parent.parent);
140488                     }
140489                     var parent = variableDeclaration.parent;
140490                     // If this is a destructuring pattern, set breakpoint in binding pattern
140491                     if (ts.isBindingPattern(variableDeclaration.name)) {
140492                         return spanInBindingPattern(variableDeclaration.name);
140493                     }
140494                     // Breakpoint is possible in variableDeclaration only if there is initialization
140495                     // or its declaration from 'for of'
140496                     if (variableDeclaration.initializer ||
140497                         ts.hasModifier(variableDeclaration, 1 /* Export */) ||
140498                         parent.parent.kind === 232 /* ForOfStatement */) {
140499                         return textSpanFromVariableDeclaration(variableDeclaration);
140500                     }
140501                     if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
140502                         variableDeclaration.parent.declarations[0] !== variableDeclaration) {
140503                         // If we cannot set breakpoint on this declaration, set it on previous one
140504                         // Because the variable declaration may be binding pattern and
140505                         // we would like to set breakpoint in last binding element if that's the case,
140506                         // use preceding token instead
140507                         return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
140508                     }
140509                 }
140510                 function canHaveSpanInParameterDeclaration(parameter) {
140511                     // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier
140512                     return !!parameter.initializer || parameter.dotDotDotToken !== undefined ||
140513                         ts.hasModifier(parameter, 4 /* Public */ | 8 /* Private */);
140514                 }
140515                 function spanInParameterDeclaration(parameter) {
140516                     if (ts.isBindingPattern(parameter.name)) {
140517                         // Set breakpoint in binding pattern
140518                         return spanInBindingPattern(parameter.name);
140519                     }
140520                     else if (canHaveSpanInParameterDeclaration(parameter)) {
140521                         return textSpan(parameter);
140522                     }
140523                     else {
140524                         var functionDeclaration = parameter.parent;
140525                         var indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
140526                         ts.Debug.assert(indexOfParameter !== -1);
140527                         if (indexOfParameter !== 0) {
140528                             // Not a first parameter, go to previous parameter
140529                             return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
140530                         }
140531                         else {
140532                             // Set breakpoint in the function declaration body
140533                             return spanInNode(functionDeclaration.body);
140534                         }
140535                     }
140536                 }
140537                 function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
140538                     return ts.hasModifier(functionDeclaration, 1 /* Export */) ||
140539                         (functionDeclaration.parent.kind === 245 /* ClassDeclaration */ && functionDeclaration.kind !== 162 /* Constructor */);
140540                 }
140541                 function spanInFunctionDeclaration(functionDeclaration) {
140542                     // No breakpoints in the function signature
140543                     if (!functionDeclaration.body) {
140544                         return undefined;
140545                     }
140546                     if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
140547                         // Set the span on whole function declaration
140548                         return textSpan(functionDeclaration);
140549                     }
140550                     // Set span in function body
140551                     return spanInNode(functionDeclaration.body);
140552                 }
140553                 function spanInFunctionBlock(block) {
140554                     var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
140555                     if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
140556                         return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
140557                     }
140558                     return spanInNode(nodeForSpanInBlock);
140559                 }
140560                 function spanInBlock(block) {
140561                     switch (block.parent.kind) {
140562                         case 249 /* ModuleDeclaration */:
140563                             if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
140564                                 return undefined;
140565                             }
140566                         // Set on parent if on same line otherwise on first statement
140567                         // falls through
140568                         case 229 /* WhileStatement */:
140569                         case 227 /* IfStatement */:
140570                         case 231 /* ForInStatement */:
140571                             return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
140572                         // Set span on previous token if it starts on same line otherwise on the first statement of the block
140573                         case 230 /* ForStatement */:
140574                         case 232 /* ForOfStatement */:
140575                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
140576                     }
140577                     // Default action is to set on first statement
140578                     return spanInNode(block.statements[0]);
140579                 }
140580                 function spanInInitializerOfForLike(forLikeStatement) {
140581                     if (forLikeStatement.initializer.kind === 243 /* VariableDeclarationList */) {
140582                         // Declaration list - set breakpoint in first declaration
140583                         var variableDeclarationList = forLikeStatement.initializer;
140584                         if (variableDeclarationList.declarations.length > 0) {
140585                             return spanInNode(variableDeclarationList.declarations[0]);
140586                         }
140587                     }
140588                     else {
140589                         // Expression - set breakpoint in it
140590                         return spanInNode(forLikeStatement.initializer);
140591                     }
140592                 }
140593                 function spanInForStatement(forStatement) {
140594                     if (forStatement.initializer) {
140595                         return spanInInitializerOfForLike(forStatement);
140596                     }
140597                     if (forStatement.condition) {
140598                         return textSpan(forStatement.condition);
140599                     }
140600                     if (forStatement.incrementor) {
140601                         return textSpan(forStatement.incrementor);
140602                     }
140603                 }
140604                 function spanInBindingPattern(bindingPattern) {
140605                     // Set breakpoint in first binding element
140606                     var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 215 /* OmittedExpression */ ? element : undefined; });
140607                     if (firstBindingElement) {
140608                         return spanInNode(firstBindingElement);
140609                     }
140610                     // Empty binding pattern of binding element, set breakpoint on binding element
140611                     if (bindingPattern.parent.kind === 191 /* BindingElement */) {
140612                         return textSpan(bindingPattern.parent);
140613                     }
140614                     // Variable declaration is used as the span
140615                     return textSpanFromVariableDeclaration(bindingPattern.parent);
140616                 }
140617                 function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) {
140618                     ts.Debug.assert(node.kind !== 190 /* ArrayBindingPattern */ && node.kind !== 189 /* ObjectBindingPattern */);
140619                     var elements = node.kind === 192 /* ArrayLiteralExpression */ ? node.elements : node.properties;
140620                     var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 215 /* OmittedExpression */ ? element : undefined; });
140621                     if (firstBindingElement) {
140622                         return spanInNode(firstBindingElement);
140623                     }
140624                     // Could be ArrayLiteral from destructuring assignment or
140625                     // just nested element in another destructuring assignment
140626                     // set breakpoint on assignment when parent is destructuring assignment
140627                     // Otherwise set breakpoint for this element
140628                     return textSpan(node.parent.kind === 209 /* BinaryExpression */ ? node.parent : node);
140629                 }
140630                 // Tokens:
140631                 function spanInOpenBraceToken(node) {
140632                     switch (node.parent.kind) {
140633                         case 248 /* EnumDeclaration */:
140634                             var enumDeclaration = node.parent;
140635                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
140636                         case 245 /* ClassDeclaration */:
140637                             var classDeclaration = node.parent;
140638                             return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
140639                         case 251 /* CaseBlock */:
140640                             return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
140641                     }
140642                     // Default to parent node
140643                     return spanInNode(node.parent);
140644                 }
140645                 function spanInCloseBraceToken(node) {
140646                     switch (node.parent.kind) {
140647                         case 250 /* ModuleBlock */:
140648                             // If this is not an instantiated module block, no bp span
140649                             if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
140650                                 return undefined;
140651                             }
140652                         // falls through
140653                         case 248 /* EnumDeclaration */:
140654                         case 245 /* ClassDeclaration */:
140655                             // Span on close brace token
140656                             return textSpan(node);
140657                         case 223 /* Block */:
140658                             if (ts.isFunctionBlock(node.parent)) {
140659                                 // Span on close brace token
140660                                 return textSpan(node);
140661                             }
140662                         // falls through
140663                         case 280 /* CatchClause */:
140664                             return spanInNode(ts.lastOrUndefined(node.parent.statements));
140665                         case 251 /* CaseBlock */:
140666                             // breakpoint in last statement of the last clause
140667                             var caseBlock = node.parent;
140668                             var lastClause = ts.lastOrUndefined(caseBlock.clauses);
140669                             if (lastClause) {
140670                                 return spanInNode(ts.lastOrUndefined(lastClause.statements));
140671                             }
140672                             return undefined;
140673                         case 189 /* ObjectBindingPattern */:
140674                             // Breakpoint in last binding element or binding pattern if it contains no elements
140675                             var bindingPattern = node.parent;
140676                             return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
140677                         // Default to parent node
140678                         default:
140679                             if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
140680                                 // Breakpoint in last binding element or binding pattern if it contains no elements
140681                                 var objectLiteral = node.parent;
140682                                 return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral);
140683                             }
140684                             return spanInNode(node.parent);
140685                     }
140686                 }
140687                 function spanInCloseBracketToken(node) {
140688                     switch (node.parent.kind) {
140689                         case 190 /* ArrayBindingPattern */:
140690                             // Breakpoint in last binding element or binding pattern if it contains no elements
140691                             var bindingPattern = node.parent;
140692                             return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
140693                         default:
140694                             if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
140695                                 // Breakpoint in last binding element or binding pattern if it contains no elements
140696                                 var arrayLiteral = node.parent;
140697                                 return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
140698                             }
140699                             // Default to parent node
140700                             return spanInNode(node.parent);
140701                     }
140702                 }
140703                 function spanInOpenParenToken(node) {
140704                     if (node.parent.kind === 228 /* DoStatement */ || // Go to while keyword and do action instead
140705                         node.parent.kind === 196 /* CallExpression */ ||
140706                         node.parent.kind === 197 /* NewExpression */) {
140707                         return spanInPreviousNode(node);
140708                     }
140709                     if (node.parent.kind === 200 /* ParenthesizedExpression */) {
140710                         return spanInNextNode(node);
140711                     }
140712                     // Default to parent node
140713                     return spanInNode(node.parent);
140714                 }
140715                 function spanInCloseParenToken(node) {
140716                     // Is this close paren token of parameter list, set span in previous token
140717                     switch (node.parent.kind) {
140718                         case 201 /* FunctionExpression */:
140719                         case 244 /* FunctionDeclaration */:
140720                         case 202 /* ArrowFunction */:
140721                         case 161 /* MethodDeclaration */:
140722                         case 160 /* MethodSignature */:
140723                         case 163 /* GetAccessor */:
140724                         case 164 /* SetAccessor */:
140725                         case 162 /* Constructor */:
140726                         case 229 /* WhileStatement */:
140727                         case 228 /* DoStatement */:
140728                         case 230 /* ForStatement */:
140729                         case 232 /* ForOfStatement */:
140730                         case 196 /* CallExpression */:
140731                         case 197 /* NewExpression */:
140732                         case 200 /* ParenthesizedExpression */:
140733                             return spanInPreviousNode(node);
140734                         // Default to parent node
140735                         default:
140736                             return spanInNode(node.parent);
140737                     }
140738                 }
140739                 function spanInColonToken(node) {
140740                     // Is this : specifying return annotation of the function declaration
140741                     if (ts.isFunctionLike(node.parent) ||
140742                         node.parent.kind === 281 /* PropertyAssignment */ ||
140743                         node.parent.kind === 156 /* Parameter */) {
140744                         return spanInPreviousNode(node);
140745                     }
140746                     return spanInNode(node.parent);
140747                 }
140748                 function spanInGreaterThanOrLessThanToken(node) {
140749                     if (node.parent.kind === 199 /* TypeAssertionExpression */) {
140750                         return spanInNextNode(node);
140751                     }
140752                     return spanInNode(node.parent);
140753                 }
140754                 function spanInWhileKeyword(node) {
140755                     if (node.parent.kind === 228 /* DoStatement */) {
140756                         // Set span on while expression
140757                         return textSpanEndingAtNextToken(node, node.parent.expression);
140758                     }
140759                     // Default to parent node
140760                     return spanInNode(node.parent);
140761                 }
140762                 function spanInOfKeyword(node) {
140763                     if (node.parent.kind === 232 /* ForOfStatement */) {
140764                         // Set using next token
140765                         return spanInNextNode(node);
140766                     }
140767                     // Default to parent node
140768                     return spanInNode(node.parent);
140769                 }
140770             }
140771         }
140772         BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation;
140773     })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {}));
140774 })(ts || (ts = {}));
140775 var ts;
140776 (function (ts) {
140777     /**
140778      * Transform one or more nodes using the supplied transformers.
140779      * @param source A single `Node` or an array of `Node` objects.
140780      * @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
140781      * @param compilerOptions Optional compiler options.
140782      */
140783     function transform(source, transformers, compilerOptions) {
140784         var diagnostics = [];
140785         compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217
140786         var nodes = ts.isArray(source) ? source : [source];
140787         var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
140788         result.diagnostics = ts.concatenate(result.diagnostics, diagnostics);
140789         return result;
140790     }
140791     ts.transform = transform;
140792 })(ts || (ts = {}));
140793 //
140794 // Copyright (c) Microsoft Corporation.  All rights reserved.
140795 //
140796 // Licensed under the Apache License, Version 2.0 (the "License");
140797 // you may not use this file except in compliance with the License.
140798 // You may obtain a copy of the License at
140799 //   http://www.apache.org/licenses/LICENSE-2.0
140800 //
140801 // Unless required by applicable law or agreed to in writing, software
140802 // distributed under the License is distributed on an "AS IS" BASIS,
140803 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
140804 // See the License for the specific language governing permissions and
140805 // limitations under the License.
140806 //
140807 /* @internal */
140808 var debugObjectHost = (function () { return this; })(); // eslint-disable-line prefer-const
140809 // We need to use 'null' to interface with the managed side.
140810 /* eslint-disable no-in-operator */
140811 /* @internal */
140812 var ts;
140813 (function (ts) {
140814     function logInternalError(logger, err) {
140815         if (logger) {
140816             logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
140817         }
140818     }
140819     var ScriptSnapshotShimAdapter = /** @class */ (function () {
140820         function ScriptSnapshotShimAdapter(scriptSnapshotShim) {
140821             this.scriptSnapshotShim = scriptSnapshotShim;
140822         }
140823         ScriptSnapshotShimAdapter.prototype.getText = function (start, end) {
140824             return this.scriptSnapshotShim.getText(start, end);
140825         };
140826         ScriptSnapshotShimAdapter.prototype.getLength = function () {
140827             return this.scriptSnapshotShim.getLength();
140828         };
140829         ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) {
140830             var oldSnapshotShim = oldSnapshot;
140831             var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
140832             /* eslint-disable no-null/no-null */
140833             if (encoded === null) {
140834                 return null; // TODO: GH#18217
140835             }
140836             /* eslint-enable no-null/no-null */
140837             var decoded = JSON.parse(encoded); // TODO: GH#18217
140838             return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
140839         };
140840         ScriptSnapshotShimAdapter.prototype.dispose = function () {
140841             // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments
140842             // 'in' does not have this effect
140843             if ("dispose" in this.scriptSnapshotShim) {
140844                 this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`?
140845             }
140846         };
140847         return ScriptSnapshotShimAdapter;
140848     }());
140849     var LanguageServiceShimHostAdapter = /** @class */ (function () {
140850         function LanguageServiceShimHostAdapter(shimHost) {
140851             var _this = this;
140852             this.shimHost = shimHost;
140853             this.loggingEnabled = false;
140854             this.tracingEnabled = false;
140855             // if shimHost is a COM object then property check will become method call with no arguments.
140856             // 'in' does not have this effect.
140857             if ("getModuleResolutionsForFile" in this.shimHost) {
140858                 this.resolveModuleNames = function (moduleNames, containingFile) {
140859                     var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217
140860                     return ts.map(moduleNames, function (name) {
140861                         var result = ts.getProperty(resolutionsInFile, name);
140862                         return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined;
140863                     });
140864                 };
140865             }
140866             if ("directoryExists" in this.shimHost) {
140867                 this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
140868             }
140869             if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
140870                 this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
140871                     var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217
140872                     return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); });
140873                 };
140874             }
140875         }
140876         LanguageServiceShimHostAdapter.prototype.log = function (s) {
140877             if (this.loggingEnabled) {
140878                 this.shimHost.log(s);
140879             }
140880         };
140881         LanguageServiceShimHostAdapter.prototype.trace = function (s) {
140882             if (this.tracingEnabled) {
140883                 this.shimHost.trace(s);
140884             }
140885         };
140886         LanguageServiceShimHostAdapter.prototype.error = function (s) {
140887             this.shimHost.error(s);
140888         };
140889         LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () {
140890             if (!this.shimHost.getProjectVersion) {
140891                 // shimmed host does not support getProjectVersion
140892                 return undefined; // TODO: GH#18217
140893             }
140894             return this.shimHost.getProjectVersion();
140895         };
140896         LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () {
140897             if (!this.shimHost.getTypeRootsVersion) {
140898                 return 0;
140899             }
140900             return this.shimHost.getTypeRootsVersion();
140901         };
140902         LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () {
140903             return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
140904         };
140905         LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () {
140906             var settingsJson = this.shimHost.getCompilationSettings();
140907             // eslint-disable-next-line no-null/no-null
140908             if (settingsJson === null || settingsJson === "") {
140909                 throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
140910             }
140911             var compilerOptions = JSON.parse(settingsJson);
140912             // permit language service to handle all files (filtering should be performed on the host side)
140913             compilerOptions.allowNonTsExtensions = true;
140914             return compilerOptions;
140915         };
140916         LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () {
140917             var encoded = this.shimHost.getScriptFileNames();
140918             return JSON.parse(encoded);
140919         };
140920         LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) {
140921             var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
140922             return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
140923         };
140924         LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) {
140925             if ("getScriptKind" in this.shimHost) {
140926                 return this.shimHost.getScriptKind(fileName); // TODO: GH#18217
140927             }
140928             else {
140929                 return 0 /* Unknown */;
140930             }
140931         };
140932         LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) {
140933             return this.shimHost.getScriptVersion(fileName);
140934         };
140935         LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () {
140936             /* eslint-disable no-null/no-null */
140937             var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
140938             if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
140939                 return null;
140940             }
140941             try {
140942                 return JSON.parse(diagnosticMessagesJson);
140943             }
140944             catch (e) {
140945                 this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
140946                 return null;
140947             }
140948             /* eslint-enable no-null/no-null */
140949         };
140950         LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () {
140951             var hostCancellationToken = this.shimHost.getCancellationToken();
140952             return new ts.ThrottledCancellationToken(hostCancellationToken);
140953         };
140954         LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () {
140955             return this.shimHost.getCurrentDirectory();
140956         };
140957         LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
140958             return JSON.parse(this.shimHost.getDirectories(path));
140959         };
140960         LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
140961             return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
140962         };
140963         LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) {
140964             var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
140965             return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
140966         };
140967         LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) {
140968             return this.shimHost.readFile(path, encoding);
140969         };
140970         LanguageServiceShimHostAdapter.prototype.fileExists = function (path) {
140971             return this.shimHost.fileExists(path);
140972         };
140973         return LanguageServiceShimHostAdapter;
140974     }());
140975     ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter;
140976     var CoreServicesShimHostAdapter = /** @class */ (function () {
140977         function CoreServicesShimHostAdapter(shimHost) {
140978             var _this = this;
140979             this.shimHost = shimHost;
140980             this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
140981             if ("directoryExists" in this.shimHost) {
140982                 this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); };
140983             }
140984             else {
140985                 this.directoryExists = undefined; // TODO: GH#18217
140986             }
140987             if ("realpath" in this.shimHost) {
140988                 this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217
140989             }
140990             else {
140991                 this.realpath = undefined; // TODO: GH#18217
140992             }
140993         }
140994         CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) {
140995             var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
140996             return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth));
140997         };
140998         CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) {
140999             return this.shimHost.fileExists(fileName);
141000         };
141001         CoreServicesShimHostAdapter.prototype.readFile = function (fileName) {
141002             return this.shimHost.readFile(fileName);
141003         };
141004         CoreServicesShimHostAdapter.prototype.getDirectories = function (path) {
141005             return JSON.parse(this.shimHost.getDirectories(path));
141006         };
141007         return CoreServicesShimHostAdapter;
141008     }());
141009     ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter;
141010     function simpleForwardCall(logger, actionDescription, action, logPerformance) {
141011         var start;
141012         if (logPerformance) {
141013             logger.log(actionDescription);
141014             start = ts.timestamp();
141015         }
141016         var result = action();
141017         if (logPerformance) {
141018             var end = ts.timestamp();
141019             logger.log(actionDescription + " completed in " + (end - start) + " msec");
141020             if (ts.isString(result)) {
141021                 var str = result;
141022                 if (str.length > 128) {
141023                     str = str.substring(0, 128) + "...";
141024                 }
141025                 logger.log("  result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
141026             }
141027         }
141028         return result;
141029     }
141030     function forwardJSONCall(logger, actionDescription, action, logPerformance) {
141031         return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance);
141032     }
141033     function forwardCall(logger, actionDescription, returnJson, action, logPerformance) {
141034         try {
141035             var result = simpleForwardCall(logger, actionDescription, action, logPerformance);
141036             return returnJson ? JSON.stringify({ result: result }) : result;
141037         }
141038         catch (err) {
141039             if (err instanceof ts.OperationCanceledException) {
141040                 return JSON.stringify({ canceled: true });
141041             }
141042             logInternalError(logger, err);
141043             err.description = actionDescription;
141044             return JSON.stringify({ error: err });
141045         }
141046     }
141047     var ShimBase = /** @class */ (function () {
141048         function ShimBase(factory) {
141049             this.factory = factory;
141050             factory.registerShim(this);
141051         }
141052         ShimBase.prototype.dispose = function (_dummy) {
141053             this.factory.unregisterShim(this);
141054         };
141055         return ShimBase;
141056     }());
141057     function realizeDiagnostics(diagnostics, newLine) {
141058         return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); });
141059     }
141060     ts.realizeDiagnostics = realizeDiagnostics;
141061     function realizeDiagnostic(diagnostic, newLine) {
141062         return {
141063             message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine),
141064             start: diagnostic.start,
141065             length: diagnostic.length,
141066             category: ts.diagnosticCategoryName(diagnostic),
141067             code: diagnostic.code,
141068             reportsUnnecessary: diagnostic.reportsUnnecessary,
141069         };
141070     }
141071     var LanguageServiceShimObject = /** @class */ (function (_super) {
141072         __extends(LanguageServiceShimObject, _super);
141073         function LanguageServiceShimObject(factory, host, languageService) {
141074             var _this = _super.call(this, factory) || this;
141075             _this.host = host;
141076             _this.languageService = languageService;
141077             _this.logPerformance = false;
141078             _this.logger = _this.host;
141079             return _this;
141080         }
141081         LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
141082             return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
141083         };
141084         /// DISPOSE
141085         /**
141086          * Ensure (almost) deterministic release of internal Javascript resources when
141087          * some external native objects holds onto us (e.g. Com/Interop).
141088          */
141089         LanguageServiceShimObject.prototype.dispose = function (dummy) {
141090             this.logger.log("dispose()");
141091             this.languageService.dispose();
141092             this.languageService = null; // eslint-disable-line no-null/no-null
141093             // force a GC
141094             if (debugObjectHost && debugObjectHost.CollectGarbage) {
141095                 debugObjectHost.CollectGarbage();
141096                 this.logger.log("CollectGarbage()");
141097             }
141098             this.logger = null; // eslint-disable-line no-null/no-null
141099             _super.prototype.dispose.call(this, dummy);
141100         };
141101         /// REFRESH
141102         /**
141103          * Update the list of scripts known to the compiler
141104          */
141105         LanguageServiceShimObject.prototype.refresh = function (throwOnError) {
141106             this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; } // eslint-disable-line no-null/no-null
141107             );
141108         };
141109         LanguageServiceShimObject.prototype.cleanupSemanticCache = function () {
141110             var _this = this;
141111             this.forwardJSONCall("cleanupSemanticCache()", function () {
141112                 _this.languageService.cleanupSemanticCache();
141113                 return null; // eslint-disable-line no-null/no-null
141114             });
141115         };
141116         LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) {
141117             var newLine = ts.getNewLineOrDefaultFromHost(this.host);
141118             return realizeDiagnostics(diagnostics, newLine);
141119         };
141120         LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) {
141121             var _this = this;
141122             return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); });
141123         };
141124         LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) {
141125             var _this = this;
141126             return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); });
141127         };
141128         LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) {
141129             var _this = this;
141130             return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", 
141131             // directly serialize the spans out to a string.  This is much faster to decode
141132             // on the managed side versus a full JSON array.
141133             function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); });
141134         };
141135         LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) {
141136             var _this = this;
141137             return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", 
141138             // directly serialize the spans out to a string.  This is much faster to decode
141139             // on the managed side versus a full JSON array.
141140             function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); });
141141         };
141142         LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) {
141143             var _this = this;
141144             return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () {
141145                 var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName);
141146                 return _this.realizeDiagnostics(diagnostics);
141147             });
141148         };
141149         LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) {
141150             var _this = this;
141151             return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () {
141152                 var diagnostics = _this.languageService.getSemanticDiagnostics(fileName);
141153                 return _this.realizeDiagnostics(diagnostics);
141154             });
141155         };
141156         LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) {
141157             var _this = this;
141158             return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); });
141159         };
141160         LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () {
141161             var _this = this;
141162             return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () {
141163                 var diagnostics = _this.languageService.getCompilerOptionsDiagnostics();
141164                 return _this.realizeDiagnostics(diagnostics);
141165             });
141166         };
141167         /// QUICKINFO
141168         /**
141169          * Computes a string representation of the type at the requested position
141170          * in the active file.
141171          */
141172         LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) {
141173             var _this = this;
141174             return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); });
141175         };
141176         /// NAMEORDOTTEDNAMESPAN
141177         /**
141178          * Computes span information of the name or dotted name at the requested position
141179          * in the active file.
141180          */
141181         LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) {
141182             var _this = this;
141183             return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); });
141184         };
141185         /**
141186          * STATEMENTSPAN
141187          * Computes span information of statement at the requested position in the active file.
141188          */
141189         LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) {
141190             var _this = this;
141191             return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); });
141192         };
141193         /// SIGNATUREHELP
141194         LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) {
141195             var _this = this;
141196             return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); });
141197         };
141198         /// GOTO DEFINITION
141199         /**
141200          * Computes the definition location and file for the symbol
141201          * at the requested position.
141202          */
141203         LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) {
141204             var _this = this;
141205             return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); });
141206         };
141207         /**
141208          * Computes the definition location and file for the symbol
141209          * at the requested position.
141210          */
141211         LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) {
141212             var _this = this;
141213             return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); });
141214         };
141215         /// GOTO Type
141216         /**
141217          * Computes the definition location of the type of the symbol
141218          * at the requested position.
141219          */
141220         LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) {
141221             var _this = this;
141222             return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); });
141223         };
141224         /// GOTO Implementation
141225         /**
141226          * Computes the implementation location of the symbol
141227          * at the requested position.
141228          */
141229         LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) {
141230             var _this = this;
141231             return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); });
141232         };
141233         LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) {
141234             var _this = this;
141235             return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); });
141236         };
141237         LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) {
141238             var _this = this;
141239             return this.forwardJSONCall("getSmartSelectionRange('" + fileName + "', " + position + ")", function () { return _this.languageService.getSmartSelectionRange(fileName, position); });
141240         };
141241         LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) {
141242             var _this = this;
141243             return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); });
141244         };
141245         /// GET BRACE MATCHING
141246         LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) {
141247             var _this = this;
141248             return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); });
141249         };
141250         LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) {
141251             var _this = this;
141252             return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); });
141253         };
141254         LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) {
141255             var _this = this;
141256             return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); });
141257         };
141258         /// GET SMART INDENT
141259         LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) {
141260             var _this = this;
141261             return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () {
141262                 var localOptions = JSON.parse(options);
141263                 return _this.languageService.getIndentationAtPosition(fileName, position, localOptions);
141264             });
141265         };
141266         /// GET REFERENCES
141267         LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) {
141268             var _this = this;
141269             return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); });
141270         };
141271         LanguageServiceShimObject.prototype.findReferences = function (fileName, position) {
141272             var _this = this;
141273             return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); });
141274         };
141275         LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) {
141276             var _this = this;
141277             return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); });
141278         };
141279         LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) {
141280             var _this = this;
141281             return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () {
141282                 var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
141283                 // workaround for VS document highlighting issue - keep only items from the initial file
141284                 var normalizedName = ts.toFileNameLowerCase(ts.normalizeSlashes(fileName));
141285                 return ts.filter(results, function (r) { return ts.toFileNameLowerCase(ts.normalizeSlashes(r.fileName)) === normalizedName; });
141286             });
141287         };
141288         /// COMPLETION LISTS
141289         /**
141290          * Get a string based representation of the completions
141291          * to provide at the given source position and providing a member completion
141292          * list if requested.
141293          */
141294         LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) {
141295             var _this = this;
141296             return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); });
141297         };
141298         /** Get a string based representation of a completion list entry details */
141299         LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) {
141300             var _this = this;
141301             return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () {
141302                 var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions);
141303                 return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences);
141304             });
141305         };
141306         LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) {
141307             var _this = this;
141308             return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () {
141309                 var localOptions = JSON.parse(options);
141310                 return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
141311             });
141312         };
141313         LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) {
141314             var _this = this;
141315             return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () {
141316                 var localOptions = JSON.parse(options);
141317                 return _this.languageService.getFormattingEditsForDocument(fileName, localOptions);
141318             });
141319         };
141320         LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) {
141321             var _this = this;
141322             return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () {
141323                 var localOptions = JSON.parse(options);
141324                 return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
141325             });
141326         };
141327         LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) {
141328             var _this = this;
141329             return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); });
141330         };
141331         /// NAVIGATE TO
141332         /** Return a list of symbols that are interesting to navigate to */
141333         LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) {
141334             var _this = this;
141335             return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); });
141336         };
141337         LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) {
141338             var _this = this;
141339             return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); });
141340         };
141341         LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) {
141342             var _this = this;
141343             return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); });
141344         };
141345         LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) {
141346             var _this = this;
141347             return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); });
141348         };
141349         LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) {
141350             var _this = this;
141351             return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); });
141352         };
141353         /// CALL HIERARCHY
141354         LanguageServiceShimObject.prototype.prepareCallHierarchy = function (fileName, position) {
141355             var _this = this;
141356             return this.forwardJSONCall("prepareCallHierarchy('" + fileName + "', " + position + ")", function () { return _this.languageService.prepareCallHierarchy(fileName, position); });
141357         };
141358         LanguageServiceShimObject.prototype.provideCallHierarchyIncomingCalls = function (fileName, position) {
141359             var _this = this;
141360             return this.forwardJSONCall("provideCallHierarchyIncomingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyIncomingCalls(fileName, position); });
141361         };
141362         LanguageServiceShimObject.prototype.provideCallHierarchyOutgoingCalls = function (fileName, position) {
141363             var _this = this;
141364             return this.forwardJSONCall("provideCallHierarchyOutgoingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyOutgoingCalls(fileName, position); });
141365         };
141366         /// Emit
141367         LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) {
141368             var _this = this;
141369             return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () {
141370                 var _a = _this.languageService.getEmitOutput(fileName), diagnostics = _a.diagnostics, rest = __rest(_a, ["diagnostics"]);
141371                 return __assign(__assign({}, rest), { diagnostics: _this.realizeDiagnostics(diagnostics) });
141372             });
141373         };
141374         LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) {
141375             var _this = this;
141376             return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", 
141377             /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance);
141378         };
141379         return LanguageServiceShimObject;
141380     }(ShimBase));
141381     function convertClassifications(classifications) {
141382         return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
141383     }
141384     var ClassifierShimObject = /** @class */ (function (_super) {
141385         __extends(ClassifierShimObject, _super);
141386         function ClassifierShimObject(factory, logger) {
141387             var _this = _super.call(this, factory) || this;
141388             _this.logger = logger;
141389             _this.logPerformance = false;
141390             _this.classifier = ts.createClassifier();
141391             return _this;
141392         }
141393         ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) {
141394             var _this = this;
141395             if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; }
141396             return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance);
141397         };
141398         /// COLORIZATION
141399         ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) {
141400             if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; }
141401             var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
141402             var result = "";
141403             for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) {
141404                 var item = _a[_i];
141405                 result += item.length + "\n";
141406                 result += item.classification + "\n";
141407             }
141408             result += classification.finalLexState;
141409             return result;
141410         };
141411         return ClassifierShimObject;
141412     }(ShimBase));
141413     var CoreServicesShimObject = /** @class */ (function (_super) {
141414         __extends(CoreServicesShimObject, _super);
141415         function CoreServicesShimObject(factory, logger, host) {
141416             var _this = _super.call(this, factory) || this;
141417             _this.logger = logger;
141418             _this.host = host;
141419             _this.logPerformance = false;
141420             return _this;
141421         }
141422         CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) {
141423             return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
141424         };
141425         CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) {
141426             var _this = this;
141427             return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () {
141428                 var compilerOptions = JSON.parse(compilerOptionsJson);
141429                 var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
141430                 var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
141431                 if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) {
141432                     resolvedFileName = undefined;
141433                 }
141434                 return {
141435                     resolvedFileName: resolvedFileName,
141436                     failedLookupLocations: result.failedLookupLocations
141437                 };
141438             });
141439         };
141440         CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) {
141441             var _this = this;
141442             return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () {
141443                 var compilerOptions = JSON.parse(compilerOptionsJson);
141444                 var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
141445                 return {
141446                     resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
141447                     primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
141448                     failedLookupLocations: result.failedLookupLocations
141449                 };
141450             });
141451         };
141452         CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) {
141453             var _this = this;
141454             return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () {
141455                 // for now treat files as JavaScript
141456                 var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
141457                 return {
141458                     referencedFiles: _this.convertFileReferences(result.referencedFiles),
141459                     importedFiles: _this.convertFileReferences(result.importedFiles),
141460                     ambientExternalModules: result.ambientExternalModules,
141461                     isLibFile: result.isLibFile,
141462                     typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives),
141463                     libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives)
141464                 };
141465             });
141466         };
141467         CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) {
141468             var _this = this;
141469             return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () {
141470                 var compilerOptions = JSON.parse(compilerOptionsJson);
141471                 return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host);
141472             });
141473         };
141474         CoreServicesShimObject.prototype.convertFileReferences = function (refs) {
141475             if (!refs) {
141476                 return undefined;
141477             }
141478             var result = [];
141479             for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
141480                 var ref = refs_1[_i];
141481                 result.push({
141482                     path: ts.normalizeSlashes(ref.fileName),
141483                     position: ref.pos,
141484                     length: ref.end - ref.pos
141485                 });
141486             }
141487             return result;
141488         };
141489         CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) {
141490             var _this = this;
141491             return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () {
141492                 var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot));
141493                 var normalizedFileName = ts.normalizeSlashes(fileName);
141494                 var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName);
141495                 return {
141496                     options: configFile.options,
141497                     typeAcquisition: configFile.typeAcquisition,
141498                     files: configFile.fileNames,
141499                     raw: configFile.raw,
141500                     errors: realizeDiagnostics(__spreadArrays(result.parseDiagnostics, configFile.errors), "\r\n")
141501                 };
141502             });
141503         };
141504         CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () {
141505             return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); });
141506         };
141507         CoreServicesShimObject.prototype.discoverTypings = function (discoverTypingsJson) {
141508             var _this = this;
141509             var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
141510             return this.forwardJSONCall("discoverTypings()", function () {
141511                 var info = JSON.parse(discoverTypingsJson);
141512                 if (_this.safeList === undefined) {
141513                     _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
141514                 }
141515                 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);
141516             });
141517         };
141518         return CoreServicesShimObject;
141519     }(ShimBase));
141520     var TypeScriptServicesFactory = /** @class */ (function () {
141521         function TypeScriptServicesFactory() {
141522             this._shims = [];
141523         }
141524         /*
141525          * Returns script API version.
141526          */
141527         TypeScriptServicesFactory.prototype.getServicesVersion = function () {
141528             return ts.servicesVersion;
141529         };
141530         TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) {
141531             try {
141532                 if (this.documentRegistry === undefined) {
141533                     this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
141534                 }
141535                 var hostAdapter = new LanguageServiceShimHostAdapter(host);
141536                 var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false);
141537                 return new LanguageServiceShimObject(this, host, languageService);
141538             }
141539             catch (err) {
141540                 logInternalError(host, err);
141541                 throw err;
141542             }
141543         };
141544         TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) {
141545             try {
141546                 return new ClassifierShimObject(this, logger);
141547             }
141548             catch (err) {
141549                 logInternalError(logger, err);
141550                 throw err;
141551             }
141552         };
141553         TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) {
141554             try {
141555                 var adapter = new CoreServicesShimHostAdapter(host);
141556                 return new CoreServicesShimObject(this, host, adapter);
141557             }
141558             catch (err) {
141559                 logInternalError(host, err);
141560                 throw err;
141561             }
141562         };
141563         TypeScriptServicesFactory.prototype.close = function () {
141564             // Forget all the registered shims
141565             ts.clear(this._shims);
141566             this.documentRegistry = undefined;
141567         };
141568         TypeScriptServicesFactory.prototype.registerShim = function (shim) {
141569             this._shims.push(shim);
141570         };
141571         TypeScriptServicesFactory.prototype.unregisterShim = function (shim) {
141572             for (var i = 0; i < this._shims.length; i++) {
141573                 if (this._shims[i] === shim) {
141574                     delete this._shims[i];
141575                     return;
141576                 }
141577             }
141578             throw new Error("Invalid operation");
141579         };
141580         return TypeScriptServicesFactory;
141581     }());
141582     ts.TypeScriptServicesFactory = TypeScriptServicesFactory;
141583 })(ts || (ts = {}));
141584 /* eslint-enable no-in-operator */
141585 // We polyfill `globalThis` here so re can reliably patch the global scope
141586 // in the contexts we want to in the same way across script and module formats
141587 /* eslint-enable no-var */
141588 ((function () {
141589     if (typeof globalThis === "object")
141590         return;
141591     try {
141592         Object.defineProperty(Object.prototype, "__magic__", {
141593             get: function () {
141594                 return this;
141595             },
141596             configurable: true
141597         });
141598         //@ts-ignore
141599         __magic__.globalThis = __magic__;
141600         // The previous line should have made `globalThis` globally
141601         // available, but it fails in Internet Explorer 10 and older.
141602         // Detect this failure and fall back.
141603         if (typeof globalThis === "undefined") {
141604             // Assume `window` exists.
141605             //@ts-ignore
141606             window.globalThis = window;
141607         }
141608         //@ts-ignore
141609         delete Object.prototype.__magic__;
141610     }
141611     catch (error) {
141612         // In IE8, Object.defineProperty only works on DOM objects.
141613         // If we hit this code path, assume `window` exists.
141614         //@ts-ignore
141615         window.globalThis = window;
141616     }
141617 })());
141618 // #endregion The polyfill ends here.
141619 // if `process` is undefined, we're probably not running in node - patch legacy members onto the global scope
141620 // @ts-ignore
141621 if (typeof process === "undefined" || process.browser) {
141622     /// TODO: this is used by VS, clean this up on both sides of the interface
141623     //@ts-ignore
141624     globalThis.TypeScript = globalThis.TypeScript || {};
141625     //@ts-ignore
141626     globalThis.TypeScript.Services = globalThis.TypeScript.Services || {};
141627     //@ts-ignore
141628     globalThis.TypeScript.Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
141629     // 'toolsVersion' gets consumed by the managed side, so it's not unused.
141630     // TODO: it should be moved into a namespace though.
141631     //@ts-ignore
141632     globalThis.toolsVersion = ts.versionMajorMinor;
141633 }
141634 if (typeof module !== "undefined" && module.exports) {
141635     module.exports = ts;
141636 }
141637
141638 //# sourceMappingURL=typescriptServices.js.map